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 "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68                        bool AllowTemplates=false)
69       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70         AllowClassTemplates(AllowTemplates) {
71     WantExpressionKeywords = false;
72     WantCXXNamedCasts = false;
73     WantRemainingKeywords = false;
74   }
75 
76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80       return (IsType || AllowedTemplate) &&
81              (AllowInvalidDecl || !ND->isInvalidDecl());
82     }
83     return !WantClassName && candidate.isKeyword();
84   }
85 
86  private:
87   bool AllowInvalidDecl;
88   bool WantClassName;
89   bool AllowClassTemplates;
90 };
91 
92 } // end anonymous namespace
93 
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96   switch (Kind) {
97   // FIXME: Take into account the current language when deciding whether a
98   // token kind is a valid type specifier
99   case tok::kw_short:
100   case tok::kw_long:
101   case tok::kw___int64:
102   case tok::kw___int128:
103   case tok::kw_signed:
104   case tok::kw_unsigned:
105   case tok::kw_void:
106   case tok::kw_char:
107   case tok::kw_int:
108   case tok::kw_half:
109   case tok::kw_float:
110   case tok::kw_double:
111   case tok::kw_wchar_t:
112   case tok::kw_bool:
113   case tok::kw___underlying_type:
114   case tok::kw___auto_type:
115     return true;
116 
117   case tok::annot_typename:
118   case tok::kw_char16_t:
119   case tok::kw_char32_t:
120   case tok::kw_typeof:
121   case tok::annot_decltype:
122   case tok::kw_decltype:
123     return getLangOpts().CPlusPlus;
124 
125   default:
126     break;
127   }
128 
129   return false;
130 }
131 
132 namespace {
133 enum class UnqualifiedTypeNameLookupResult {
134   NotFound,
135   FoundNonType,
136   FoundType
137 };
138 } // end anonymous namespace
139 
140 /// \brief Tries to perform unqualified lookup of the type decls in bases for
141 /// dependent class.
142 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
143 /// type decl, \a FoundType if only type decls are found.
144 static UnqualifiedTypeNameLookupResult
145 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
146                                 SourceLocation NameLoc,
147                                 const CXXRecordDecl *RD) {
148   if (!RD->hasDefinition())
149     return UnqualifiedTypeNameLookupResult::NotFound;
150   // Look for type decls in base classes.
151   UnqualifiedTypeNameLookupResult FoundTypeDecl =
152       UnqualifiedTypeNameLookupResult::NotFound;
153   for (const auto &Base : RD->bases()) {
154     const CXXRecordDecl *BaseRD = nullptr;
155     if (auto *BaseTT = Base.getType()->getAs<TagType>())
156       BaseRD = BaseTT->getAsCXXRecordDecl();
157     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
158       // Look for type decls in dependent base classes that have known primary
159       // templates.
160       if (!TST || !TST->isDependentType())
161         continue;
162       auto *TD = TST->getTemplateName().getAsTemplateDecl();
163       if (!TD)
164         continue;
165       auto *BasePrimaryTemplate =
166           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
167       if (!BasePrimaryTemplate)
168         continue;
169       BaseRD = BasePrimaryTemplate;
170     }
171     if (BaseRD) {
172       for (NamedDecl *ND : BaseRD->lookup(&II)) {
173         if (!isa<TypeDecl>(ND))
174           return UnqualifiedTypeNameLookupResult::FoundNonType;
175         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
176       }
177       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
178         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
179         case UnqualifiedTypeNameLookupResult::FoundNonType:
180           return UnqualifiedTypeNameLookupResult::FoundNonType;
181         case UnqualifiedTypeNameLookupResult::FoundType:
182           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
183           break;
184         case UnqualifiedTypeNameLookupResult::NotFound:
185           break;
186         }
187       }
188     }
189   }
190 
191   return FoundTypeDecl;
192 }
193 
194 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
195                                                       const IdentifierInfo &II,
196                                                       SourceLocation NameLoc) {
197   // Lookup in the parent class template context, if any.
198   const CXXRecordDecl *RD = nullptr;
199   UnqualifiedTypeNameLookupResult FoundTypeDecl =
200       UnqualifiedTypeNameLookupResult::NotFound;
201   for (DeclContext *DC = S.CurContext;
202        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
203        DC = DC->getParent()) {
204     // Look for type decls in dependent base classes that have known primary
205     // templates.
206     RD = dyn_cast<CXXRecordDecl>(DC);
207     if (RD && RD->getDescribedClassTemplate())
208       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
209   }
210   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
211     return nullptr;
212 
213   // We found some types in dependent base classes.  Recover as if the user
214   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
215   // lookup during template instantiation.
216   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
217 
218   ASTContext &Context = S.Context;
219   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
220                                           cast<Type>(Context.getRecordType(RD)));
221   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
222 
223   CXXScopeSpec SS;
224   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
225 
226   TypeLocBuilder Builder;
227   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
228   DepTL.setNameLoc(NameLoc);
229   DepTL.setElaboratedKeywordLoc(SourceLocation());
230   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
231   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
232 }
233 
234 /// \brief If the identifier refers to a type name within this scope,
235 /// return the declaration of that type.
236 ///
237 /// This routine performs ordinary name lookup of the identifier II
238 /// within the given scope, with optional C++ scope specifier SS, to
239 /// determine whether the name refers to a type. If so, returns an
240 /// opaque pointer (actually a QualType) corresponding to that
241 /// type. Otherwise, returns NULL.
242 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
243                              Scope *S, CXXScopeSpec *SS,
244                              bool isClassName, bool HasTrailingDot,
245                              ParsedType ObjectTypePtr,
246                              bool IsCtorOrDtorName,
247                              bool WantNontrivialTypeSourceInfo,
248                              IdentifierInfo **CorrectedII) {
249   // Determine where we will perform name lookup.
250   DeclContext *LookupCtx = nullptr;
251   if (ObjectTypePtr) {
252     QualType ObjectType = ObjectTypePtr.get();
253     if (ObjectType->isRecordType())
254       LookupCtx = computeDeclContext(ObjectType);
255   } else if (SS && SS->isNotEmpty()) {
256     LookupCtx = computeDeclContext(*SS, false);
257 
258     if (!LookupCtx) {
259       if (isDependentScopeSpecifier(*SS)) {
260         // C++ [temp.res]p3:
261         //   A qualified-id that refers to a type and in which the
262         //   nested-name-specifier depends on a template-parameter (14.6.2)
263         //   shall be prefixed by the keyword typename to indicate that the
264         //   qualified-id denotes a type, forming an
265         //   elaborated-type-specifier (7.1.5.3).
266         //
267         // We therefore do not perform any name lookup if the result would
268         // refer to a member of an unknown specialization.
269         if (!isClassName && !IsCtorOrDtorName)
270           return nullptr;
271 
272         // We know from the grammar that this name refers to a type,
273         // so build a dependent node to describe the type.
274         if (WantNontrivialTypeSourceInfo)
275           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
276 
277         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
278         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
279                                        II, NameLoc);
280         return ParsedType::make(T);
281       }
282 
283       return nullptr;
284     }
285 
286     if (!LookupCtx->isDependentContext() &&
287         RequireCompleteDeclContext(*SS, LookupCtx))
288       return nullptr;
289   }
290 
291   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
292   // lookup for class-names.
293   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
294                                       LookupOrdinaryName;
295   LookupResult Result(*this, &II, NameLoc, Kind);
296   if (LookupCtx) {
297     // Perform "qualified" name lookup into the declaration context we
298     // computed, which is either the type of the base of a member access
299     // expression or the declaration context associated with a prior
300     // nested-name-specifier.
301     LookupQualifiedName(Result, LookupCtx);
302 
303     if (ObjectTypePtr && Result.empty()) {
304       // C++ [basic.lookup.classref]p3:
305       //   If the unqualified-id is ~type-name, the type-name is looked up
306       //   in the context of the entire postfix-expression. If the type T of
307       //   the object expression is of a class type C, the type-name is also
308       //   looked up in the scope of class C. At least one of the lookups shall
309       //   find a name that refers to (possibly cv-qualified) T.
310       LookupName(Result, S);
311     }
312   } else {
313     // Perform unqualified name lookup.
314     LookupName(Result, S);
315 
316     // For unqualified lookup in a class template in MSVC mode, look into
317     // dependent base classes where the primary class template is known.
318     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
319       if (ParsedType TypeInBase =
320               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
321         return TypeInBase;
322     }
323   }
324 
325   NamedDecl *IIDecl = nullptr;
326   switch (Result.getResultKind()) {
327   case LookupResult::NotFound:
328   case LookupResult::NotFoundInCurrentInstantiation:
329     if (CorrectedII) {
330       TypoCorrection Correction = CorrectTypo(
331           Result.getLookupNameInfo(), Kind, S, SS,
332           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
333           CTK_ErrorRecovery);
334       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
335       TemplateTy Template;
336       bool MemberOfUnknownSpecialization;
337       UnqualifiedId TemplateName;
338       TemplateName.setIdentifier(NewII, NameLoc);
339       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
340       CXXScopeSpec NewSS, *NewSSPtr = SS;
341       if (SS && NNS) {
342         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
343         NewSSPtr = &NewSS;
344       }
345       if (Correction && (NNS || NewII != &II) &&
346           // Ignore a correction to a template type as the to-be-corrected
347           // identifier is not a template (typo correction for template names
348           // is handled elsewhere).
349           !(getLangOpts().CPlusPlus && NewSSPtr &&
350             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
351                            Template, MemberOfUnknownSpecialization))) {
352         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
353                                     isClassName, HasTrailingDot, ObjectTypePtr,
354                                     IsCtorOrDtorName,
355                                     WantNontrivialTypeSourceInfo);
356         if (Ty) {
357           diagnoseTypo(Correction,
358                        PDiag(diag::err_unknown_type_or_class_name_suggest)
359                          << Result.getLookupName() << isClassName);
360           if (SS && NNS)
361             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
362           *CorrectedII = NewII;
363           return Ty;
364         }
365       }
366     }
367     // If typo correction failed or was not performed, fall through
368   case LookupResult::FoundOverloaded:
369   case LookupResult::FoundUnresolvedValue:
370     Result.suppressDiagnostics();
371     return nullptr;
372 
373   case LookupResult::Ambiguous:
374     // Recover from type-hiding ambiguities by hiding the type.  We'll
375     // do the lookup again when looking for an object, and we can
376     // diagnose the error then.  If we don't do this, then the error
377     // about hiding the type will be immediately followed by an error
378     // that only makes sense if the identifier was treated like a type.
379     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
380       Result.suppressDiagnostics();
381       return nullptr;
382     }
383 
384     // Look to see if we have a type anywhere in the list of results.
385     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
386          Res != ResEnd; ++Res) {
387       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
388         if (!IIDecl ||
389             (*Res)->getLocation().getRawEncoding() <
390               IIDecl->getLocation().getRawEncoding())
391           IIDecl = *Res;
392       }
393     }
394 
395     if (!IIDecl) {
396       // None of the entities we found is a type, so there is no way
397       // to even assume that the result is a type. In this case, don't
398       // complain about the ambiguity. The parser will either try to
399       // perform this lookup again (e.g., as an object name), which
400       // will produce the ambiguity, or will complain that it expected
401       // a type name.
402       Result.suppressDiagnostics();
403       return nullptr;
404     }
405 
406     // We found a type within the ambiguous lookup; diagnose the
407     // ambiguity and then return that type. This might be the right
408     // answer, or it might not be, but it suppresses any attempt to
409     // perform the name lookup again.
410     break;
411 
412   case LookupResult::Found:
413     IIDecl = Result.getFoundDecl();
414     break;
415   }
416 
417   assert(IIDecl && "Didn't find decl");
418 
419   QualType T;
420   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
421     DiagnoseUseOfDecl(IIDecl, NameLoc);
422 
423     T = Context.getTypeDeclType(TD);
424     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
425 
426     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
427     // constructor or destructor name (in such a case, the scope specifier
428     // will be attached to the enclosing Expr or Decl node).
429     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
430       if (WantNontrivialTypeSourceInfo) {
431         // Construct a type with type-source information.
432         TypeLocBuilder Builder;
433         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
434 
435         T = getElaboratedType(ETK_None, *SS, T);
436         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
437         ElabTL.setElaboratedKeywordLoc(SourceLocation());
438         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
439         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
440       } else {
441         T = getElaboratedType(ETK_None, *SS, T);
442       }
443     }
444   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
445     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
446     if (!HasTrailingDot)
447       T = Context.getObjCInterfaceType(IDecl);
448   }
449 
450   if (T.isNull()) {
451     // If it's not plausibly a type, suppress diagnostics.
452     Result.suppressDiagnostics();
453     return nullptr;
454   }
455   return ParsedType::make(T);
456 }
457 
458 // Builds a fake NNS for the given decl context.
459 static NestedNameSpecifier *
460 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
461   for (;; DC = DC->getLookupParent()) {
462     DC = DC->getPrimaryContext();
463     auto *ND = dyn_cast<NamespaceDecl>(DC);
464     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
465       return NestedNameSpecifier::Create(Context, nullptr, ND);
466     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
467       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
468                                          RD->getTypeForDecl());
469     else if (isa<TranslationUnitDecl>(DC))
470       return NestedNameSpecifier::GlobalSpecifier(Context);
471   }
472   llvm_unreachable("something isn't in TU scope?");
473 }
474 
475 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
476                                                 SourceLocation NameLoc) {
477   // Accepting an undeclared identifier as a default argument for a template
478   // type parameter is a Microsoft extension.
479   Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
480 
481   // Build a fake DependentNameType that will perform lookup into CurContext at
482   // instantiation time.  The name specifier isn't dependent, so template
483   // instantiation won't transform it.  It will retry the lookup, however.
484   NestedNameSpecifier *NNS =
485       synthesizeCurrentNestedNameSpecifier(Context, CurContext);
486   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
487 
488   // Build type location information.  We synthesized the qualifier, so we have
489   // to build a fake NestedNameSpecifierLoc.
490   NestedNameSpecifierLocBuilder NNSLocBuilder;
491   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
492   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
493 
494   TypeLocBuilder Builder;
495   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
496   DepTL.setNameLoc(NameLoc);
497   DepTL.setElaboratedKeywordLoc(SourceLocation());
498   DepTL.setQualifierLoc(QualifierLoc);
499   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
500 }
501 
502 /// isTagName() - This method is called *for error recovery purposes only*
503 /// to determine if the specified name is a valid tag name ("struct foo").  If
504 /// so, this returns the TST for the tag corresponding to it (TST_enum,
505 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
506 /// cases in C where the user forgot to specify the tag.
507 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
508   // Do a tag name lookup in this scope.
509   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
510   LookupName(R, S, false);
511   R.suppressDiagnostics();
512   if (R.getResultKind() == LookupResult::Found)
513     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
514       switch (TD->getTagKind()) {
515       case TTK_Struct: return DeclSpec::TST_struct;
516       case TTK_Interface: return DeclSpec::TST_interface;
517       case TTK_Union:  return DeclSpec::TST_union;
518       case TTK_Class:  return DeclSpec::TST_class;
519       case TTK_Enum:   return DeclSpec::TST_enum;
520       }
521     }
522 
523   return DeclSpec::TST_unspecified;
524 }
525 
526 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
527 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
528 /// then downgrade the missing typename error to a warning.
529 /// This is needed for MSVC compatibility; Example:
530 /// @code
531 /// template<class T> class A {
532 /// public:
533 ///   typedef int TYPE;
534 /// };
535 /// template<class T> class B : public A<T> {
536 /// public:
537 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
538 /// };
539 /// @endcode
540 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
541   if (CurContext->isRecord()) {
542     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
543       return true;
544 
545     const Type *Ty = SS->getScopeRep()->getAsType();
546 
547     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
548     for (const auto &Base : RD->bases())
549       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
550         return true;
551     return S->isFunctionPrototypeScope();
552   }
553   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
554 }
555 
556 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
557                                    SourceLocation IILoc,
558                                    Scope *S,
559                                    CXXScopeSpec *SS,
560                                    ParsedType &SuggestedType,
561                                    bool AllowClassTemplates) {
562   // We don't have anything to suggest (yet).
563   SuggestedType = nullptr;
564 
565   // There may have been a typo in the name of the type. Look up typo
566   // results, in case we have something that we can suggest.
567   if (TypoCorrection Corrected =
568           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
569                       llvm::make_unique<TypeNameValidatorCCC>(
570                           false, false, AllowClassTemplates),
571                       CTK_ErrorRecovery)) {
572     if (Corrected.isKeyword()) {
573       // We corrected to a keyword.
574       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
575       II = Corrected.getCorrectionAsIdentifierInfo();
576     } else {
577       // We found a similarly-named type or interface; suggest that.
578       if (!SS || !SS->isSet()) {
579         diagnoseTypo(Corrected,
580                      PDiag(diag::err_unknown_typename_suggest) << II);
581       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
582         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
583         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
584                                 II->getName().equals(CorrectedStr);
585         diagnoseTypo(Corrected,
586                      PDiag(diag::err_unknown_nested_typename_suggest)
587                        << II << DC << DroppedSpecifier << SS->getRange());
588       } else {
589         llvm_unreachable("could not have corrected a typo here");
590       }
591 
592       CXXScopeSpec tmpSS;
593       if (Corrected.getCorrectionSpecifier())
594         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
595                           SourceRange(IILoc));
596       SuggestedType =
597           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
598                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
599                       /*IsCtorOrDtorName=*/false,
600                       /*NonTrivialTypeSourceInfo=*/true);
601     }
602     return;
603   }
604 
605   if (getLangOpts().CPlusPlus) {
606     // See if II is a class template that the user forgot to pass arguments to.
607     UnqualifiedId Name;
608     Name.setIdentifier(II, IILoc);
609     CXXScopeSpec EmptySS;
610     TemplateTy TemplateResult;
611     bool MemberOfUnknownSpecialization;
612     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
613                        Name, nullptr, true, TemplateResult,
614                        MemberOfUnknownSpecialization) == TNK_Type_template) {
615       TemplateName TplName = TemplateResult.get();
616       Diag(IILoc, diag::err_template_missing_args) << TplName;
617       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
618         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
619           << TplDecl->getTemplateParameters()->getSourceRange();
620       }
621       return;
622     }
623   }
624 
625   // FIXME: Should we move the logic that tries to recover from a missing tag
626   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
627 
628   if (!SS || (!SS->isSet() && !SS->isInvalid()))
629     Diag(IILoc, diag::err_unknown_typename) << II;
630   else if (DeclContext *DC = computeDeclContext(*SS, false))
631     Diag(IILoc, diag::err_typename_nested_not_found)
632       << II << DC << SS->getRange();
633   else if (isDependentScopeSpecifier(*SS)) {
634     unsigned DiagID = diag::err_typename_missing;
635     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
636       DiagID = diag::ext_typename_missing;
637 
638     Diag(SS->getRange().getBegin(), DiagID)
639       << SS->getScopeRep() << II->getName()
640       << SourceRange(SS->getRange().getBegin(), IILoc)
641       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
642     SuggestedType = ActOnTypenameType(S, SourceLocation(),
643                                       *SS, *II, IILoc).get();
644   } else {
645     assert(SS && SS->isInvalid() &&
646            "Invalid scope specifier has already been diagnosed");
647   }
648 }
649 
650 /// \brief Determine whether the given result set contains either a type name
651 /// or
652 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
653   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
654                        NextToken.is(tok::less);
655 
656   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
657     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
658       return true;
659 
660     if (CheckTemplate && isa<TemplateDecl>(*I))
661       return true;
662   }
663 
664   return false;
665 }
666 
667 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
668                                     Scope *S, CXXScopeSpec &SS,
669                                     IdentifierInfo *&Name,
670                                     SourceLocation NameLoc) {
671   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
672   SemaRef.LookupParsedName(R, S, &SS);
673   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
674     StringRef FixItTagName;
675     switch (Tag->getTagKind()) {
676       case TTK_Class:
677         FixItTagName = "class ";
678         break;
679 
680       case TTK_Enum:
681         FixItTagName = "enum ";
682         break;
683 
684       case TTK_Struct:
685         FixItTagName = "struct ";
686         break;
687 
688       case TTK_Interface:
689         FixItTagName = "__interface ";
690         break;
691 
692       case TTK_Union:
693         FixItTagName = "union ";
694         break;
695     }
696 
697     StringRef TagName = FixItTagName.drop_back();
698     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
699       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
700       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
701 
702     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
703          I != IEnd; ++I)
704       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
705         << Name << TagName;
706 
707     // Replace lookup results with just the tag decl.
708     Result.clear(Sema::LookupTagName);
709     SemaRef.LookupParsedName(Result, S, &SS);
710     return true;
711   }
712 
713   return false;
714 }
715 
716 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
717 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
718                                   QualType T, SourceLocation NameLoc) {
719   ASTContext &Context = S.Context;
720 
721   TypeLocBuilder Builder;
722   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
723 
724   T = S.getElaboratedType(ETK_None, SS, T);
725   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
726   ElabTL.setElaboratedKeywordLoc(SourceLocation());
727   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
728   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
729 }
730 
731 Sema::NameClassification
732 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
733                    SourceLocation NameLoc, const Token &NextToken,
734                    bool IsAddressOfOperand,
735                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
736   DeclarationNameInfo NameInfo(Name, NameLoc);
737   ObjCMethodDecl *CurMethod = getCurMethodDecl();
738 
739   if (NextToken.is(tok::coloncolon)) {
740     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
741                                 QualType(), false, SS, nullptr, false);
742   }
743 
744   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
745   LookupParsedName(Result, S, &SS, !CurMethod);
746 
747   // For unqualified lookup in a class template in MSVC mode, look into
748   // dependent base classes where the primary class template is known.
749   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
750     if (ParsedType TypeInBase =
751             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
752       return TypeInBase;
753   }
754 
755   // Perform lookup for Objective-C instance variables (including automatically
756   // synthesized instance variables), if we're in an Objective-C method.
757   // FIXME: This lookup really, really needs to be folded in to the normal
758   // unqualified lookup mechanism.
759   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
760     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
761     if (E.get() || E.isInvalid())
762       return E;
763   }
764 
765   bool SecondTry = false;
766   bool IsFilteredTemplateName = false;
767 
768 Corrected:
769   switch (Result.getResultKind()) {
770   case LookupResult::NotFound:
771     // If an unqualified-id is followed by a '(', then we have a function
772     // call.
773     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
774       // In C++, this is an ADL-only call.
775       // FIXME: Reference?
776       if (getLangOpts().CPlusPlus)
777         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
778 
779       // C90 6.3.2.2:
780       //   If the expression that precedes the parenthesized argument list in a
781       //   function call consists solely of an identifier, and if no
782       //   declaration is visible for this identifier, the identifier is
783       //   implicitly declared exactly as if, in the innermost block containing
784       //   the function call, the declaration
785       //
786       //     extern int identifier ();
787       //
788       //   appeared.
789       //
790       // We also allow this in C99 as an extension.
791       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
792         Result.addDecl(D);
793         Result.resolveKind();
794         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
795       }
796     }
797 
798     // In C, we first see whether there is a tag type by the same name, in
799     // which case it's likely that the user just forgot to write "enum",
800     // "struct", or "union".
801     if (!getLangOpts().CPlusPlus && !SecondTry &&
802         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
803       break;
804     }
805 
806     // Perform typo correction to determine if there is another name that is
807     // close to this name.
808     if (!SecondTry && CCC) {
809       SecondTry = true;
810       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
811                                                  Result.getLookupKind(), S,
812                                                  &SS, std::move(CCC),
813                                                  CTK_ErrorRecovery)) {
814         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
815         unsigned QualifiedDiag = diag::err_no_member_suggest;
816 
817         NamedDecl *FirstDecl = Corrected.getFoundDecl();
818         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
819         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
820             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
821           UnqualifiedDiag = diag::err_no_template_suggest;
822           QualifiedDiag = diag::err_no_member_template_suggest;
823         } else if (UnderlyingFirstDecl &&
824                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
825                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
826                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
827           UnqualifiedDiag = diag::err_unknown_typename_suggest;
828           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
829         }
830 
831         if (SS.isEmpty()) {
832           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
833         } else {// FIXME: is this even reachable? Test it.
834           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
835           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
836                                   Name->getName().equals(CorrectedStr);
837           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
838                                     << Name << computeDeclContext(SS, false)
839                                     << DroppedSpecifier << SS.getRange());
840         }
841 
842         // Update the name, so that the caller has the new name.
843         Name = Corrected.getCorrectionAsIdentifierInfo();
844 
845         // Typo correction corrected to a keyword.
846         if (Corrected.isKeyword())
847           return Name;
848 
849         // Also update the LookupResult...
850         // FIXME: This should probably go away at some point
851         Result.clear();
852         Result.setLookupName(Corrected.getCorrection());
853         if (FirstDecl)
854           Result.addDecl(FirstDecl);
855 
856         // If we found an Objective-C instance variable, let
857         // LookupInObjCMethod build the appropriate expression to
858         // reference the ivar.
859         // FIXME: This is a gross hack.
860         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
861           Result.clear();
862           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
863           return E;
864         }
865 
866         goto Corrected;
867       }
868     }
869 
870     // We failed to correct; just fall through and let the parser deal with it.
871     Result.suppressDiagnostics();
872     return NameClassification::Unknown();
873 
874   case LookupResult::NotFoundInCurrentInstantiation: {
875     // We performed name lookup into the current instantiation, and there were
876     // dependent bases, so we treat this result the same way as any other
877     // dependent nested-name-specifier.
878 
879     // C++ [temp.res]p2:
880     //   A name used in a template declaration or definition and that is
881     //   dependent on a template-parameter is assumed not to name a type
882     //   unless the applicable name lookup finds a type name or the name is
883     //   qualified by the keyword typename.
884     //
885     // FIXME: If the next token is '<', we might want to ask the parser to
886     // perform some heroics to see if we actually have a
887     // template-argument-list, which would indicate a missing 'template'
888     // keyword here.
889     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
890                                       NameInfo, IsAddressOfOperand,
891                                       /*TemplateArgs=*/nullptr);
892   }
893 
894   case LookupResult::Found:
895   case LookupResult::FoundOverloaded:
896   case LookupResult::FoundUnresolvedValue:
897     break;
898 
899   case LookupResult::Ambiguous:
900     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
901         hasAnyAcceptableTemplateNames(Result)) {
902       // C++ [temp.local]p3:
903       //   A lookup that finds an injected-class-name (10.2) can result in an
904       //   ambiguity in certain cases (for example, if it is found in more than
905       //   one base class). If all of the injected-class-names that are found
906       //   refer to specializations of the same class template, and if the name
907       //   is followed by a template-argument-list, the reference refers to the
908       //   class template itself and not a specialization thereof, and is not
909       //   ambiguous.
910       //
911       // This filtering can make an ambiguous result into an unambiguous one,
912       // so try again after filtering out template names.
913       FilterAcceptableTemplateNames(Result);
914       if (!Result.isAmbiguous()) {
915         IsFilteredTemplateName = true;
916         break;
917       }
918     }
919 
920     // Diagnose the ambiguity and return an error.
921     return NameClassification::Error();
922   }
923 
924   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
925       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
926     // C++ [temp.names]p3:
927     //   After name lookup (3.4) finds that a name is a template-name or that
928     //   an operator-function-id or a literal- operator-id refers to a set of
929     //   overloaded functions any member of which is a function template if
930     //   this is followed by a <, the < is always taken as the delimiter of a
931     //   template-argument-list and never as the less-than operator.
932     if (!IsFilteredTemplateName)
933       FilterAcceptableTemplateNames(Result);
934 
935     if (!Result.empty()) {
936       bool IsFunctionTemplate;
937       bool IsVarTemplate;
938       TemplateName Template;
939       if (Result.end() - Result.begin() > 1) {
940         IsFunctionTemplate = true;
941         Template = Context.getOverloadedTemplateName(Result.begin(),
942                                                      Result.end());
943       } else {
944         TemplateDecl *TD
945           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
946         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
947         IsVarTemplate = isa<VarTemplateDecl>(TD);
948 
949         if (SS.isSet() && !SS.isInvalid())
950           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
951                                                     /*TemplateKeyword=*/false,
952                                                       TD);
953         else
954           Template = TemplateName(TD);
955       }
956 
957       if (IsFunctionTemplate) {
958         // Function templates always go through overload resolution, at which
959         // point we'll perform the various checks (e.g., accessibility) we need
960         // to based on which function we selected.
961         Result.suppressDiagnostics();
962 
963         return NameClassification::FunctionTemplate(Template);
964       }
965 
966       return IsVarTemplate ? NameClassification::VarTemplate(Template)
967                            : NameClassification::TypeTemplate(Template);
968     }
969   }
970 
971   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
972   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
973     DiagnoseUseOfDecl(Type, NameLoc);
974     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
975     QualType T = Context.getTypeDeclType(Type);
976     if (SS.isNotEmpty())
977       return buildNestedType(*this, SS, T, NameLoc);
978     return ParsedType::make(T);
979   }
980 
981   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
982   if (!Class) {
983     // FIXME: It's unfortunate that we don't have a Type node for handling this.
984     if (ObjCCompatibleAliasDecl *Alias =
985             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
986       Class = Alias->getClassInterface();
987   }
988 
989   if (Class) {
990     DiagnoseUseOfDecl(Class, NameLoc);
991 
992     if (NextToken.is(tok::period)) {
993       // Interface. <something> is parsed as a property reference expression.
994       // Just return "unknown" as a fall-through for now.
995       Result.suppressDiagnostics();
996       return NameClassification::Unknown();
997     }
998 
999     QualType T = Context.getObjCInterfaceType(Class);
1000     return ParsedType::make(T);
1001   }
1002 
1003   // We can have a type template here if we're classifying a template argument.
1004   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1005     return NameClassification::TypeTemplate(
1006         TemplateName(cast<TemplateDecl>(FirstDecl)));
1007 
1008   // Check for a tag type hidden by a non-type decl in a few cases where it
1009   // seems likely a type is wanted instead of the non-type that was found.
1010   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1011   if ((NextToken.is(tok::identifier) ||
1012        (NextIsOp &&
1013         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1014       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1015     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1016     DiagnoseUseOfDecl(Type, NameLoc);
1017     QualType T = Context.getTypeDeclType(Type);
1018     if (SS.isNotEmpty())
1019       return buildNestedType(*this, SS, T, NameLoc);
1020     return ParsedType::make(T);
1021   }
1022 
1023   if (FirstDecl->isCXXClassMember())
1024     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1025                                            nullptr, S);
1026 
1027   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1028   return BuildDeclarationNameExpr(SS, Result, ADL);
1029 }
1030 
1031 // Determines the context to return to after temporarily entering a
1032 // context.  This depends in an unnecessarily complicated way on the
1033 // exact ordering of callbacks from the parser.
1034 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1035 
1036   // Functions defined inline within classes aren't parsed until we've
1037   // finished parsing the top-level class, so the top-level class is
1038   // the context we'll need to return to.
1039   // A Lambda call operator whose parent is a class must not be treated
1040   // as an inline member function.  A Lambda can be used legally
1041   // either as an in-class member initializer or a default argument.  These
1042   // are parsed once the class has been marked complete and so the containing
1043   // context would be the nested class (when the lambda is defined in one);
1044   // If the class is not complete, then the lambda is being used in an
1045   // ill-formed fashion (such as to specify the width of a bit-field, or
1046   // in an array-bound) - in which case we still want to return the
1047   // lexically containing DC (which could be a nested class).
1048   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1049     DC = DC->getLexicalParent();
1050 
1051     // A function not defined within a class will always return to its
1052     // lexical context.
1053     if (!isa<CXXRecordDecl>(DC))
1054       return DC;
1055 
1056     // A C++ inline method/friend is parsed *after* the topmost class
1057     // it was declared in is fully parsed ("complete");  the topmost
1058     // class is the context we need to return to.
1059     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1060       DC = RD;
1061 
1062     // Return the declaration context of the topmost class the inline method is
1063     // declared in.
1064     return DC;
1065   }
1066 
1067   return DC->getLexicalParent();
1068 }
1069 
1070 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1071   assert(getContainingDC(DC) == CurContext &&
1072       "The next DeclContext should be lexically contained in the current one.");
1073   CurContext = DC;
1074   S->setEntity(DC);
1075 }
1076 
1077 void Sema::PopDeclContext() {
1078   assert(CurContext && "DeclContext imbalance!");
1079 
1080   CurContext = getContainingDC(CurContext);
1081   assert(CurContext && "Popped translation unit!");
1082 }
1083 
1084 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1085                                                                     Decl *D) {
1086   // Unlike PushDeclContext, the context to which we return is not necessarily
1087   // the containing DC of TD, because the new context will be some pre-existing
1088   // TagDecl definition instead of a fresh one.
1089   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1090   CurContext = cast<TagDecl>(D)->getDefinition();
1091   assert(CurContext && "skipping definition of undefined tag");
1092   // Start lookups from the parent of the current context; we don't want to look
1093   // into the pre-existing complete definition.
1094   S->setEntity(CurContext->getLookupParent());
1095   return Result;
1096 }
1097 
1098 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1099   CurContext = static_cast<decltype(CurContext)>(Context);
1100 }
1101 
1102 /// EnterDeclaratorContext - Used when we must lookup names in the context
1103 /// of a declarator's nested name specifier.
1104 ///
1105 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1106   // C++0x [basic.lookup.unqual]p13:
1107   //   A name used in the definition of a static data member of class
1108   //   X (after the qualified-id of the static member) is looked up as
1109   //   if the name was used in a member function of X.
1110   // C++0x [basic.lookup.unqual]p14:
1111   //   If a variable member of a namespace is defined outside of the
1112   //   scope of its namespace then any name used in the definition of
1113   //   the variable member (after the declarator-id) is looked up as
1114   //   if the definition of the variable member occurred in its
1115   //   namespace.
1116   // Both of these imply that we should push a scope whose context
1117   // is the semantic context of the declaration.  We can't use
1118   // PushDeclContext here because that context is not necessarily
1119   // lexically contained in the current context.  Fortunately,
1120   // the containing scope should have the appropriate information.
1121 
1122   assert(!S->getEntity() && "scope already has entity");
1123 
1124 #ifndef NDEBUG
1125   Scope *Ancestor = S->getParent();
1126   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1127   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1128 #endif
1129 
1130   CurContext = DC;
1131   S->setEntity(DC);
1132 }
1133 
1134 void Sema::ExitDeclaratorContext(Scope *S) {
1135   assert(S->getEntity() == CurContext && "Context imbalance!");
1136 
1137   // Switch back to the lexical context.  The safety of this is
1138   // enforced by an assert in EnterDeclaratorContext.
1139   Scope *Ancestor = S->getParent();
1140   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1141   CurContext = Ancestor->getEntity();
1142 
1143   // We don't need to do anything with the scope, which is going to
1144   // disappear.
1145 }
1146 
1147 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1148   // We assume that the caller has already called
1149   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1150   FunctionDecl *FD = D->getAsFunction();
1151   if (!FD)
1152     return;
1153 
1154   // Same implementation as PushDeclContext, but enters the context
1155   // from the lexical parent, rather than the top-level class.
1156   assert(CurContext == FD->getLexicalParent() &&
1157     "The next DeclContext should be lexically contained in the current one.");
1158   CurContext = FD;
1159   S->setEntity(CurContext);
1160 
1161   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1162     ParmVarDecl *Param = FD->getParamDecl(P);
1163     // If the parameter has an identifier, then add it to the scope
1164     if (Param->getIdentifier()) {
1165       S->AddDecl(Param);
1166       IdResolver.AddDecl(Param);
1167     }
1168   }
1169 }
1170 
1171 void Sema::ActOnExitFunctionContext() {
1172   // Same implementation as PopDeclContext, but returns to the lexical parent,
1173   // rather than the top-level class.
1174   assert(CurContext && "DeclContext imbalance!");
1175   CurContext = CurContext->getLexicalParent();
1176   assert(CurContext && "Popped translation unit!");
1177 }
1178 
1179 /// \brief Determine whether we allow overloading of the function
1180 /// PrevDecl with another declaration.
1181 ///
1182 /// This routine determines whether overloading is possible, not
1183 /// whether some new function is actually an overload. It will return
1184 /// true in C++ (where we can always provide overloads) or, as an
1185 /// extension, in C when the previous function is already an
1186 /// overloaded function declaration or has the "overloadable"
1187 /// attribute.
1188 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1189                                        ASTContext &Context) {
1190   if (Context.getLangOpts().CPlusPlus)
1191     return true;
1192 
1193   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1194     return true;
1195 
1196   return (Previous.getResultKind() == LookupResult::Found
1197           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1198 }
1199 
1200 /// Add this decl to the scope shadowed decl chains.
1201 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1202   // Move up the scope chain until we find the nearest enclosing
1203   // non-transparent context. The declaration will be introduced into this
1204   // scope.
1205   while (S->getEntity() && S->getEntity()->isTransparentContext())
1206     S = S->getParent();
1207 
1208   // Add scoped declarations into their context, so that they can be
1209   // found later. Declarations without a context won't be inserted
1210   // into any context.
1211   if (AddToContext)
1212     CurContext->addDecl(D);
1213 
1214   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1215   // are function-local declarations.
1216   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1217       !D->getDeclContext()->getRedeclContext()->Equals(
1218         D->getLexicalDeclContext()->getRedeclContext()) &&
1219       !D->getLexicalDeclContext()->isFunctionOrMethod())
1220     return;
1221 
1222   // Template instantiations should also not be pushed into scope.
1223   if (isa<FunctionDecl>(D) &&
1224       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1225     return;
1226 
1227   // If this replaces anything in the current scope,
1228   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1229                                IEnd = IdResolver.end();
1230   for (; I != IEnd; ++I) {
1231     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1232       S->RemoveDecl(*I);
1233       IdResolver.RemoveDecl(*I);
1234 
1235       // Should only need to replace one decl.
1236       break;
1237     }
1238   }
1239 
1240   S->AddDecl(D);
1241 
1242   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1243     // Implicitly-generated labels may end up getting generated in an order that
1244     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1245     // the label at the appropriate place in the identifier chain.
1246     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1247       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1248       if (IDC == CurContext) {
1249         if (!S->isDeclScope(*I))
1250           continue;
1251       } else if (IDC->Encloses(CurContext))
1252         break;
1253     }
1254 
1255     IdResolver.InsertDeclAfter(I, D);
1256   } else {
1257     IdResolver.AddDecl(D);
1258   }
1259 }
1260 
1261 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1262   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1263     TUScope->AddDecl(D);
1264 }
1265 
1266 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1267                          bool AllowInlineNamespace) {
1268   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1269 }
1270 
1271 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1272   DeclContext *TargetDC = DC->getPrimaryContext();
1273   do {
1274     if (DeclContext *ScopeDC = S->getEntity())
1275       if (ScopeDC->getPrimaryContext() == TargetDC)
1276         return S;
1277   } while ((S = S->getParent()));
1278 
1279   return nullptr;
1280 }
1281 
1282 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1283                                             DeclContext*,
1284                                             ASTContext&);
1285 
1286 /// Filters out lookup results that don't fall within the given scope
1287 /// as determined by isDeclInScope.
1288 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1289                                 bool ConsiderLinkage,
1290                                 bool AllowInlineNamespace) {
1291   LookupResult::Filter F = R.makeFilter();
1292   while (F.hasNext()) {
1293     NamedDecl *D = F.next();
1294 
1295     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1296       continue;
1297 
1298     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1299       continue;
1300 
1301     F.erase();
1302   }
1303 
1304   F.done();
1305 }
1306 
1307 static bool isUsingDecl(NamedDecl *D) {
1308   return isa<UsingShadowDecl>(D) ||
1309          isa<UnresolvedUsingTypenameDecl>(D) ||
1310          isa<UnresolvedUsingValueDecl>(D);
1311 }
1312 
1313 /// Removes using shadow declarations from the lookup results.
1314 static void RemoveUsingDecls(LookupResult &R) {
1315   LookupResult::Filter F = R.makeFilter();
1316   while (F.hasNext())
1317     if (isUsingDecl(F.next()))
1318       F.erase();
1319 
1320   F.done();
1321 }
1322 
1323 /// \brief Check for this common pattern:
1324 /// @code
1325 /// class S {
1326 ///   S(const S&); // DO NOT IMPLEMENT
1327 ///   void operator=(const S&); // DO NOT IMPLEMENT
1328 /// };
1329 /// @endcode
1330 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1331   // FIXME: Should check for private access too but access is set after we get
1332   // the decl here.
1333   if (D->doesThisDeclarationHaveABody())
1334     return false;
1335 
1336   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1337     return CD->isCopyConstructor();
1338   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1339     return Method->isCopyAssignmentOperator();
1340   return false;
1341 }
1342 
1343 // We need this to handle
1344 //
1345 // typedef struct {
1346 //   void *foo() { return 0; }
1347 // } A;
1348 //
1349 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1350 // for example. If 'A', foo will have external linkage. If we have '*A',
1351 // foo will have no linkage. Since we can't know until we get to the end
1352 // of the typedef, this function finds out if D might have non-external linkage.
1353 // Callers should verify at the end of the TU if it D has external linkage or
1354 // not.
1355 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1356   const DeclContext *DC = D->getDeclContext();
1357   while (!DC->isTranslationUnit()) {
1358     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1359       if (!RD->hasNameForLinkage())
1360         return true;
1361     }
1362     DC = DC->getParent();
1363   }
1364 
1365   return !D->isExternallyVisible();
1366 }
1367 
1368 // FIXME: This needs to be refactored; some other isInMainFile users want
1369 // these semantics.
1370 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1371   if (S.TUKind != TU_Complete)
1372     return false;
1373   return S.SourceMgr.isInMainFile(Loc);
1374 }
1375 
1376 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1377   assert(D);
1378 
1379   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1380     return false;
1381 
1382   // Ignore all entities declared within templates, and out-of-line definitions
1383   // of members of class templates.
1384   if (D->getDeclContext()->isDependentContext() ||
1385       D->getLexicalDeclContext()->isDependentContext())
1386     return false;
1387 
1388   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1389     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1390       return false;
1391 
1392     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1393       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1394         return false;
1395     } else {
1396       // 'static inline' functions are defined in headers; don't warn.
1397       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1398         return false;
1399     }
1400 
1401     if (FD->doesThisDeclarationHaveABody() &&
1402         Context.DeclMustBeEmitted(FD))
1403       return false;
1404   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1405     // Constants and utility variables are defined in headers with internal
1406     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1407     // like "inline".)
1408     if (!isMainFileLoc(*this, VD->getLocation()))
1409       return false;
1410 
1411     if (Context.DeclMustBeEmitted(VD))
1412       return false;
1413 
1414     if (VD->isStaticDataMember() &&
1415         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1416       return false;
1417   } else {
1418     return false;
1419   }
1420 
1421   // Only warn for unused decls internal to the translation unit.
1422   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1423   // for inline functions defined in the main source file, for instance.
1424   return mightHaveNonExternalLinkage(D);
1425 }
1426 
1427 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1428   if (!D)
1429     return;
1430 
1431   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1432     const FunctionDecl *First = FD->getFirstDecl();
1433     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1434       return; // First should already be in the vector.
1435   }
1436 
1437   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1438     const VarDecl *First = VD->getFirstDecl();
1439     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1440       return; // First should already be in the vector.
1441   }
1442 
1443   if (ShouldWarnIfUnusedFileScopedDecl(D))
1444     UnusedFileScopedDecls.push_back(D);
1445 }
1446 
1447 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1448   if (D->isInvalidDecl())
1449     return false;
1450 
1451   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1452       D->hasAttr<ObjCPreciseLifetimeAttr>())
1453     return false;
1454 
1455   if (isa<LabelDecl>(D))
1456     return true;
1457 
1458   // Except for labels, we only care about unused decls that are local to
1459   // functions.
1460   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1461   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1462     // For dependent types, the diagnostic is deferred.
1463     WithinFunction =
1464         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1465   if (!WithinFunction)
1466     return false;
1467 
1468   if (isa<TypedefNameDecl>(D))
1469     return true;
1470 
1471   // White-list anything that isn't a local variable.
1472   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1473     return false;
1474 
1475   // Types of valid local variables should be complete, so this should succeed.
1476   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1477 
1478     // White-list anything with an __attribute__((unused)) type.
1479     QualType Ty = VD->getType();
1480 
1481     // Only look at the outermost level of typedef.
1482     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1483       if (TT->getDecl()->hasAttr<UnusedAttr>())
1484         return false;
1485     }
1486 
1487     // If we failed to complete the type for some reason, or if the type is
1488     // dependent, don't diagnose the variable.
1489     if (Ty->isIncompleteType() || Ty->isDependentType())
1490       return false;
1491 
1492     if (const TagType *TT = Ty->getAs<TagType>()) {
1493       const TagDecl *Tag = TT->getDecl();
1494       if (Tag->hasAttr<UnusedAttr>())
1495         return false;
1496 
1497       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1498         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1499           return false;
1500 
1501         if (const Expr *Init = VD->getInit()) {
1502           if (const ExprWithCleanups *Cleanups =
1503                   dyn_cast<ExprWithCleanups>(Init))
1504             Init = Cleanups->getSubExpr();
1505           const CXXConstructExpr *Construct =
1506             dyn_cast<CXXConstructExpr>(Init);
1507           if (Construct && !Construct->isElidable()) {
1508             CXXConstructorDecl *CD = Construct->getConstructor();
1509             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1510               return false;
1511           }
1512         }
1513       }
1514     }
1515 
1516     // TODO: __attribute__((unused)) templates?
1517   }
1518 
1519   return true;
1520 }
1521 
1522 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1523                                      FixItHint &Hint) {
1524   if (isa<LabelDecl>(D)) {
1525     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1526                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1527     if (AfterColon.isInvalid())
1528       return;
1529     Hint = FixItHint::CreateRemoval(CharSourceRange::
1530                                     getCharRange(D->getLocStart(), AfterColon));
1531   }
1532 }
1533 
1534 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1535   if (D->getTypeForDecl()->isDependentType())
1536     return;
1537 
1538   for (auto *TmpD : D->decls()) {
1539     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1540       DiagnoseUnusedDecl(T);
1541     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1542       DiagnoseUnusedNestedTypedefs(R);
1543   }
1544 }
1545 
1546 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1547 /// unless they are marked attr(unused).
1548 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1549   if (!ShouldDiagnoseUnusedDecl(D))
1550     return;
1551 
1552   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1553     // typedefs can be referenced later on, so the diagnostics are emitted
1554     // at end-of-translation-unit.
1555     UnusedLocalTypedefNameCandidates.insert(TD);
1556     return;
1557   }
1558 
1559   FixItHint Hint;
1560   GenerateFixForUnusedDecl(D, Context, Hint);
1561 
1562   unsigned DiagID;
1563   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1564     DiagID = diag::warn_unused_exception_param;
1565   else if (isa<LabelDecl>(D))
1566     DiagID = diag::warn_unused_label;
1567   else
1568     DiagID = diag::warn_unused_variable;
1569 
1570   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1571 }
1572 
1573 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1574   // Verify that we have no forward references left.  If so, there was a goto
1575   // or address of a label taken, but no definition of it.  Label fwd
1576   // definitions are indicated with a null substmt which is also not a resolved
1577   // MS inline assembly label name.
1578   bool Diagnose = false;
1579   if (L->isMSAsmLabel())
1580     Diagnose = !L->isResolvedMSAsmLabel();
1581   else
1582     Diagnose = L->getStmt() == nullptr;
1583   if (Diagnose)
1584     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1585 }
1586 
1587 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1588   S->mergeNRVOIntoParent();
1589 
1590   if (S->decl_empty()) return;
1591   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1592          "Scope shouldn't contain decls!");
1593 
1594   for (auto *TmpD : S->decls()) {
1595     assert(TmpD && "This decl didn't get pushed??");
1596 
1597     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1598     NamedDecl *D = cast<NamedDecl>(TmpD);
1599 
1600     if (!D->getDeclName()) continue;
1601 
1602     // Diagnose unused variables in this scope.
1603     if (!S->hasUnrecoverableErrorOccurred()) {
1604       DiagnoseUnusedDecl(D);
1605       if (const auto *RD = dyn_cast<RecordDecl>(D))
1606         DiagnoseUnusedNestedTypedefs(RD);
1607     }
1608 
1609     // If this was a forward reference to a label, verify it was defined.
1610     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1611       CheckPoppedLabel(LD, *this);
1612 
1613     // Remove this name from our lexical scope.
1614     IdResolver.RemoveDecl(D);
1615   }
1616 }
1617 
1618 /// \brief Look for an Objective-C class in the translation unit.
1619 ///
1620 /// \param Id The name of the Objective-C class we're looking for. If
1621 /// typo-correction fixes this name, the Id will be updated
1622 /// to the fixed name.
1623 ///
1624 /// \param IdLoc The location of the name in the translation unit.
1625 ///
1626 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1627 /// if there is no class with the given name.
1628 ///
1629 /// \returns The declaration of the named Objective-C class, or NULL if the
1630 /// class could not be found.
1631 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1632                                               SourceLocation IdLoc,
1633                                               bool DoTypoCorrection) {
1634   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1635   // creation from this context.
1636   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1637 
1638   if (!IDecl && DoTypoCorrection) {
1639     // Perform typo correction at the given location, but only if we
1640     // find an Objective-C class name.
1641     if (TypoCorrection C = CorrectTypo(
1642             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1643             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1644             CTK_ErrorRecovery)) {
1645       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1646       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1647       Id = IDecl->getIdentifier();
1648     }
1649   }
1650   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1651   // This routine must always return a class definition, if any.
1652   if (Def && Def->getDefinition())
1653       Def = Def->getDefinition();
1654   return Def;
1655 }
1656 
1657 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1658 /// from S, where a non-field would be declared. This routine copes
1659 /// with the difference between C and C++ scoping rules in structs and
1660 /// unions. For example, the following code is well-formed in C but
1661 /// ill-formed in C++:
1662 /// @code
1663 /// struct S6 {
1664 ///   enum { BAR } e;
1665 /// };
1666 ///
1667 /// void test_S6() {
1668 ///   struct S6 a;
1669 ///   a.e = BAR;
1670 /// }
1671 /// @endcode
1672 /// For the declaration of BAR, this routine will return a different
1673 /// scope. The scope S will be the scope of the unnamed enumeration
1674 /// within S6. In C++, this routine will return the scope associated
1675 /// with S6, because the enumeration's scope is a transparent
1676 /// context but structures can contain non-field names. In C, this
1677 /// routine will return the translation unit scope, since the
1678 /// enumeration's scope is a transparent context and structures cannot
1679 /// contain non-field names.
1680 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1681   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1682          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1683          (S->isClassScope() && !getLangOpts().CPlusPlus))
1684     S = S->getParent();
1685   return S;
1686 }
1687 
1688 /// \brief Looks up the declaration of "struct objc_super" and
1689 /// saves it for later use in building builtin declaration of
1690 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1691 /// pre-existing declaration exists no action takes place.
1692 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1693                                         IdentifierInfo *II) {
1694   if (!II->isStr("objc_msgSendSuper"))
1695     return;
1696   ASTContext &Context = ThisSema.Context;
1697 
1698   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1699                       SourceLocation(), Sema::LookupTagName);
1700   ThisSema.LookupName(Result, S);
1701   if (Result.getResultKind() == LookupResult::Found)
1702     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1703       Context.setObjCSuperType(Context.getTagDeclType(TD));
1704 }
1705 
1706 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1707   switch (Error) {
1708   case ASTContext::GE_None:
1709     return "";
1710   case ASTContext::GE_Missing_stdio:
1711     return "stdio.h";
1712   case ASTContext::GE_Missing_setjmp:
1713     return "setjmp.h";
1714   case ASTContext::GE_Missing_ucontext:
1715     return "ucontext.h";
1716   }
1717   llvm_unreachable("unhandled error kind");
1718 }
1719 
1720 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1721 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1722 /// if we're creating this built-in in anticipation of redeclaring the
1723 /// built-in.
1724 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1725                                      Scope *S, bool ForRedeclaration,
1726                                      SourceLocation Loc) {
1727   LookupPredefedObjCSuperType(*this, S, II);
1728 
1729   ASTContext::GetBuiltinTypeError Error;
1730   QualType R = Context.GetBuiltinType(ID, Error);
1731   if (Error) {
1732     if (ForRedeclaration)
1733       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1734           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1735     return nullptr;
1736   }
1737 
1738   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1739     Diag(Loc, diag::ext_implicit_lib_function_decl)
1740         << Context.BuiltinInfo.getName(ID) << R;
1741     if (Context.BuiltinInfo.getHeaderName(ID) &&
1742         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1743       Diag(Loc, diag::note_include_header_or_declare)
1744           << Context.BuiltinInfo.getHeaderName(ID)
1745           << Context.BuiltinInfo.getName(ID);
1746   }
1747 
1748   if (R.isNull())
1749     return nullptr;
1750 
1751   DeclContext *Parent = Context.getTranslationUnitDecl();
1752   if (getLangOpts().CPlusPlus) {
1753     LinkageSpecDecl *CLinkageDecl =
1754         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1755                                 LinkageSpecDecl::lang_c, false);
1756     CLinkageDecl->setImplicit();
1757     Parent->addDecl(CLinkageDecl);
1758     Parent = CLinkageDecl;
1759   }
1760 
1761   FunctionDecl *New = FunctionDecl::Create(Context,
1762                                            Parent,
1763                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1764                                            SC_Extern,
1765                                            false,
1766                                            R->isFunctionProtoType());
1767   New->setImplicit();
1768 
1769   // Create Decl objects for each parameter, adding them to the
1770   // FunctionDecl.
1771   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1772     SmallVector<ParmVarDecl*, 16> Params;
1773     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1774       ParmVarDecl *parm =
1775           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1776                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1777                               SC_None, nullptr);
1778       parm->setScopeInfo(0, i);
1779       Params.push_back(parm);
1780     }
1781     New->setParams(Params);
1782   }
1783 
1784   AddKnownFunctionAttributes(New);
1785   RegisterLocallyScopedExternCDecl(New, S);
1786 
1787   // TUScope is the translation-unit scope to insert this function into.
1788   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1789   // relate Scopes to DeclContexts, and probably eliminate CurContext
1790   // entirely, but we're not there yet.
1791   DeclContext *SavedContext = CurContext;
1792   CurContext = Parent;
1793   PushOnScopeChains(New, TUScope);
1794   CurContext = SavedContext;
1795   return New;
1796 }
1797 
1798 /// Typedef declarations don't have linkage, but they still denote the same
1799 /// entity if their types are the same.
1800 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1801 /// isSameEntity.
1802 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1803                                                      TypedefNameDecl *Decl,
1804                                                      LookupResult &Previous) {
1805   // This is only interesting when modules are enabled.
1806   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1807     return;
1808 
1809   // Empty sets are uninteresting.
1810   if (Previous.empty())
1811     return;
1812 
1813   LookupResult::Filter Filter = Previous.makeFilter();
1814   while (Filter.hasNext()) {
1815     NamedDecl *Old = Filter.next();
1816 
1817     // Non-hidden declarations are never ignored.
1818     if (S.isVisible(Old))
1819       continue;
1820 
1821     // Declarations of the same entity are not ignored, even if they have
1822     // different linkages.
1823     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1824       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1825                                 Decl->getUnderlyingType()))
1826         continue;
1827 
1828       // If both declarations give a tag declaration a typedef name for linkage
1829       // purposes, then they declare the same entity.
1830       if (S.getLangOpts().CPlusPlus &&
1831           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1832           Decl->getAnonDeclWithTypedefName())
1833         continue;
1834     }
1835 
1836     Filter.erase();
1837   }
1838 
1839   Filter.done();
1840 }
1841 
1842 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1843   QualType OldType;
1844   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1845     OldType = OldTypedef->getUnderlyingType();
1846   else
1847     OldType = Context.getTypeDeclType(Old);
1848   QualType NewType = New->getUnderlyingType();
1849 
1850   if (NewType->isVariablyModifiedType()) {
1851     // Must not redefine a typedef with a variably-modified type.
1852     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1853     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1854       << Kind << NewType;
1855     if (Old->getLocation().isValid())
1856       Diag(Old->getLocation(), diag::note_previous_definition);
1857     New->setInvalidDecl();
1858     return true;
1859   }
1860 
1861   if (OldType != NewType &&
1862       !OldType->isDependentType() &&
1863       !NewType->isDependentType() &&
1864       !Context.hasSameType(OldType, NewType)) {
1865     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1866     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1867       << Kind << NewType << OldType;
1868     if (Old->getLocation().isValid())
1869       Diag(Old->getLocation(), diag::note_previous_definition);
1870     New->setInvalidDecl();
1871     return true;
1872   }
1873   return false;
1874 }
1875 
1876 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1877 /// same name and scope as a previous declaration 'Old'.  Figure out
1878 /// how to resolve this situation, merging decls or emitting
1879 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1880 ///
1881 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1882                                 LookupResult &OldDecls) {
1883   // If the new decl is known invalid already, don't bother doing any
1884   // merging checks.
1885   if (New->isInvalidDecl()) return;
1886 
1887   // Allow multiple definitions for ObjC built-in typedefs.
1888   // FIXME: Verify the underlying types are equivalent!
1889   if (getLangOpts().ObjC1) {
1890     const IdentifierInfo *TypeID = New->getIdentifier();
1891     switch (TypeID->getLength()) {
1892     default: break;
1893     case 2:
1894       {
1895         if (!TypeID->isStr("id"))
1896           break;
1897         QualType T = New->getUnderlyingType();
1898         if (!T->isPointerType())
1899           break;
1900         if (!T->isVoidPointerType()) {
1901           QualType PT = T->getAs<PointerType>()->getPointeeType();
1902           if (!PT->isStructureType())
1903             break;
1904         }
1905         Context.setObjCIdRedefinitionType(T);
1906         // Install the built-in type for 'id', ignoring the current definition.
1907         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1908         return;
1909       }
1910     case 5:
1911       if (!TypeID->isStr("Class"))
1912         break;
1913       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1914       // Install the built-in type for 'Class', ignoring the current definition.
1915       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1916       return;
1917     case 3:
1918       if (!TypeID->isStr("SEL"))
1919         break;
1920       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1921       // Install the built-in type for 'SEL', ignoring the current definition.
1922       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1923       return;
1924     }
1925     // Fall through - the typedef name was not a builtin type.
1926   }
1927 
1928   // Verify the old decl was also a type.
1929   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1930   if (!Old) {
1931     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1932       << New->getDeclName();
1933 
1934     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1935     if (OldD->getLocation().isValid())
1936       Diag(OldD->getLocation(), diag::note_previous_definition);
1937 
1938     return New->setInvalidDecl();
1939   }
1940 
1941   // If the old declaration is invalid, just give up here.
1942   if (Old->isInvalidDecl())
1943     return New->setInvalidDecl();
1944 
1945   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1946     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
1947     auto *NewTag = New->getAnonDeclWithTypedefName();
1948     NamedDecl *Hidden = nullptr;
1949     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
1950         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
1951         !hasVisibleDefinition(OldTag, &Hidden)) {
1952       // There is a definition of this tag, but it is not visible. Use it
1953       // instead of our tag.
1954       New->setTypeForDecl(OldTD->getTypeForDecl());
1955       if (OldTD->isModed())
1956         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
1957                                     OldTD->getUnderlyingType());
1958       else
1959         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
1960 
1961       // Make the old tag definition visible.
1962       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
1963 
1964       // If this was an unscoped enumeration, yank all of its enumerators
1965       // out of the scope.
1966       if (isa<EnumDecl>(NewTag)) {
1967         Scope *EnumScope = getNonFieldDeclScope(S);
1968         for (auto *D : NewTag->decls()) {
1969           auto *ED = cast<EnumConstantDecl>(D);
1970           assert(EnumScope->isDeclScope(ED));
1971           EnumScope->RemoveDecl(ED);
1972           IdResolver.RemoveDecl(ED);
1973           ED->getLexicalDeclContext()->removeDecl(ED);
1974         }
1975       }
1976     }
1977   }
1978 
1979   // If the typedef types are not identical, reject them in all languages and
1980   // with any extensions enabled.
1981   if (isIncompatibleTypedef(Old, New))
1982     return;
1983 
1984   // The types match.  Link up the redeclaration chain and merge attributes if
1985   // the old declaration was a typedef.
1986   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1987     New->setPreviousDecl(Typedef);
1988     mergeDeclAttributes(New, Old);
1989   }
1990 
1991   if (getLangOpts().MicrosoftExt)
1992     return;
1993 
1994   if (getLangOpts().CPlusPlus) {
1995     // C++ [dcl.typedef]p2:
1996     //   In a given non-class scope, a typedef specifier can be used to
1997     //   redefine the name of any type declared in that scope to refer
1998     //   to the type to which it already refers.
1999     if (!isa<CXXRecordDecl>(CurContext))
2000       return;
2001 
2002     // C++0x [dcl.typedef]p4:
2003     //   In a given class scope, a typedef specifier can be used to redefine
2004     //   any class-name declared in that scope that is not also a typedef-name
2005     //   to refer to the type to which it already refers.
2006     //
2007     // This wording came in via DR424, which was a correction to the
2008     // wording in DR56, which accidentally banned code like:
2009     //
2010     //   struct S {
2011     //     typedef struct A { } A;
2012     //   };
2013     //
2014     // in the C++03 standard. We implement the C++0x semantics, which
2015     // allow the above but disallow
2016     //
2017     //   struct S {
2018     //     typedef int I;
2019     //     typedef int I;
2020     //   };
2021     //
2022     // since that was the intent of DR56.
2023     if (!isa<TypedefNameDecl>(Old))
2024       return;
2025 
2026     Diag(New->getLocation(), diag::err_redefinition)
2027       << New->getDeclName();
2028     Diag(Old->getLocation(), diag::note_previous_definition);
2029     return New->setInvalidDecl();
2030   }
2031 
2032   // Modules always permit redefinition of typedefs, as does C11.
2033   if (getLangOpts().Modules || getLangOpts().C11)
2034     return;
2035 
2036   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2037   // is normally mapped to an error, but can be controlled with
2038   // -Wtypedef-redefinition.  If either the original or the redefinition is
2039   // in a system header, don't emit this for compatibility with GCC.
2040   if (getDiagnostics().getSuppressSystemWarnings() &&
2041       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2042        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2043     return;
2044 
2045   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2046     << New->getDeclName();
2047   Diag(Old->getLocation(), diag::note_previous_definition);
2048 }
2049 
2050 /// DeclhasAttr - returns true if decl Declaration already has the target
2051 /// attribute.
2052 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2053   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2054   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2055   for (const auto *i : D->attrs())
2056     if (i->getKind() == A->getKind()) {
2057       if (Ann) {
2058         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2059           return true;
2060         continue;
2061       }
2062       // FIXME: Don't hardcode this check
2063       if (OA && isa<OwnershipAttr>(i))
2064         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2065       return true;
2066     }
2067 
2068   return false;
2069 }
2070 
2071 static bool isAttributeTargetADefinition(Decl *D) {
2072   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2073     return VD->isThisDeclarationADefinition();
2074   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2075     return TD->isCompleteDefinition() || TD->isBeingDefined();
2076   return true;
2077 }
2078 
2079 /// Merge alignment attributes from \p Old to \p New, taking into account the
2080 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2081 ///
2082 /// \return \c true if any attributes were added to \p New.
2083 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2084   // Look for alignas attributes on Old, and pick out whichever attribute
2085   // specifies the strictest alignment requirement.
2086   AlignedAttr *OldAlignasAttr = nullptr;
2087   AlignedAttr *OldStrictestAlignAttr = nullptr;
2088   unsigned OldAlign = 0;
2089   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2090     // FIXME: We have no way of representing inherited dependent alignments
2091     // in a case like:
2092     //   template<int A, int B> struct alignas(A) X;
2093     //   template<int A, int B> struct alignas(B) X {};
2094     // For now, we just ignore any alignas attributes which are not on the
2095     // definition in such a case.
2096     if (I->isAlignmentDependent())
2097       return false;
2098 
2099     if (I->isAlignas())
2100       OldAlignasAttr = I;
2101 
2102     unsigned Align = I->getAlignment(S.Context);
2103     if (Align > OldAlign) {
2104       OldAlign = Align;
2105       OldStrictestAlignAttr = I;
2106     }
2107   }
2108 
2109   // Look for alignas attributes on New.
2110   AlignedAttr *NewAlignasAttr = nullptr;
2111   unsigned NewAlign = 0;
2112   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2113     if (I->isAlignmentDependent())
2114       return false;
2115 
2116     if (I->isAlignas())
2117       NewAlignasAttr = I;
2118 
2119     unsigned Align = I->getAlignment(S.Context);
2120     if (Align > NewAlign)
2121       NewAlign = Align;
2122   }
2123 
2124   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2125     // Both declarations have 'alignas' attributes. We require them to match.
2126     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2127     // fall short. (If two declarations both have alignas, they must both match
2128     // every definition, and so must match each other if there is a definition.)
2129 
2130     // If either declaration only contains 'alignas(0)' specifiers, then it
2131     // specifies the natural alignment for the type.
2132     if (OldAlign == 0 || NewAlign == 0) {
2133       QualType Ty;
2134       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2135         Ty = VD->getType();
2136       else
2137         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2138 
2139       if (OldAlign == 0)
2140         OldAlign = S.Context.getTypeAlign(Ty);
2141       if (NewAlign == 0)
2142         NewAlign = S.Context.getTypeAlign(Ty);
2143     }
2144 
2145     if (OldAlign != NewAlign) {
2146       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2147         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2148         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2149       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2150     }
2151   }
2152 
2153   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2154     // C++11 [dcl.align]p6:
2155     //   if any declaration of an entity has an alignment-specifier,
2156     //   every defining declaration of that entity shall specify an
2157     //   equivalent alignment.
2158     // C11 6.7.5/7:
2159     //   If the definition of an object does not have an alignment
2160     //   specifier, any other declaration of that object shall also
2161     //   have no alignment specifier.
2162     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2163       << OldAlignasAttr;
2164     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2165       << OldAlignasAttr;
2166   }
2167 
2168   bool AnyAdded = false;
2169 
2170   // Ensure we have an attribute representing the strictest alignment.
2171   if (OldAlign > NewAlign) {
2172     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2173     Clone->setInherited(true);
2174     New->addAttr(Clone);
2175     AnyAdded = true;
2176   }
2177 
2178   // Ensure we have an alignas attribute if the old declaration had one.
2179   if (OldAlignasAttr && !NewAlignasAttr &&
2180       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2181     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2182     Clone->setInherited(true);
2183     New->addAttr(Clone);
2184     AnyAdded = true;
2185   }
2186 
2187   return AnyAdded;
2188 }
2189 
2190 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2191                                const InheritableAttr *Attr,
2192                                Sema::AvailabilityMergeKind AMK) {
2193   InheritableAttr *NewAttr = nullptr;
2194   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2195   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2196     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2197                                       AA->getIntroduced(), AA->getDeprecated(),
2198                                       AA->getObsoleted(), AA->getUnavailable(),
2199                                       AA->getMessage(), AA->getStrict(), AMK,
2200                                       AttrSpellingListIndex);
2201   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2202     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2203                                     AttrSpellingListIndex);
2204   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2205     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2206                                         AttrSpellingListIndex);
2207   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2208     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2209                                    AttrSpellingListIndex);
2210   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2211     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2212                                    AttrSpellingListIndex);
2213   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2214     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2215                                 FA->getFormatIdx(), FA->getFirstArg(),
2216                                 AttrSpellingListIndex);
2217   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2218     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2219                                  AttrSpellingListIndex);
2220   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2221     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2222                                        AttrSpellingListIndex,
2223                                        IA->getSemanticSpelling());
2224   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2225     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2226                                       &S.Context.Idents.get(AA->getSpelling()),
2227                                       AttrSpellingListIndex);
2228   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2229     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2230   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2231     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2232   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2233     NewAttr = S.mergeInternalLinkageAttr(
2234         D, InternalLinkageA->getRange(),
2235         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2236         AttrSpellingListIndex);
2237   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2238     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2239                                 &S.Context.Idents.get(CommonA->getSpelling()),
2240                                 AttrSpellingListIndex);
2241   else if (isa<AlignedAttr>(Attr))
2242     // AlignedAttrs are handled separately, because we need to handle all
2243     // such attributes on a declaration at the same time.
2244     NewAttr = nullptr;
2245   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2246            (AMK == Sema::AMK_Override ||
2247             AMK == Sema::AMK_ProtocolImplementation))
2248     NewAttr = nullptr;
2249   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2250     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2251 
2252   if (NewAttr) {
2253     NewAttr->setInherited(true);
2254     D->addAttr(NewAttr);
2255     if (isa<MSInheritanceAttr>(NewAttr))
2256       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2257     return true;
2258   }
2259 
2260   return false;
2261 }
2262 
2263 static const Decl *getDefinition(const Decl *D) {
2264   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2265     return TD->getDefinition();
2266   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2267     const VarDecl *Def = VD->getDefinition();
2268     if (Def)
2269       return Def;
2270     return VD->getActingDefinition();
2271   }
2272   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2273     const FunctionDecl* Def;
2274     if (FD->isDefined(Def))
2275       return Def;
2276   }
2277   return nullptr;
2278 }
2279 
2280 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2281   for (const auto *Attribute : D->attrs())
2282     if (Attribute->getKind() == Kind)
2283       return true;
2284   return false;
2285 }
2286 
2287 /// checkNewAttributesAfterDef - If we already have a definition, check that
2288 /// there are no new attributes in this declaration.
2289 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2290   if (!New->hasAttrs())
2291     return;
2292 
2293   const Decl *Def = getDefinition(Old);
2294   if (!Def || Def == New)
2295     return;
2296 
2297   AttrVec &NewAttributes = New->getAttrs();
2298   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2299     const Attr *NewAttribute = NewAttributes[I];
2300 
2301     if (isa<AliasAttr>(NewAttribute)) {
2302       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2303         Sema::SkipBodyInfo SkipBody;
2304         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2305 
2306         // If we're skipping this definition, drop the "alias" attribute.
2307         if (SkipBody.ShouldSkip) {
2308           NewAttributes.erase(NewAttributes.begin() + I);
2309           --E;
2310           continue;
2311         }
2312       } else {
2313         VarDecl *VD = cast<VarDecl>(New);
2314         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2315                                 VarDecl::TentativeDefinition
2316                             ? diag::err_alias_after_tentative
2317                             : diag::err_redefinition;
2318         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2319         S.Diag(Def->getLocation(), diag::note_previous_definition);
2320         VD->setInvalidDecl();
2321       }
2322       ++I;
2323       continue;
2324     }
2325 
2326     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2327       // Tentative definitions are only interesting for the alias check above.
2328       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2329         ++I;
2330         continue;
2331       }
2332     }
2333 
2334     if (hasAttribute(Def, NewAttribute->getKind())) {
2335       ++I;
2336       continue; // regular attr merging will take care of validating this.
2337     }
2338 
2339     if (isa<C11NoReturnAttr>(NewAttribute)) {
2340       // C's _Noreturn is allowed to be added to a function after it is defined.
2341       ++I;
2342       continue;
2343     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2344       if (AA->isAlignas()) {
2345         // C++11 [dcl.align]p6:
2346         //   if any declaration of an entity has an alignment-specifier,
2347         //   every defining declaration of that entity shall specify an
2348         //   equivalent alignment.
2349         // C11 6.7.5/7:
2350         //   If the definition of an object does not have an alignment
2351         //   specifier, any other declaration of that object shall also
2352         //   have no alignment specifier.
2353         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2354           << AA;
2355         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2356           << AA;
2357         NewAttributes.erase(NewAttributes.begin() + I);
2358         --E;
2359         continue;
2360       }
2361     }
2362 
2363     S.Diag(NewAttribute->getLocation(),
2364            diag::warn_attribute_precede_definition);
2365     S.Diag(Def->getLocation(), diag::note_previous_definition);
2366     NewAttributes.erase(NewAttributes.begin() + I);
2367     --E;
2368   }
2369 }
2370 
2371 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2372 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2373                                AvailabilityMergeKind AMK) {
2374   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2375     UsedAttr *NewAttr = OldAttr->clone(Context);
2376     NewAttr->setInherited(true);
2377     New->addAttr(NewAttr);
2378   }
2379 
2380   if (!Old->hasAttrs() && !New->hasAttrs())
2381     return;
2382 
2383   // Attributes declared post-definition are currently ignored.
2384   checkNewAttributesAfterDef(*this, New, Old);
2385 
2386   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2387     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2388       if (OldA->getLabel() != NewA->getLabel()) {
2389         // This redeclaration changes __asm__ label.
2390         Diag(New->getLocation(), diag::err_different_asm_label);
2391         Diag(OldA->getLocation(), diag::note_previous_declaration);
2392       }
2393     } else if (Old->isUsed()) {
2394       // This redeclaration adds an __asm__ label to a declaration that has
2395       // already been ODR-used.
2396       Diag(New->getLocation(), diag::err_late_asm_label_name)
2397         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2398     }
2399   }
2400 
2401   if (!Old->hasAttrs())
2402     return;
2403 
2404   bool foundAny = New->hasAttrs();
2405 
2406   // Ensure that any moving of objects within the allocated map is done before
2407   // we process them.
2408   if (!foundAny) New->setAttrs(AttrVec());
2409 
2410   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2411     // Ignore deprecated/unavailable/availability attributes if requested.
2412     AvailabilityMergeKind LocalAMK = AMK_None;
2413     if (isa<DeprecatedAttr>(I) ||
2414         isa<UnavailableAttr>(I) ||
2415         isa<AvailabilityAttr>(I)) {
2416       switch (AMK) {
2417       case AMK_None:
2418         continue;
2419 
2420       case AMK_Redeclaration:
2421       case AMK_Override:
2422       case AMK_ProtocolImplementation:
2423         LocalAMK = AMK;
2424         break;
2425       }
2426     }
2427 
2428     // Already handled.
2429     if (isa<UsedAttr>(I))
2430       continue;
2431 
2432     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2433       foundAny = true;
2434   }
2435 
2436   if (mergeAlignedAttrs(*this, New, Old))
2437     foundAny = true;
2438 
2439   if (!foundAny) New->dropAttrs();
2440 }
2441 
2442 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2443 /// to the new one.
2444 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2445                                      const ParmVarDecl *oldDecl,
2446                                      Sema &S) {
2447   // C++11 [dcl.attr.depend]p2:
2448   //   The first declaration of a function shall specify the
2449   //   carries_dependency attribute for its declarator-id if any declaration
2450   //   of the function specifies the carries_dependency attribute.
2451   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2452   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2453     S.Diag(CDA->getLocation(),
2454            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2455     // Find the first declaration of the parameter.
2456     // FIXME: Should we build redeclaration chains for function parameters?
2457     const FunctionDecl *FirstFD =
2458       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2459     const ParmVarDecl *FirstVD =
2460       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2461     S.Diag(FirstVD->getLocation(),
2462            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2463   }
2464 
2465   if (!oldDecl->hasAttrs())
2466     return;
2467 
2468   bool foundAny = newDecl->hasAttrs();
2469 
2470   // Ensure that any moving of objects within the allocated map is
2471   // done before we process them.
2472   if (!foundAny) newDecl->setAttrs(AttrVec());
2473 
2474   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2475     if (!DeclHasAttr(newDecl, I)) {
2476       InheritableAttr *newAttr =
2477         cast<InheritableParamAttr>(I->clone(S.Context));
2478       newAttr->setInherited(true);
2479       newDecl->addAttr(newAttr);
2480       foundAny = true;
2481     }
2482   }
2483 
2484   if (!foundAny) newDecl->dropAttrs();
2485 }
2486 
2487 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2488                                 const ParmVarDecl *OldParam,
2489                                 Sema &S) {
2490   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2491     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2492       if (*Oldnullability != *Newnullability) {
2493         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2494           << DiagNullabilityKind(
2495                *Newnullability,
2496                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2497                 != 0))
2498           << DiagNullabilityKind(
2499                *Oldnullability,
2500                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2501                 != 0));
2502         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2503       }
2504     } else {
2505       QualType NewT = NewParam->getType();
2506       NewT = S.Context.getAttributedType(
2507                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2508                          NewT, NewT);
2509       NewParam->setType(NewT);
2510     }
2511   }
2512 }
2513 
2514 namespace {
2515 
2516 /// Used in MergeFunctionDecl to keep track of function parameters in
2517 /// C.
2518 struct GNUCompatibleParamWarning {
2519   ParmVarDecl *OldParm;
2520   ParmVarDecl *NewParm;
2521   QualType PromotedType;
2522 };
2523 
2524 } // end anonymous namespace
2525 
2526 /// getSpecialMember - get the special member enum for a method.
2527 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2528   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2529     if (Ctor->isDefaultConstructor())
2530       return Sema::CXXDefaultConstructor;
2531 
2532     if (Ctor->isCopyConstructor())
2533       return Sema::CXXCopyConstructor;
2534 
2535     if (Ctor->isMoveConstructor())
2536       return Sema::CXXMoveConstructor;
2537   } else if (isa<CXXDestructorDecl>(MD)) {
2538     return Sema::CXXDestructor;
2539   } else if (MD->isCopyAssignmentOperator()) {
2540     return Sema::CXXCopyAssignment;
2541   } else if (MD->isMoveAssignmentOperator()) {
2542     return Sema::CXXMoveAssignment;
2543   }
2544 
2545   return Sema::CXXInvalid;
2546 }
2547 
2548 // Determine whether the previous declaration was a definition, implicit
2549 // declaration, or a declaration.
2550 template <typename T>
2551 static std::pair<diag::kind, SourceLocation>
2552 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2553   diag::kind PrevDiag;
2554   SourceLocation OldLocation = Old->getLocation();
2555   if (Old->isThisDeclarationADefinition())
2556     PrevDiag = diag::note_previous_definition;
2557   else if (Old->isImplicit()) {
2558     PrevDiag = diag::note_previous_implicit_declaration;
2559     if (OldLocation.isInvalid())
2560       OldLocation = New->getLocation();
2561   } else
2562     PrevDiag = diag::note_previous_declaration;
2563   return std::make_pair(PrevDiag, OldLocation);
2564 }
2565 
2566 /// canRedefineFunction - checks if a function can be redefined. Currently,
2567 /// only extern inline functions can be redefined, and even then only in
2568 /// GNU89 mode.
2569 static bool canRedefineFunction(const FunctionDecl *FD,
2570                                 const LangOptions& LangOpts) {
2571   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2572           !LangOpts.CPlusPlus &&
2573           FD->isInlineSpecified() &&
2574           FD->getStorageClass() == SC_Extern);
2575 }
2576 
2577 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2578   const AttributedType *AT = T->getAs<AttributedType>();
2579   while (AT && !AT->isCallingConv())
2580     AT = AT->getModifiedType()->getAs<AttributedType>();
2581   return AT;
2582 }
2583 
2584 template <typename T>
2585 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2586   const DeclContext *DC = Old->getDeclContext();
2587   if (DC->isRecord())
2588     return false;
2589 
2590   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2591   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2592     return true;
2593   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2594     return true;
2595   return false;
2596 }
2597 
2598 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2599 static bool isExternC(VarTemplateDecl *) { return false; }
2600 
2601 /// \brief Check whether a redeclaration of an entity introduced by a
2602 /// using-declaration is valid, given that we know it's not an overload
2603 /// (nor a hidden tag declaration).
2604 template<typename ExpectedDecl>
2605 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2606                                    ExpectedDecl *New) {
2607   // C++11 [basic.scope.declarative]p4:
2608   //   Given a set of declarations in a single declarative region, each of
2609   //   which specifies the same unqualified name,
2610   //   -- they shall all refer to the same entity, or all refer to functions
2611   //      and function templates; or
2612   //   -- exactly one declaration shall declare a class name or enumeration
2613   //      name that is not a typedef name and the other declarations shall all
2614   //      refer to the same variable or enumerator, or all refer to functions
2615   //      and function templates; in this case the class name or enumeration
2616   //      name is hidden (3.3.10).
2617 
2618   // C++11 [namespace.udecl]p14:
2619   //   If a function declaration in namespace scope or block scope has the
2620   //   same name and the same parameter-type-list as a function introduced
2621   //   by a using-declaration, and the declarations do not declare the same
2622   //   function, the program is ill-formed.
2623 
2624   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2625   if (Old &&
2626       !Old->getDeclContext()->getRedeclContext()->Equals(
2627           New->getDeclContext()->getRedeclContext()) &&
2628       !(isExternC(Old) && isExternC(New)))
2629     Old = nullptr;
2630 
2631   if (!Old) {
2632     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2633     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2634     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2635     return true;
2636   }
2637   return false;
2638 }
2639 
2640 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2641                                             const FunctionDecl *B) {
2642   assert(A->getNumParams() == B->getNumParams());
2643 
2644   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2645     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2646     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2647     if (AttrA == AttrB)
2648       return true;
2649     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2650   };
2651 
2652   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2653 }
2654 
2655 /// MergeFunctionDecl - We just parsed a function 'New' from
2656 /// declarator D which has the same name and scope as a previous
2657 /// declaration 'Old'.  Figure out how to resolve this situation,
2658 /// merging decls or emitting diagnostics as appropriate.
2659 ///
2660 /// In C++, New and Old must be declarations that are not
2661 /// overloaded. Use IsOverload to determine whether New and Old are
2662 /// overloaded, and to select the Old declaration that New should be
2663 /// merged with.
2664 ///
2665 /// Returns true if there was an error, false otherwise.
2666 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2667                              Scope *S, bool MergeTypeWithOld) {
2668   // Verify the old decl was also a function.
2669   FunctionDecl *Old = OldD->getAsFunction();
2670   if (!Old) {
2671     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2672       if (New->getFriendObjectKind()) {
2673         Diag(New->getLocation(), diag::err_using_decl_friend);
2674         Diag(Shadow->getTargetDecl()->getLocation(),
2675              diag::note_using_decl_target);
2676         Diag(Shadow->getUsingDecl()->getLocation(),
2677              diag::note_using_decl) << 0;
2678         return true;
2679       }
2680 
2681       // Check whether the two declarations might declare the same function.
2682       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2683         return true;
2684       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2685     } else {
2686       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2687         << New->getDeclName();
2688       Diag(OldD->getLocation(), diag::note_previous_definition);
2689       return true;
2690     }
2691   }
2692 
2693   // If the old declaration is invalid, just give up here.
2694   if (Old->isInvalidDecl())
2695     return true;
2696 
2697   diag::kind PrevDiag;
2698   SourceLocation OldLocation;
2699   std::tie(PrevDiag, OldLocation) =
2700       getNoteDiagForInvalidRedeclaration(Old, New);
2701 
2702   // Don't complain about this if we're in GNU89 mode and the old function
2703   // is an extern inline function.
2704   // Don't complain about specializations. They are not supposed to have
2705   // storage classes.
2706   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2707       New->getStorageClass() == SC_Static &&
2708       Old->hasExternalFormalLinkage() &&
2709       !New->getTemplateSpecializationInfo() &&
2710       !canRedefineFunction(Old, getLangOpts())) {
2711     if (getLangOpts().MicrosoftExt) {
2712       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2713       Diag(OldLocation, PrevDiag);
2714     } else {
2715       Diag(New->getLocation(), diag::err_static_non_static) << New;
2716       Diag(OldLocation, PrevDiag);
2717       return true;
2718     }
2719   }
2720 
2721   if (New->hasAttr<InternalLinkageAttr>() &&
2722       !Old->hasAttr<InternalLinkageAttr>()) {
2723     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2724         << New->getDeclName();
2725     Diag(Old->getLocation(), diag::note_previous_definition);
2726     New->dropAttr<InternalLinkageAttr>();
2727   }
2728 
2729   // If a function is first declared with a calling convention, but is later
2730   // declared or defined without one, all following decls assume the calling
2731   // convention of the first.
2732   //
2733   // It's OK if a function is first declared without a calling convention,
2734   // but is later declared or defined with the default calling convention.
2735   //
2736   // To test if either decl has an explicit calling convention, we look for
2737   // AttributedType sugar nodes on the type as written.  If they are missing or
2738   // were canonicalized away, we assume the calling convention was implicit.
2739   //
2740   // Note also that we DO NOT return at this point, because we still have
2741   // other tests to run.
2742   QualType OldQType = Context.getCanonicalType(Old->getType());
2743   QualType NewQType = Context.getCanonicalType(New->getType());
2744   const FunctionType *OldType = cast<FunctionType>(OldQType);
2745   const FunctionType *NewType = cast<FunctionType>(NewQType);
2746   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2747   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2748   bool RequiresAdjustment = false;
2749 
2750   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2751     FunctionDecl *First = Old->getFirstDecl();
2752     const FunctionType *FT =
2753         First->getType().getCanonicalType()->castAs<FunctionType>();
2754     FunctionType::ExtInfo FI = FT->getExtInfo();
2755     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2756     if (!NewCCExplicit) {
2757       // Inherit the CC from the previous declaration if it was specified
2758       // there but not here.
2759       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2760       RequiresAdjustment = true;
2761     } else {
2762       // Calling conventions aren't compatible, so complain.
2763       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2764       Diag(New->getLocation(), diag::err_cconv_change)
2765         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2766         << !FirstCCExplicit
2767         << (!FirstCCExplicit ? "" :
2768             FunctionType::getNameForCallConv(FI.getCC()));
2769 
2770       // Put the note on the first decl, since it is the one that matters.
2771       Diag(First->getLocation(), diag::note_previous_declaration);
2772       return true;
2773     }
2774   }
2775 
2776   // FIXME: diagnose the other way around?
2777   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2778     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2779     RequiresAdjustment = true;
2780   }
2781 
2782   // Merge regparm attribute.
2783   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2784       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2785     if (NewTypeInfo.getHasRegParm()) {
2786       Diag(New->getLocation(), diag::err_regparm_mismatch)
2787         << NewType->getRegParmType()
2788         << OldType->getRegParmType();
2789       Diag(OldLocation, diag::note_previous_declaration);
2790       return true;
2791     }
2792 
2793     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2794     RequiresAdjustment = true;
2795   }
2796 
2797   // Merge ns_returns_retained attribute.
2798   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2799     if (NewTypeInfo.getProducesResult()) {
2800       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2801       Diag(OldLocation, diag::note_previous_declaration);
2802       return true;
2803     }
2804 
2805     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2806     RequiresAdjustment = true;
2807   }
2808 
2809   if (RequiresAdjustment) {
2810     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2811     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2812     New->setType(QualType(AdjustedType, 0));
2813     NewQType = Context.getCanonicalType(New->getType());
2814     NewType = cast<FunctionType>(NewQType);
2815   }
2816 
2817   // If this redeclaration makes the function inline, we may need to add it to
2818   // UndefinedButUsed.
2819   if (!Old->isInlined() && New->isInlined() &&
2820       !New->hasAttr<GNUInlineAttr>() &&
2821       !getLangOpts().GNUInline &&
2822       Old->isUsed(false) &&
2823       !Old->isDefined() && !New->isThisDeclarationADefinition())
2824     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2825                                            SourceLocation()));
2826 
2827   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2828   // about it.
2829   if (New->hasAttr<GNUInlineAttr>() &&
2830       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2831     UndefinedButUsed.erase(Old->getCanonicalDecl());
2832   }
2833 
2834   // If pass_object_size params don't match up perfectly, this isn't a valid
2835   // redeclaration.
2836   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2837       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2838     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2839         << New->getDeclName();
2840     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2841     return true;
2842   }
2843 
2844   if (getLangOpts().CPlusPlus) {
2845     // (C++98 13.1p2):
2846     //   Certain function declarations cannot be overloaded:
2847     //     -- Function declarations that differ only in the return type
2848     //        cannot be overloaded.
2849 
2850     // Go back to the type source info to compare the declared return types,
2851     // per C++1y [dcl.type.auto]p13:
2852     //   Redeclarations or specializations of a function or function template
2853     //   with a declared return type that uses a placeholder type shall also
2854     //   use that placeholder, not a deduced type.
2855     QualType OldDeclaredReturnType =
2856         (Old->getTypeSourceInfo()
2857              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2858              : OldType)->getReturnType();
2859     QualType NewDeclaredReturnType =
2860         (New->getTypeSourceInfo()
2861              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2862              : NewType)->getReturnType();
2863     QualType ResQT;
2864     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2865         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2866           New->isLocalExternDecl())) {
2867       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2868           OldDeclaredReturnType->isObjCObjectPointerType())
2869         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2870       if (ResQT.isNull()) {
2871         if (New->isCXXClassMember() && New->isOutOfLine())
2872           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2873               << New << New->getReturnTypeSourceRange();
2874         else
2875           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2876               << New->getReturnTypeSourceRange();
2877         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2878                                     << Old->getReturnTypeSourceRange();
2879         return true;
2880       }
2881       else
2882         NewQType = ResQT;
2883     }
2884 
2885     QualType OldReturnType = OldType->getReturnType();
2886     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2887     if (OldReturnType != NewReturnType) {
2888       // If this function has a deduced return type and has already been
2889       // defined, copy the deduced value from the old declaration.
2890       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2891       if (OldAT && OldAT->isDeduced()) {
2892         New->setType(
2893             SubstAutoType(New->getType(),
2894                           OldAT->isDependentType() ? Context.DependentTy
2895                                                    : OldAT->getDeducedType()));
2896         NewQType = Context.getCanonicalType(
2897             SubstAutoType(NewQType,
2898                           OldAT->isDependentType() ? Context.DependentTy
2899                                                    : OldAT->getDeducedType()));
2900       }
2901     }
2902 
2903     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2904     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2905     if (OldMethod && NewMethod) {
2906       // Preserve triviality.
2907       NewMethod->setTrivial(OldMethod->isTrivial());
2908 
2909       // MSVC allows explicit template specialization at class scope:
2910       // 2 CXXMethodDecls referring to the same function will be injected.
2911       // We don't want a redeclaration error.
2912       bool IsClassScopeExplicitSpecialization =
2913                               OldMethod->isFunctionTemplateSpecialization() &&
2914                               NewMethod->isFunctionTemplateSpecialization();
2915       bool isFriend = NewMethod->getFriendObjectKind();
2916 
2917       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2918           !IsClassScopeExplicitSpecialization) {
2919         //    -- Member function declarations with the same name and the
2920         //       same parameter types cannot be overloaded if any of them
2921         //       is a static member function declaration.
2922         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2923           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2924           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2925           return true;
2926         }
2927 
2928         // C++ [class.mem]p1:
2929         //   [...] A member shall not be declared twice in the
2930         //   member-specification, except that a nested class or member
2931         //   class template can be declared and then later defined.
2932         if (ActiveTemplateInstantiations.empty()) {
2933           unsigned NewDiag;
2934           if (isa<CXXConstructorDecl>(OldMethod))
2935             NewDiag = diag::err_constructor_redeclared;
2936           else if (isa<CXXDestructorDecl>(NewMethod))
2937             NewDiag = diag::err_destructor_redeclared;
2938           else if (isa<CXXConversionDecl>(NewMethod))
2939             NewDiag = diag::err_conv_function_redeclared;
2940           else
2941             NewDiag = diag::err_member_redeclared;
2942 
2943           Diag(New->getLocation(), NewDiag);
2944         } else {
2945           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2946             << New << New->getType();
2947         }
2948         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2949         return true;
2950 
2951       // Complain if this is an explicit declaration of a special
2952       // member that was initially declared implicitly.
2953       //
2954       // As an exception, it's okay to befriend such methods in order
2955       // to permit the implicit constructor/destructor/operator calls.
2956       } else if (OldMethod->isImplicit()) {
2957         if (isFriend) {
2958           NewMethod->setImplicit();
2959         } else {
2960           Diag(NewMethod->getLocation(),
2961                diag::err_definition_of_implicitly_declared_member)
2962             << New << getSpecialMember(OldMethod);
2963           return true;
2964         }
2965       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2966         Diag(NewMethod->getLocation(),
2967              diag::err_definition_of_explicitly_defaulted_member)
2968           << getSpecialMember(OldMethod);
2969         return true;
2970       }
2971     }
2972 
2973     // C++11 [dcl.attr.noreturn]p1:
2974     //   The first declaration of a function shall specify the noreturn
2975     //   attribute if any declaration of that function specifies the noreturn
2976     //   attribute.
2977     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2978     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2979       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2980       Diag(Old->getFirstDecl()->getLocation(),
2981            diag::note_noreturn_missing_first_decl);
2982     }
2983 
2984     // C++11 [dcl.attr.depend]p2:
2985     //   The first declaration of a function shall specify the
2986     //   carries_dependency attribute for its declarator-id if any declaration
2987     //   of the function specifies the carries_dependency attribute.
2988     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2989     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2990       Diag(CDA->getLocation(),
2991            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2992       Diag(Old->getFirstDecl()->getLocation(),
2993            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2994     }
2995 
2996     // (C++98 8.3.5p3):
2997     //   All declarations for a function shall agree exactly in both the
2998     //   return type and the parameter-type-list.
2999     // We also want to respect all the extended bits except noreturn.
3000 
3001     // noreturn should now match unless the old type info didn't have it.
3002     QualType OldQTypeForComparison = OldQType;
3003     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3004       assert(OldQType == QualType(OldType, 0));
3005       const FunctionType *OldTypeForComparison
3006         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3007       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3008       assert(OldQTypeForComparison.isCanonical());
3009     }
3010 
3011     if (haveIncompatibleLanguageLinkages(Old, New)) {
3012       // As a special case, retain the language linkage from previous
3013       // declarations of a friend function as an extension.
3014       //
3015       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3016       // and is useful because there's otherwise no way to specify language
3017       // linkage within class scope.
3018       //
3019       // Check cautiously as the friend object kind isn't yet complete.
3020       if (New->getFriendObjectKind() != Decl::FOK_None) {
3021         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3022         Diag(OldLocation, PrevDiag);
3023       } else {
3024         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3025         Diag(OldLocation, PrevDiag);
3026         return true;
3027       }
3028     }
3029 
3030     if (OldQTypeForComparison == NewQType)
3031       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3032 
3033     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3034         New->isLocalExternDecl()) {
3035       // It's OK if we couldn't merge types for a local function declaraton
3036       // if either the old or new type is dependent. We'll merge the types
3037       // when we instantiate the function.
3038       return false;
3039     }
3040 
3041     // Fall through for conflicting redeclarations and redefinitions.
3042   }
3043 
3044   // C: Function types need to be compatible, not identical. This handles
3045   // duplicate function decls like "void f(int); void f(enum X);" properly.
3046   if (!getLangOpts().CPlusPlus &&
3047       Context.typesAreCompatible(OldQType, NewQType)) {
3048     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3049     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3050     const FunctionProtoType *OldProto = nullptr;
3051     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3052         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3053       // The old declaration provided a function prototype, but the
3054       // new declaration does not. Merge in the prototype.
3055       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3056       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3057       NewQType =
3058           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3059                                   OldProto->getExtProtoInfo());
3060       New->setType(NewQType);
3061       New->setHasInheritedPrototype();
3062 
3063       // Synthesize parameters with the same types.
3064       SmallVector<ParmVarDecl*, 16> Params;
3065       for (const auto &ParamType : OldProto->param_types()) {
3066         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3067                                                  SourceLocation(), nullptr,
3068                                                  ParamType, /*TInfo=*/nullptr,
3069                                                  SC_None, nullptr);
3070         Param->setScopeInfo(0, Params.size());
3071         Param->setImplicit();
3072         Params.push_back(Param);
3073       }
3074 
3075       New->setParams(Params);
3076     }
3077 
3078     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3079   }
3080 
3081   // GNU C permits a K&R definition to follow a prototype declaration
3082   // if the declared types of the parameters in the K&R definition
3083   // match the types in the prototype declaration, even when the
3084   // promoted types of the parameters from the K&R definition differ
3085   // from the types in the prototype. GCC then keeps the types from
3086   // the prototype.
3087   //
3088   // If a variadic prototype is followed by a non-variadic K&R definition,
3089   // the K&R definition becomes variadic.  This is sort of an edge case, but
3090   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3091   // C99 6.9.1p8.
3092   if (!getLangOpts().CPlusPlus &&
3093       Old->hasPrototype() && !New->hasPrototype() &&
3094       New->getType()->getAs<FunctionProtoType>() &&
3095       Old->getNumParams() == New->getNumParams()) {
3096     SmallVector<QualType, 16> ArgTypes;
3097     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3098     const FunctionProtoType *OldProto
3099       = Old->getType()->getAs<FunctionProtoType>();
3100     const FunctionProtoType *NewProto
3101       = New->getType()->getAs<FunctionProtoType>();
3102 
3103     // Determine whether this is the GNU C extension.
3104     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3105                                                NewProto->getReturnType());
3106     bool LooseCompatible = !MergedReturn.isNull();
3107     for (unsigned Idx = 0, End = Old->getNumParams();
3108          LooseCompatible && Idx != End; ++Idx) {
3109       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3110       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3111       if (Context.typesAreCompatible(OldParm->getType(),
3112                                      NewProto->getParamType(Idx))) {
3113         ArgTypes.push_back(NewParm->getType());
3114       } else if (Context.typesAreCompatible(OldParm->getType(),
3115                                             NewParm->getType(),
3116                                             /*CompareUnqualified=*/true)) {
3117         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3118                                            NewProto->getParamType(Idx) };
3119         Warnings.push_back(Warn);
3120         ArgTypes.push_back(NewParm->getType());
3121       } else
3122         LooseCompatible = false;
3123     }
3124 
3125     if (LooseCompatible) {
3126       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3127         Diag(Warnings[Warn].NewParm->getLocation(),
3128              diag::ext_param_promoted_not_compatible_with_prototype)
3129           << Warnings[Warn].PromotedType
3130           << Warnings[Warn].OldParm->getType();
3131         if (Warnings[Warn].OldParm->getLocation().isValid())
3132           Diag(Warnings[Warn].OldParm->getLocation(),
3133                diag::note_previous_declaration);
3134       }
3135 
3136       if (MergeTypeWithOld)
3137         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3138                                              OldProto->getExtProtoInfo()));
3139       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3140     }
3141 
3142     // Fall through to diagnose conflicting types.
3143   }
3144 
3145   // A function that has already been declared has been redeclared or
3146   // defined with a different type; show an appropriate diagnostic.
3147 
3148   // If the previous declaration was an implicitly-generated builtin
3149   // declaration, then at the very least we should use a specialized note.
3150   unsigned BuiltinID;
3151   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3152     // If it's actually a library-defined builtin function like 'malloc'
3153     // or 'printf', just warn about the incompatible redeclaration.
3154     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3155       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3156       Diag(OldLocation, diag::note_previous_builtin_declaration)
3157         << Old << Old->getType();
3158 
3159       // If this is a global redeclaration, just forget hereafter
3160       // about the "builtin-ness" of the function.
3161       //
3162       // Doing this for local extern declarations is problematic.  If
3163       // the builtin declaration remains visible, a second invalid
3164       // local declaration will produce a hard error; if it doesn't
3165       // remain visible, a single bogus local redeclaration (which is
3166       // actually only a warning) could break all the downstream code.
3167       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3168         New->getIdentifier()->revertBuiltin();
3169 
3170       return false;
3171     }
3172 
3173     PrevDiag = diag::note_previous_builtin_declaration;
3174   }
3175 
3176   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3177   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3178   return true;
3179 }
3180 
3181 /// \brief Completes the merge of two function declarations that are
3182 /// known to be compatible.
3183 ///
3184 /// This routine handles the merging of attributes and other
3185 /// properties of function declarations from the old declaration to
3186 /// the new declaration, once we know that New is in fact a
3187 /// redeclaration of Old.
3188 ///
3189 /// \returns false
3190 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3191                                         Scope *S, bool MergeTypeWithOld) {
3192   // Merge the attributes
3193   mergeDeclAttributes(New, Old);
3194 
3195   // Merge "pure" flag.
3196   if (Old->isPure())
3197     New->setPure();
3198 
3199   // Merge "used" flag.
3200   if (Old->getMostRecentDecl()->isUsed(false))
3201     New->setIsUsed();
3202 
3203   // Merge attributes from the parameters.  These can mismatch with K&R
3204   // declarations.
3205   if (New->getNumParams() == Old->getNumParams())
3206       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3207         ParmVarDecl *NewParam = New->getParamDecl(i);
3208         ParmVarDecl *OldParam = Old->getParamDecl(i);
3209         mergeParamDeclAttributes(NewParam, OldParam, *this);
3210         mergeParamDeclTypes(NewParam, OldParam, *this);
3211       }
3212 
3213   if (getLangOpts().CPlusPlus)
3214     return MergeCXXFunctionDecl(New, Old, S);
3215 
3216   // Merge the function types so the we get the composite types for the return
3217   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3218   // was visible.
3219   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3220   if (!Merged.isNull() && MergeTypeWithOld)
3221     New->setType(Merged);
3222 
3223   return false;
3224 }
3225 
3226 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3227                                 ObjCMethodDecl *oldMethod) {
3228   // Merge the attributes, including deprecated/unavailable
3229   AvailabilityMergeKind MergeKind =
3230     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3231       ? AMK_ProtocolImplementation
3232       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3233                                                        : AMK_Override;
3234 
3235   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3236 
3237   // Merge attributes from the parameters.
3238   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3239                                        oe = oldMethod->param_end();
3240   for (ObjCMethodDecl::param_iterator
3241          ni = newMethod->param_begin(), ne = newMethod->param_end();
3242        ni != ne && oi != oe; ++ni, ++oi)
3243     mergeParamDeclAttributes(*ni, *oi, *this);
3244 
3245   CheckObjCMethodOverride(newMethod, oldMethod);
3246 }
3247 
3248 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3249   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3250 
3251   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3252          ? diag::err_redefinition_different_type
3253          : diag::err_redeclaration_different_type)
3254     << New->getDeclName() << New->getType() << Old->getType();
3255 
3256   diag::kind PrevDiag;
3257   SourceLocation OldLocation;
3258   std::tie(PrevDiag, OldLocation)
3259     = getNoteDiagForInvalidRedeclaration(Old, New);
3260   S.Diag(OldLocation, PrevDiag);
3261   New->setInvalidDecl();
3262 }
3263 
3264 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3265 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3266 /// emitting diagnostics as appropriate.
3267 ///
3268 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3269 /// to here in AddInitializerToDecl. We can't check them before the initializer
3270 /// is attached.
3271 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3272                              bool MergeTypeWithOld) {
3273   if (New->isInvalidDecl() || Old->isInvalidDecl())
3274     return;
3275 
3276   QualType MergedT;
3277   if (getLangOpts().CPlusPlus) {
3278     if (New->getType()->isUndeducedType()) {
3279       // We don't know what the new type is until the initializer is attached.
3280       return;
3281     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3282       // These could still be something that needs exception specs checked.
3283       return MergeVarDeclExceptionSpecs(New, Old);
3284     }
3285     // C++ [basic.link]p10:
3286     //   [...] the types specified by all declarations referring to a given
3287     //   object or function shall be identical, except that declarations for an
3288     //   array object can specify array types that differ by the presence or
3289     //   absence of a major array bound (8.3.4).
3290     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3291       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3292       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3293 
3294       // We are merging a variable declaration New into Old. If it has an array
3295       // bound, and that bound differs from Old's bound, we should diagnose the
3296       // mismatch.
3297       if (!NewArray->isIncompleteArrayType()) {
3298         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3299              PrevVD = PrevVD->getPreviousDecl()) {
3300           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3301           if (PrevVDTy->isIncompleteArrayType())
3302             continue;
3303 
3304           if (!Context.hasSameType(NewArray, PrevVDTy))
3305             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3306         }
3307       }
3308 
3309       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3310         if (Context.hasSameType(OldArray->getElementType(),
3311                                 NewArray->getElementType()))
3312           MergedT = New->getType();
3313       }
3314       // FIXME: Check visibility. New is hidden but has a complete type. If New
3315       // has no array bound, it should not inherit one from Old, if Old is not
3316       // visible.
3317       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3318         if (Context.hasSameType(OldArray->getElementType(),
3319                                 NewArray->getElementType()))
3320           MergedT = Old->getType();
3321       }
3322     }
3323     else if (New->getType()->isObjCObjectPointerType() &&
3324                Old->getType()->isObjCObjectPointerType()) {
3325       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3326                                               Old->getType());
3327     }
3328   } else {
3329     // C 6.2.7p2:
3330     //   All declarations that refer to the same object or function shall have
3331     //   compatible type.
3332     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3333   }
3334   if (MergedT.isNull()) {
3335     // It's OK if we couldn't merge types if either type is dependent, for a
3336     // block-scope variable. In other cases (static data members of class
3337     // templates, variable templates, ...), we require the types to be
3338     // equivalent.
3339     // FIXME: The C++ standard doesn't say anything about this.
3340     if ((New->getType()->isDependentType() ||
3341          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3342       // If the old type was dependent, we can't merge with it, so the new type
3343       // becomes dependent for now. We'll reproduce the original type when we
3344       // instantiate the TypeSourceInfo for the variable.
3345       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3346         New->setType(Context.DependentTy);
3347       return;
3348     }
3349     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3350   }
3351 
3352   // Don't actually update the type on the new declaration if the old
3353   // declaration was an extern declaration in a different scope.
3354   if (MergeTypeWithOld)
3355     New->setType(MergedT);
3356 }
3357 
3358 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3359                                   LookupResult &Previous) {
3360   // C11 6.2.7p4:
3361   //   For an identifier with internal or external linkage declared
3362   //   in a scope in which a prior declaration of that identifier is
3363   //   visible, if the prior declaration specifies internal or
3364   //   external linkage, the type of the identifier at the later
3365   //   declaration becomes the composite type.
3366   //
3367   // If the variable isn't visible, we do not merge with its type.
3368   if (Previous.isShadowed())
3369     return false;
3370 
3371   if (S.getLangOpts().CPlusPlus) {
3372     // C++11 [dcl.array]p3:
3373     //   If there is a preceding declaration of the entity in the same
3374     //   scope in which the bound was specified, an omitted array bound
3375     //   is taken to be the same as in that earlier declaration.
3376     return NewVD->isPreviousDeclInSameBlockScope() ||
3377            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3378             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3379   } else {
3380     // If the old declaration was function-local, don't merge with its
3381     // type unless we're in the same function.
3382     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3383            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3384   }
3385 }
3386 
3387 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3388 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3389 /// situation, merging decls or emitting diagnostics as appropriate.
3390 ///
3391 /// Tentative definition rules (C99 6.9.2p2) are checked by
3392 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3393 /// definitions here, since the initializer hasn't been attached.
3394 ///
3395 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3396   // If the new decl is already invalid, don't do any other checking.
3397   if (New->isInvalidDecl())
3398     return;
3399 
3400   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3401     return;
3402 
3403   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3404 
3405   // Verify the old decl was also a variable or variable template.
3406   VarDecl *Old = nullptr;
3407   VarTemplateDecl *OldTemplate = nullptr;
3408   if (Previous.isSingleResult()) {
3409     if (NewTemplate) {
3410       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3411       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3412 
3413       if (auto *Shadow =
3414               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3415         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3416           return New->setInvalidDecl();
3417     } else {
3418       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3419 
3420       if (auto *Shadow =
3421               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3422         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3423           return New->setInvalidDecl();
3424     }
3425   }
3426   if (!Old) {
3427     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3428       << New->getDeclName();
3429     Diag(Previous.getRepresentativeDecl()->getLocation(),
3430          diag::note_previous_definition);
3431     return New->setInvalidDecl();
3432   }
3433 
3434   // Ensure the template parameters are compatible.
3435   if (NewTemplate &&
3436       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3437                                       OldTemplate->getTemplateParameters(),
3438                                       /*Complain=*/true, TPL_TemplateMatch))
3439     return New->setInvalidDecl();
3440 
3441   // C++ [class.mem]p1:
3442   //   A member shall not be declared twice in the member-specification [...]
3443   //
3444   // Here, we need only consider static data members.
3445   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3446     Diag(New->getLocation(), diag::err_duplicate_member)
3447       << New->getIdentifier();
3448     Diag(Old->getLocation(), diag::note_previous_declaration);
3449     New->setInvalidDecl();
3450   }
3451 
3452   mergeDeclAttributes(New, Old);
3453   // Warn if an already-declared variable is made a weak_import in a subsequent
3454   // declaration
3455   if (New->hasAttr<WeakImportAttr>() &&
3456       Old->getStorageClass() == SC_None &&
3457       !Old->hasAttr<WeakImportAttr>()) {
3458     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3459     Diag(Old->getLocation(), diag::note_previous_definition);
3460     // Remove weak_import attribute on new declaration.
3461     New->dropAttr<WeakImportAttr>();
3462   }
3463 
3464   if (New->hasAttr<InternalLinkageAttr>() &&
3465       !Old->hasAttr<InternalLinkageAttr>()) {
3466     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3467         << New->getDeclName();
3468     Diag(Old->getLocation(), diag::note_previous_definition);
3469     New->dropAttr<InternalLinkageAttr>();
3470   }
3471 
3472   // Merge the types.
3473   VarDecl *MostRecent = Old->getMostRecentDecl();
3474   if (MostRecent != Old) {
3475     MergeVarDeclTypes(New, MostRecent,
3476                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3477     if (New->isInvalidDecl())
3478       return;
3479   }
3480 
3481   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3482   if (New->isInvalidDecl())
3483     return;
3484 
3485   diag::kind PrevDiag;
3486   SourceLocation OldLocation;
3487   std::tie(PrevDiag, OldLocation) =
3488       getNoteDiagForInvalidRedeclaration(Old, New);
3489 
3490   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3491   if (New->getStorageClass() == SC_Static &&
3492       !New->isStaticDataMember() &&
3493       Old->hasExternalFormalLinkage()) {
3494     if (getLangOpts().MicrosoftExt) {
3495       Diag(New->getLocation(), diag::ext_static_non_static)
3496           << New->getDeclName();
3497       Diag(OldLocation, PrevDiag);
3498     } else {
3499       Diag(New->getLocation(), diag::err_static_non_static)
3500           << New->getDeclName();
3501       Diag(OldLocation, PrevDiag);
3502       return New->setInvalidDecl();
3503     }
3504   }
3505   // C99 6.2.2p4:
3506   //   For an identifier declared with the storage-class specifier
3507   //   extern in a scope in which a prior declaration of that
3508   //   identifier is visible,23) if the prior declaration specifies
3509   //   internal or external linkage, the linkage of the identifier at
3510   //   the later declaration is the same as the linkage specified at
3511   //   the prior declaration. If no prior declaration is visible, or
3512   //   if the prior declaration specifies no linkage, then the
3513   //   identifier has external linkage.
3514   if (New->hasExternalStorage() && Old->hasLinkage())
3515     /* Okay */;
3516   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3517            !New->isStaticDataMember() &&
3518            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3519     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3520     Diag(OldLocation, PrevDiag);
3521     return New->setInvalidDecl();
3522   }
3523 
3524   // Check if extern is followed by non-extern and vice-versa.
3525   if (New->hasExternalStorage() &&
3526       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3527     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3528     Diag(OldLocation, PrevDiag);
3529     return New->setInvalidDecl();
3530   }
3531   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3532       !New->hasExternalStorage()) {
3533     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3534     Diag(OldLocation, PrevDiag);
3535     return New->setInvalidDecl();
3536   }
3537 
3538   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3539 
3540   // FIXME: The test for external storage here seems wrong? We still
3541   // need to check for mismatches.
3542   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3543       // Don't complain about out-of-line definitions of static members.
3544       !(Old->getLexicalDeclContext()->isRecord() &&
3545         !New->getLexicalDeclContext()->isRecord())) {
3546     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3547     Diag(OldLocation, PrevDiag);
3548     return New->setInvalidDecl();
3549   }
3550 
3551   if (New->getTLSKind() != Old->getTLSKind()) {
3552     if (!Old->getTLSKind()) {
3553       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3554       Diag(OldLocation, PrevDiag);
3555     } else if (!New->getTLSKind()) {
3556       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3557       Diag(OldLocation, PrevDiag);
3558     } else {
3559       // Do not allow redeclaration to change the variable between requiring
3560       // static and dynamic initialization.
3561       // FIXME: GCC allows this, but uses the TLS keyword on the first
3562       // declaration to determine the kind. Do we need to be compatible here?
3563       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3564         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3565       Diag(OldLocation, PrevDiag);
3566     }
3567   }
3568 
3569   // C++ doesn't have tentative definitions, so go right ahead and check here.
3570   VarDecl *Def;
3571   if (getLangOpts().CPlusPlus &&
3572       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3573       (Def = Old->getDefinition())) {
3574     NamedDecl *Hidden = nullptr;
3575     if (!hasVisibleDefinition(Def, &Hidden) &&
3576         (New->getFormalLinkage() == InternalLinkage ||
3577          New->getDescribedVarTemplate() ||
3578          New->getNumTemplateParameterLists() ||
3579          New->getDeclContext()->isDependentContext())) {
3580       // The previous definition is hidden, and multiple definitions are
3581       // permitted (in separate TUs). Form another definition of it.
3582     } else {
3583       Diag(New->getLocation(), diag::err_redefinition) << New;
3584       Diag(Def->getLocation(), diag::note_previous_definition);
3585       New->setInvalidDecl();
3586       return;
3587     }
3588   }
3589 
3590   if (haveIncompatibleLanguageLinkages(Old, New)) {
3591     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3592     Diag(OldLocation, PrevDiag);
3593     New->setInvalidDecl();
3594     return;
3595   }
3596 
3597   // Merge "used" flag.
3598   if (Old->getMostRecentDecl()->isUsed(false))
3599     New->setIsUsed();
3600 
3601   // Keep a chain of previous declarations.
3602   New->setPreviousDecl(Old);
3603   if (NewTemplate)
3604     NewTemplate->setPreviousDecl(OldTemplate);
3605 
3606   // Inherit access appropriately.
3607   New->setAccess(Old->getAccess());
3608   if (NewTemplate)
3609     NewTemplate->setAccess(New->getAccess());
3610 }
3611 
3612 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3613 /// no declarator (e.g. "struct foo;") is parsed.
3614 Decl *
3615 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3616                                  RecordDecl *&AnonRecord) {
3617   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3618                                     AnonRecord);
3619 }
3620 
3621 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3622 // disambiguate entities defined in different scopes.
3623 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3624 // compatibility.
3625 // We will pick our mangling number depending on which version of MSVC is being
3626 // targeted.
3627 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3628   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3629              ? S->getMSCurManglingNumber()
3630              : S->getMSLastManglingNumber();
3631 }
3632 
3633 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3634   if (!Context.getLangOpts().CPlusPlus)
3635     return;
3636 
3637   if (isa<CXXRecordDecl>(Tag->getParent())) {
3638     // If this tag is the direct child of a class, number it if
3639     // it is anonymous.
3640     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3641       return;
3642     MangleNumberingContext &MCtx =
3643         Context.getManglingNumberContext(Tag->getParent());
3644     Context.setManglingNumber(
3645         Tag, MCtx.getManglingNumber(
3646                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3647     return;
3648   }
3649 
3650   // If this tag isn't a direct child of a class, number it if it is local.
3651   Decl *ManglingContextDecl;
3652   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3653           Tag->getDeclContext(), ManglingContextDecl)) {
3654     Context.setManglingNumber(
3655         Tag, MCtx->getManglingNumber(
3656                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3657   }
3658 }
3659 
3660 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3661                                         TypedefNameDecl *NewTD) {
3662   if (TagFromDeclSpec->isInvalidDecl())
3663     return;
3664 
3665   // Do nothing if the tag already has a name for linkage purposes.
3666   if (TagFromDeclSpec->hasNameForLinkage())
3667     return;
3668 
3669   // A well-formed anonymous tag must always be a TUK_Definition.
3670   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3671 
3672   // The type must match the tag exactly;  no qualifiers allowed.
3673   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3674                            Context.getTagDeclType(TagFromDeclSpec))) {
3675     if (getLangOpts().CPlusPlus)
3676       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3677     return;
3678   }
3679 
3680   // If we've already computed linkage for the anonymous tag, then
3681   // adding a typedef name for the anonymous decl can change that
3682   // linkage, which might be a serious problem.  Diagnose this as
3683   // unsupported and ignore the typedef name.  TODO: we should
3684   // pursue this as a language defect and establish a formal rule
3685   // for how to handle it.
3686   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3687     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3688 
3689     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3690     tagLoc = getLocForEndOfToken(tagLoc);
3691 
3692     llvm::SmallString<40> textToInsert;
3693     textToInsert += ' ';
3694     textToInsert += NewTD->getIdentifier()->getName();
3695     Diag(tagLoc, diag::note_typedef_changes_linkage)
3696         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3697     return;
3698   }
3699 
3700   // Otherwise, set this is the anon-decl typedef for the tag.
3701   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3702 }
3703 
3704 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3705   switch (T) {
3706   case DeclSpec::TST_class:
3707     return 0;
3708   case DeclSpec::TST_struct:
3709     return 1;
3710   case DeclSpec::TST_interface:
3711     return 2;
3712   case DeclSpec::TST_union:
3713     return 3;
3714   case DeclSpec::TST_enum:
3715     return 4;
3716   default:
3717     llvm_unreachable("unexpected type specifier");
3718   }
3719 }
3720 
3721 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3722 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3723 /// parameters to cope with template friend declarations.
3724 Decl *
3725 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3726                                  MultiTemplateParamsArg TemplateParams,
3727                                  bool IsExplicitInstantiation,
3728                                  RecordDecl *&AnonRecord) {
3729   Decl *TagD = nullptr;
3730   TagDecl *Tag = nullptr;
3731   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3732       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3733       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3734       DS.getTypeSpecType() == DeclSpec::TST_union ||
3735       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3736     TagD = DS.getRepAsDecl();
3737 
3738     if (!TagD) // We probably had an error
3739       return nullptr;
3740 
3741     // Note that the above type specs guarantee that the
3742     // type rep is a Decl, whereas in many of the others
3743     // it's a Type.
3744     if (isa<TagDecl>(TagD))
3745       Tag = cast<TagDecl>(TagD);
3746     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3747       Tag = CTD->getTemplatedDecl();
3748   }
3749 
3750   if (Tag) {
3751     handleTagNumbering(Tag, S);
3752     Tag->setFreeStanding();
3753     if (Tag->isInvalidDecl())
3754       return Tag;
3755   }
3756 
3757   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3758     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3759     // or incomplete types shall not be restrict-qualified."
3760     if (TypeQuals & DeclSpec::TQ_restrict)
3761       Diag(DS.getRestrictSpecLoc(),
3762            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3763            << DS.getSourceRange();
3764   }
3765 
3766   if (DS.isConstexprSpecified()) {
3767     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3768     // and definitions of functions and variables.
3769     if (Tag)
3770       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3771           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3772     else
3773       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3774     // Don't emit warnings after this error.
3775     return TagD;
3776   }
3777 
3778   if (DS.isConceptSpecified()) {
3779     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3780     // either a function concept and its definition or a variable concept and
3781     // its initializer.
3782     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3783     return TagD;
3784   }
3785 
3786   DiagnoseFunctionSpecifiers(DS);
3787 
3788   if (DS.isFriendSpecified()) {
3789     // If we're dealing with a decl but not a TagDecl, assume that
3790     // whatever routines created it handled the friendship aspect.
3791     if (TagD && !Tag)
3792       return nullptr;
3793     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3794   }
3795 
3796   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3797   bool IsExplicitSpecialization =
3798     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3799   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3800       !IsExplicitInstantiation && !IsExplicitSpecialization &&
3801       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3802     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3803     // nested-name-specifier unless it is an explicit instantiation
3804     // or an explicit specialization.
3805     //
3806     // FIXME: We allow class template partial specializations here too, per the
3807     // obvious intent of DR1819.
3808     //
3809     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3810     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3811         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3812     return nullptr;
3813   }
3814 
3815   // Track whether this decl-specifier declares anything.
3816   bool DeclaresAnything = true;
3817 
3818   // Handle anonymous struct definitions.
3819   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3820     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3821         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3822       if (getLangOpts().CPlusPlus ||
3823           Record->getDeclContext()->isRecord()) {
3824         // If CurContext is a DeclContext that can contain statements,
3825         // RecursiveASTVisitor won't visit the decls that
3826         // BuildAnonymousStructOrUnion() will put into CurContext.
3827         // Also store them here so that they can be part of the
3828         // DeclStmt that gets created in this case.
3829         // FIXME: Also return the IndirectFieldDecls created by
3830         // BuildAnonymousStructOr union, for the same reason?
3831         if (CurContext->isFunctionOrMethod())
3832           AnonRecord = Record;
3833         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3834                                            Context.getPrintingPolicy());
3835       }
3836 
3837       DeclaresAnything = false;
3838     }
3839   }
3840 
3841   // C11 6.7.2.1p2:
3842   //   A struct-declaration that does not declare an anonymous structure or
3843   //   anonymous union shall contain a struct-declarator-list.
3844   //
3845   // This rule also existed in C89 and C99; the grammar for struct-declaration
3846   // did not permit a struct-declaration without a struct-declarator-list.
3847   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3848       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3849     // Check for Microsoft C extension: anonymous struct/union member.
3850     // Handle 2 kinds of anonymous struct/union:
3851     //   struct STRUCT;
3852     //   union UNION;
3853     // and
3854     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3855     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3856     if ((Tag && Tag->getDeclName()) ||
3857         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3858       RecordDecl *Record = nullptr;
3859       if (Tag)
3860         Record = dyn_cast<RecordDecl>(Tag);
3861       else if (const RecordType *RT =
3862                    DS.getRepAsType().get()->getAsStructureType())
3863         Record = RT->getDecl();
3864       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3865         Record = UT->getDecl();
3866 
3867       if (Record && getLangOpts().MicrosoftExt) {
3868         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3869           << Record->isUnion() << DS.getSourceRange();
3870         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3871       }
3872 
3873       DeclaresAnything = false;
3874     }
3875   }
3876 
3877   // Skip all the checks below if we have a type error.
3878   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3879       (TagD && TagD->isInvalidDecl()))
3880     return TagD;
3881 
3882   if (getLangOpts().CPlusPlus &&
3883       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3884     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3885       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3886           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3887         DeclaresAnything = false;
3888 
3889   if (!DS.isMissingDeclaratorOk()) {
3890     // Customize diagnostic for a typedef missing a name.
3891     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3892       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3893         << DS.getSourceRange();
3894     else
3895       DeclaresAnything = false;
3896   }
3897 
3898   if (DS.isModulePrivateSpecified() &&
3899       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3900     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3901       << Tag->getTagKind()
3902       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3903 
3904   ActOnDocumentableDecl(TagD);
3905 
3906   // C 6.7/2:
3907   //   A declaration [...] shall declare at least a declarator [...], a tag,
3908   //   or the members of an enumeration.
3909   // C++ [dcl.dcl]p3:
3910   //   [If there are no declarators], and except for the declaration of an
3911   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3912   //   names into the program, or shall redeclare a name introduced by a
3913   //   previous declaration.
3914   if (!DeclaresAnything) {
3915     // In C, we allow this as a (popular) extension / bug. Don't bother
3916     // producing further diagnostics for redundant qualifiers after this.
3917     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3918     return TagD;
3919   }
3920 
3921   // C++ [dcl.stc]p1:
3922   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3923   //   init-declarator-list of the declaration shall not be empty.
3924   // C++ [dcl.fct.spec]p1:
3925   //   If a cv-qualifier appears in a decl-specifier-seq, the
3926   //   init-declarator-list of the declaration shall not be empty.
3927   //
3928   // Spurious qualifiers here appear to be valid in C.
3929   unsigned DiagID = diag::warn_standalone_specifier;
3930   if (getLangOpts().CPlusPlus)
3931     DiagID = diag::ext_standalone_specifier;
3932 
3933   // Note that a linkage-specification sets a storage class, but
3934   // 'extern "C" struct foo;' is actually valid and not theoretically
3935   // useless.
3936   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3937     if (SCS == DeclSpec::SCS_mutable)
3938       // Since mutable is not a viable storage class specifier in C, there is
3939       // no reason to treat it as an extension. Instead, diagnose as an error.
3940       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3941     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3942       Diag(DS.getStorageClassSpecLoc(), DiagID)
3943         << DeclSpec::getSpecifierName(SCS);
3944   }
3945 
3946   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3947     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3948       << DeclSpec::getSpecifierName(TSCS);
3949   if (DS.getTypeQualifiers()) {
3950     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3951       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3952     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3953       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3954     // Restrict is covered above.
3955     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3956       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3957   }
3958 
3959   // Warn about ignored type attributes, for example:
3960   // __attribute__((aligned)) struct A;
3961   // Attributes should be placed after tag to apply to type declaration.
3962   if (!DS.getAttributes().empty()) {
3963     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3964     if (TypeSpecType == DeclSpec::TST_class ||
3965         TypeSpecType == DeclSpec::TST_struct ||
3966         TypeSpecType == DeclSpec::TST_interface ||
3967         TypeSpecType == DeclSpec::TST_union ||
3968         TypeSpecType == DeclSpec::TST_enum) {
3969       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
3970            attrs = attrs->getNext())
3971         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3972             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
3973     }
3974   }
3975 
3976   return TagD;
3977 }
3978 
3979 /// We are trying to inject an anonymous member into the given scope;
3980 /// check if there's an existing declaration that can't be overloaded.
3981 ///
3982 /// \return true if this is a forbidden redeclaration
3983 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3984                                          Scope *S,
3985                                          DeclContext *Owner,
3986                                          DeclarationName Name,
3987                                          SourceLocation NameLoc,
3988                                          bool IsUnion) {
3989   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3990                  Sema::ForRedeclaration);
3991   if (!SemaRef.LookupName(R, S)) return false;
3992 
3993   // Pick a representative declaration.
3994   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3995   assert(PrevDecl && "Expected a non-null Decl");
3996 
3997   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3998     return false;
3999 
4000   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4001     << IsUnion << Name;
4002   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4003 
4004   return true;
4005 }
4006 
4007 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4008 /// anonymous struct or union AnonRecord into the owning context Owner
4009 /// and scope S. This routine will be invoked just after we realize
4010 /// that an unnamed union or struct is actually an anonymous union or
4011 /// struct, e.g.,
4012 ///
4013 /// @code
4014 /// union {
4015 ///   int i;
4016 ///   float f;
4017 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4018 ///    // f into the surrounding scope.x
4019 /// @endcode
4020 ///
4021 /// This routine is recursive, injecting the names of nested anonymous
4022 /// structs/unions into the owning context and scope as well.
4023 static bool
4024 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4025                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4026                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4027   bool Invalid = false;
4028 
4029   // Look every FieldDecl and IndirectFieldDecl with a name.
4030   for (auto *D : AnonRecord->decls()) {
4031     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4032         cast<NamedDecl>(D)->getDeclName()) {
4033       ValueDecl *VD = cast<ValueDecl>(D);
4034       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4035                                        VD->getLocation(),
4036                                        AnonRecord->isUnion())) {
4037         // C++ [class.union]p2:
4038         //   The names of the members of an anonymous union shall be
4039         //   distinct from the names of any other entity in the
4040         //   scope in which the anonymous union is declared.
4041         Invalid = true;
4042       } else {
4043         // C++ [class.union]p2:
4044         //   For the purpose of name lookup, after the anonymous union
4045         //   definition, the members of the anonymous union are
4046         //   considered to have been defined in the scope in which the
4047         //   anonymous union is declared.
4048         unsigned OldChainingSize = Chaining.size();
4049         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4050           Chaining.append(IF->chain_begin(), IF->chain_end());
4051         else
4052           Chaining.push_back(VD);
4053 
4054         assert(Chaining.size() >= 2);
4055         NamedDecl **NamedChain =
4056           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4057         for (unsigned i = 0; i < Chaining.size(); i++)
4058           NamedChain[i] = Chaining[i];
4059 
4060         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4061             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4062             VD->getType(), NamedChain, Chaining.size());
4063 
4064         for (const auto *Attr : VD->attrs())
4065           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4066 
4067         IndirectField->setAccess(AS);
4068         IndirectField->setImplicit();
4069         SemaRef.PushOnScopeChains(IndirectField, S);
4070 
4071         // That includes picking up the appropriate access specifier.
4072         if (AS != AS_none) IndirectField->setAccess(AS);
4073 
4074         Chaining.resize(OldChainingSize);
4075       }
4076     }
4077   }
4078 
4079   return Invalid;
4080 }
4081 
4082 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4083 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4084 /// illegal input values are mapped to SC_None.
4085 static StorageClass
4086 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4087   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4088   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4089          "Parser allowed 'typedef' as storage class VarDecl.");
4090   switch (StorageClassSpec) {
4091   case DeclSpec::SCS_unspecified:    return SC_None;
4092   case DeclSpec::SCS_extern:
4093     if (DS.isExternInLinkageSpec())
4094       return SC_None;
4095     return SC_Extern;
4096   case DeclSpec::SCS_static:         return SC_Static;
4097   case DeclSpec::SCS_auto:           return SC_Auto;
4098   case DeclSpec::SCS_register:       return SC_Register;
4099   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4100     // Illegal SCSs map to None: error reporting is up to the caller.
4101   case DeclSpec::SCS_mutable:        // Fall through.
4102   case DeclSpec::SCS_typedef:        return SC_None;
4103   }
4104   llvm_unreachable("unknown storage class specifier");
4105 }
4106 
4107 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4108   assert(Record->hasInClassInitializer());
4109 
4110   for (const auto *I : Record->decls()) {
4111     const auto *FD = dyn_cast<FieldDecl>(I);
4112     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4113       FD = IFD->getAnonField();
4114     if (FD && FD->hasInClassInitializer())
4115       return FD->getLocation();
4116   }
4117 
4118   llvm_unreachable("couldn't find in-class initializer");
4119 }
4120 
4121 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4122                                       SourceLocation DefaultInitLoc) {
4123   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4124     return;
4125 
4126   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4127   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4128 }
4129 
4130 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4131                                       CXXRecordDecl *AnonUnion) {
4132   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4133     return;
4134 
4135   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4136 }
4137 
4138 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4139 /// anonymous structure or union. Anonymous unions are a C++ feature
4140 /// (C++ [class.union]) and a C11 feature; anonymous structures
4141 /// are a C11 feature and GNU C++ extension.
4142 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4143                                         AccessSpecifier AS,
4144                                         RecordDecl *Record,
4145                                         const PrintingPolicy &Policy) {
4146   DeclContext *Owner = Record->getDeclContext();
4147 
4148   // Diagnose whether this anonymous struct/union is an extension.
4149   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4150     Diag(Record->getLocation(), diag::ext_anonymous_union);
4151   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4152     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4153   else if (!Record->isUnion() && !getLangOpts().C11)
4154     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4155 
4156   // C and C++ require different kinds of checks for anonymous
4157   // structs/unions.
4158   bool Invalid = false;
4159   if (getLangOpts().CPlusPlus) {
4160     const char *PrevSpec = nullptr;
4161     unsigned DiagID;
4162     if (Record->isUnion()) {
4163       // C++ [class.union]p6:
4164       //   Anonymous unions declared in a named namespace or in the
4165       //   global namespace shall be declared static.
4166       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4167           (isa<TranslationUnitDecl>(Owner) ||
4168            (isa<NamespaceDecl>(Owner) &&
4169             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4170         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4171           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4172 
4173         // Recover by adding 'static'.
4174         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4175                                PrevSpec, DiagID, Policy);
4176       }
4177       // C++ [class.union]p6:
4178       //   A storage class is not allowed in a declaration of an
4179       //   anonymous union in a class scope.
4180       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4181                isa<RecordDecl>(Owner)) {
4182         Diag(DS.getStorageClassSpecLoc(),
4183              diag::err_anonymous_union_with_storage_spec)
4184           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4185 
4186         // Recover by removing the storage specifier.
4187         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4188                                SourceLocation(),
4189                                PrevSpec, DiagID, Context.getPrintingPolicy());
4190       }
4191     }
4192 
4193     // Ignore const/volatile/restrict qualifiers.
4194     if (DS.getTypeQualifiers()) {
4195       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4196         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4197           << Record->isUnion() << "const"
4198           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4199       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4200         Diag(DS.getVolatileSpecLoc(),
4201              diag::ext_anonymous_struct_union_qualified)
4202           << Record->isUnion() << "volatile"
4203           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4204       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4205         Diag(DS.getRestrictSpecLoc(),
4206              diag::ext_anonymous_struct_union_qualified)
4207           << Record->isUnion() << "restrict"
4208           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4209       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4210         Diag(DS.getAtomicSpecLoc(),
4211              diag::ext_anonymous_struct_union_qualified)
4212           << Record->isUnion() << "_Atomic"
4213           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4214 
4215       DS.ClearTypeQualifiers();
4216     }
4217 
4218     // C++ [class.union]p2:
4219     //   The member-specification of an anonymous union shall only
4220     //   define non-static data members. [Note: nested types and
4221     //   functions cannot be declared within an anonymous union. ]
4222     for (auto *Mem : Record->decls()) {
4223       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4224         // C++ [class.union]p3:
4225         //   An anonymous union shall not have private or protected
4226         //   members (clause 11).
4227         assert(FD->getAccess() != AS_none);
4228         if (FD->getAccess() != AS_public) {
4229           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4230             << Record->isUnion() << (FD->getAccess() == AS_protected);
4231           Invalid = true;
4232         }
4233 
4234         // C++ [class.union]p1
4235         //   An object of a class with a non-trivial constructor, a non-trivial
4236         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4237         //   assignment operator cannot be a member of a union, nor can an
4238         //   array of such objects.
4239         if (CheckNontrivialField(FD))
4240           Invalid = true;
4241       } else if (Mem->isImplicit()) {
4242         // Any implicit members are fine.
4243       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4244         // This is a type that showed up in an
4245         // elaborated-type-specifier inside the anonymous struct or
4246         // union, but which actually declares a type outside of the
4247         // anonymous struct or union. It's okay.
4248       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4249         if (!MemRecord->isAnonymousStructOrUnion() &&
4250             MemRecord->getDeclName()) {
4251           // Visual C++ allows type definition in anonymous struct or union.
4252           if (getLangOpts().MicrosoftExt)
4253             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4254               << Record->isUnion();
4255           else {
4256             // This is a nested type declaration.
4257             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4258               << Record->isUnion();
4259             Invalid = true;
4260           }
4261         } else {
4262           // This is an anonymous type definition within another anonymous type.
4263           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4264           // not part of standard C++.
4265           Diag(MemRecord->getLocation(),
4266                diag::ext_anonymous_record_with_anonymous_type)
4267             << Record->isUnion();
4268         }
4269       } else if (isa<AccessSpecDecl>(Mem)) {
4270         // Any access specifier is fine.
4271       } else if (isa<StaticAssertDecl>(Mem)) {
4272         // In C++1z, static_assert declarations are also fine.
4273       } else {
4274         // We have something that isn't a non-static data
4275         // member. Complain about it.
4276         unsigned DK = diag::err_anonymous_record_bad_member;
4277         if (isa<TypeDecl>(Mem))
4278           DK = diag::err_anonymous_record_with_type;
4279         else if (isa<FunctionDecl>(Mem))
4280           DK = diag::err_anonymous_record_with_function;
4281         else if (isa<VarDecl>(Mem))
4282           DK = diag::err_anonymous_record_with_static;
4283 
4284         // Visual C++ allows type definition in anonymous struct or union.
4285         if (getLangOpts().MicrosoftExt &&
4286             DK == diag::err_anonymous_record_with_type)
4287           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4288             << Record->isUnion();
4289         else {
4290           Diag(Mem->getLocation(), DK) << Record->isUnion();
4291           Invalid = true;
4292         }
4293       }
4294     }
4295 
4296     // C++11 [class.union]p8 (DR1460):
4297     //   At most one variant member of a union may have a
4298     //   brace-or-equal-initializer.
4299     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4300         Owner->isRecord())
4301       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4302                                 cast<CXXRecordDecl>(Record));
4303   }
4304 
4305   if (!Record->isUnion() && !Owner->isRecord()) {
4306     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4307       << getLangOpts().CPlusPlus;
4308     Invalid = true;
4309   }
4310 
4311   // Mock up a declarator.
4312   Declarator Dc(DS, Declarator::MemberContext);
4313   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4314   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4315 
4316   // Create a declaration for this anonymous struct/union.
4317   NamedDecl *Anon = nullptr;
4318   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4319     Anon = FieldDecl::Create(Context, OwningClass,
4320                              DS.getLocStart(),
4321                              Record->getLocation(),
4322                              /*IdentifierInfo=*/nullptr,
4323                              Context.getTypeDeclType(Record),
4324                              TInfo,
4325                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4326                              /*InitStyle=*/ICIS_NoInit);
4327     Anon->setAccess(AS);
4328     if (getLangOpts().CPlusPlus)
4329       FieldCollector->Add(cast<FieldDecl>(Anon));
4330   } else {
4331     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4332     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4333     if (SCSpec == DeclSpec::SCS_mutable) {
4334       // mutable can only appear on non-static class members, so it's always
4335       // an error here
4336       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4337       Invalid = true;
4338       SC = SC_None;
4339     }
4340 
4341     Anon = VarDecl::Create(Context, Owner,
4342                            DS.getLocStart(),
4343                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4344                            Context.getTypeDeclType(Record),
4345                            TInfo, SC);
4346 
4347     // Default-initialize the implicit variable. This initialization will be
4348     // trivial in almost all cases, except if a union member has an in-class
4349     // initializer:
4350     //   union { int n = 0; };
4351     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4352   }
4353   Anon->setImplicit();
4354 
4355   // Mark this as an anonymous struct/union type.
4356   Record->setAnonymousStructOrUnion(true);
4357 
4358   // Add the anonymous struct/union object to the current
4359   // context. We'll be referencing this object when we refer to one of
4360   // its members.
4361   Owner->addDecl(Anon);
4362 
4363   // Inject the members of the anonymous struct/union into the owning
4364   // context and into the identifier resolver chain for name lookup
4365   // purposes.
4366   SmallVector<NamedDecl*, 2> Chain;
4367   Chain.push_back(Anon);
4368 
4369   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4370     Invalid = true;
4371 
4372   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4373     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4374       Decl *ManglingContextDecl;
4375       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4376               NewVD->getDeclContext(), ManglingContextDecl)) {
4377         Context.setManglingNumber(
4378             NewVD, MCtx->getManglingNumber(
4379                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4380         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4381       }
4382     }
4383   }
4384 
4385   if (Invalid)
4386     Anon->setInvalidDecl();
4387 
4388   return Anon;
4389 }
4390 
4391 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4392 /// Microsoft C anonymous structure.
4393 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4394 /// Example:
4395 ///
4396 /// struct A { int a; };
4397 /// struct B { struct A; int b; };
4398 ///
4399 /// void foo() {
4400 ///   B var;
4401 ///   var.a = 3;
4402 /// }
4403 ///
4404 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4405                                            RecordDecl *Record) {
4406   assert(Record && "expected a record!");
4407 
4408   // Mock up a declarator.
4409   Declarator Dc(DS, Declarator::TypeNameContext);
4410   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4411   assert(TInfo && "couldn't build declarator info for anonymous struct");
4412 
4413   auto *ParentDecl = cast<RecordDecl>(CurContext);
4414   QualType RecTy = Context.getTypeDeclType(Record);
4415 
4416   // Create a declaration for this anonymous struct.
4417   NamedDecl *Anon = FieldDecl::Create(Context,
4418                              ParentDecl,
4419                              DS.getLocStart(),
4420                              DS.getLocStart(),
4421                              /*IdentifierInfo=*/nullptr,
4422                              RecTy,
4423                              TInfo,
4424                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4425                              /*InitStyle=*/ICIS_NoInit);
4426   Anon->setImplicit();
4427 
4428   // Add the anonymous struct object to the current context.
4429   CurContext->addDecl(Anon);
4430 
4431   // Inject the members of the anonymous struct into the current
4432   // context and into the identifier resolver chain for name lookup
4433   // purposes.
4434   SmallVector<NamedDecl*, 2> Chain;
4435   Chain.push_back(Anon);
4436 
4437   RecordDecl *RecordDef = Record->getDefinition();
4438   if (RequireCompleteType(Anon->getLocation(), RecTy,
4439                           diag::err_field_incomplete) ||
4440       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4441                                           AS_none, Chain)) {
4442     Anon->setInvalidDecl();
4443     ParentDecl->setInvalidDecl();
4444   }
4445 
4446   return Anon;
4447 }
4448 
4449 /// GetNameForDeclarator - Determine the full declaration name for the
4450 /// given Declarator.
4451 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4452   return GetNameFromUnqualifiedId(D.getName());
4453 }
4454 
4455 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4456 DeclarationNameInfo
4457 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4458   DeclarationNameInfo NameInfo;
4459   NameInfo.setLoc(Name.StartLocation);
4460 
4461   switch (Name.getKind()) {
4462 
4463   case UnqualifiedId::IK_ImplicitSelfParam:
4464   case UnqualifiedId::IK_Identifier:
4465     NameInfo.setName(Name.Identifier);
4466     NameInfo.setLoc(Name.StartLocation);
4467     return NameInfo;
4468 
4469   case UnqualifiedId::IK_OperatorFunctionId:
4470     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4471                                            Name.OperatorFunctionId.Operator));
4472     NameInfo.setLoc(Name.StartLocation);
4473     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4474       = Name.OperatorFunctionId.SymbolLocations[0];
4475     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4476       = Name.EndLocation.getRawEncoding();
4477     return NameInfo;
4478 
4479   case UnqualifiedId::IK_LiteralOperatorId:
4480     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4481                                                            Name.Identifier));
4482     NameInfo.setLoc(Name.StartLocation);
4483     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4484     return NameInfo;
4485 
4486   case UnqualifiedId::IK_ConversionFunctionId: {
4487     TypeSourceInfo *TInfo;
4488     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4489     if (Ty.isNull())
4490       return DeclarationNameInfo();
4491     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4492                                                Context.getCanonicalType(Ty)));
4493     NameInfo.setLoc(Name.StartLocation);
4494     NameInfo.setNamedTypeInfo(TInfo);
4495     return NameInfo;
4496   }
4497 
4498   case UnqualifiedId::IK_ConstructorName: {
4499     TypeSourceInfo *TInfo;
4500     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4501     if (Ty.isNull())
4502       return DeclarationNameInfo();
4503     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4504                                               Context.getCanonicalType(Ty)));
4505     NameInfo.setLoc(Name.StartLocation);
4506     NameInfo.setNamedTypeInfo(TInfo);
4507     return NameInfo;
4508   }
4509 
4510   case UnqualifiedId::IK_ConstructorTemplateId: {
4511     // In well-formed code, we can only have a constructor
4512     // template-id that refers to the current context, so go there
4513     // to find the actual type being constructed.
4514     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4515     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4516       return DeclarationNameInfo();
4517 
4518     // Determine the type of the class being constructed.
4519     QualType CurClassType = Context.getTypeDeclType(CurClass);
4520 
4521     // FIXME: Check two things: that the template-id names the same type as
4522     // CurClassType, and that the template-id does not occur when the name
4523     // was qualified.
4524 
4525     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4526                                     Context.getCanonicalType(CurClassType)));
4527     NameInfo.setLoc(Name.StartLocation);
4528     // FIXME: should we retrieve TypeSourceInfo?
4529     NameInfo.setNamedTypeInfo(nullptr);
4530     return NameInfo;
4531   }
4532 
4533   case UnqualifiedId::IK_DestructorName: {
4534     TypeSourceInfo *TInfo;
4535     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4536     if (Ty.isNull())
4537       return DeclarationNameInfo();
4538     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4539                                               Context.getCanonicalType(Ty)));
4540     NameInfo.setLoc(Name.StartLocation);
4541     NameInfo.setNamedTypeInfo(TInfo);
4542     return NameInfo;
4543   }
4544 
4545   case UnqualifiedId::IK_TemplateId: {
4546     TemplateName TName = Name.TemplateId->Template.get();
4547     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4548     return Context.getNameForTemplate(TName, TNameLoc);
4549   }
4550 
4551   } // switch (Name.getKind())
4552 
4553   llvm_unreachable("Unknown name kind");
4554 }
4555 
4556 static QualType getCoreType(QualType Ty) {
4557   do {
4558     if (Ty->isPointerType() || Ty->isReferenceType())
4559       Ty = Ty->getPointeeType();
4560     else if (Ty->isArrayType())
4561       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4562     else
4563       return Ty.withoutLocalFastQualifiers();
4564   } while (true);
4565 }
4566 
4567 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4568 /// and Definition have "nearly" matching parameters. This heuristic is
4569 /// used to improve diagnostics in the case where an out-of-line function
4570 /// definition doesn't match any declaration within the class or namespace.
4571 /// Also sets Params to the list of indices to the parameters that differ
4572 /// between the declaration and the definition. If hasSimilarParameters
4573 /// returns true and Params is empty, then all of the parameters match.
4574 static bool hasSimilarParameters(ASTContext &Context,
4575                                      FunctionDecl *Declaration,
4576                                      FunctionDecl *Definition,
4577                                      SmallVectorImpl<unsigned> &Params) {
4578   Params.clear();
4579   if (Declaration->param_size() != Definition->param_size())
4580     return false;
4581   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4582     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4583     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4584 
4585     // The parameter types are identical
4586     if (Context.hasSameType(DefParamTy, DeclParamTy))
4587       continue;
4588 
4589     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4590     QualType DefParamBaseTy = getCoreType(DefParamTy);
4591     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4592     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4593 
4594     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4595         (DeclTyName && DeclTyName == DefTyName))
4596       Params.push_back(Idx);
4597     else  // The two parameters aren't even close
4598       return false;
4599   }
4600 
4601   return true;
4602 }
4603 
4604 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4605 /// declarator needs to be rebuilt in the current instantiation.
4606 /// Any bits of declarator which appear before the name are valid for
4607 /// consideration here.  That's specifically the type in the decl spec
4608 /// and the base type in any member-pointer chunks.
4609 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4610                                                     DeclarationName Name) {
4611   // The types we specifically need to rebuild are:
4612   //   - typenames, typeofs, and decltypes
4613   //   - types which will become injected class names
4614   // Of course, we also need to rebuild any type referencing such a
4615   // type.  It's safest to just say "dependent", but we call out a
4616   // few cases here.
4617 
4618   DeclSpec &DS = D.getMutableDeclSpec();
4619   switch (DS.getTypeSpecType()) {
4620   case DeclSpec::TST_typename:
4621   case DeclSpec::TST_typeofType:
4622   case DeclSpec::TST_underlyingType:
4623   case DeclSpec::TST_atomic: {
4624     // Grab the type from the parser.
4625     TypeSourceInfo *TSI = nullptr;
4626     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4627     if (T.isNull() || !T->isDependentType()) break;
4628 
4629     // Make sure there's a type source info.  This isn't really much
4630     // of a waste; most dependent types should have type source info
4631     // attached already.
4632     if (!TSI)
4633       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4634 
4635     // Rebuild the type in the current instantiation.
4636     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4637     if (!TSI) return true;
4638 
4639     // Store the new type back in the decl spec.
4640     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4641     DS.UpdateTypeRep(LocType);
4642     break;
4643   }
4644 
4645   case DeclSpec::TST_decltype:
4646   case DeclSpec::TST_typeofExpr: {
4647     Expr *E = DS.getRepAsExpr();
4648     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4649     if (Result.isInvalid()) return true;
4650     DS.UpdateExprRep(Result.get());
4651     break;
4652   }
4653 
4654   default:
4655     // Nothing to do for these decl specs.
4656     break;
4657   }
4658 
4659   // It doesn't matter what order we do this in.
4660   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4661     DeclaratorChunk &Chunk = D.getTypeObject(I);
4662 
4663     // The only type information in the declarator which can come
4664     // before the declaration name is the base type of a member
4665     // pointer.
4666     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4667       continue;
4668 
4669     // Rebuild the scope specifier in-place.
4670     CXXScopeSpec &SS = Chunk.Mem.Scope();
4671     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4672       return true;
4673   }
4674 
4675   return false;
4676 }
4677 
4678 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4679   D.setFunctionDefinitionKind(FDK_Declaration);
4680   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4681 
4682   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4683       Dcl && Dcl->getDeclContext()->isFileContext())
4684     Dcl->setTopLevelDeclInObjCContainer();
4685 
4686   return Dcl;
4687 }
4688 
4689 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4690 ///   If T is the name of a class, then each of the following shall have a
4691 ///   name different from T:
4692 ///     - every static data member of class T;
4693 ///     - every member function of class T
4694 ///     - every member of class T that is itself a type;
4695 /// \returns true if the declaration name violates these rules.
4696 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4697                                    DeclarationNameInfo NameInfo) {
4698   DeclarationName Name = NameInfo.getName();
4699 
4700   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4701   while (Record && Record->isAnonymousStructOrUnion())
4702     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4703   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4704     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4705     return true;
4706   }
4707 
4708   return false;
4709 }
4710 
4711 /// \brief Diagnose a declaration whose declarator-id has the given
4712 /// nested-name-specifier.
4713 ///
4714 /// \param SS The nested-name-specifier of the declarator-id.
4715 ///
4716 /// \param DC The declaration context to which the nested-name-specifier
4717 /// resolves.
4718 ///
4719 /// \param Name The name of the entity being declared.
4720 ///
4721 /// \param Loc The location of the name of the entity being declared.
4722 ///
4723 /// \returns true if we cannot safely recover from this error, false otherwise.
4724 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4725                                         DeclarationName Name,
4726                                         SourceLocation Loc) {
4727   DeclContext *Cur = CurContext;
4728   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4729     Cur = Cur->getParent();
4730 
4731   // If the user provided a superfluous scope specifier that refers back to the
4732   // class in which the entity is already declared, diagnose and ignore it.
4733   //
4734   // class X {
4735   //   void X::f();
4736   // };
4737   //
4738   // Note, it was once ill-formed to give redundant qualification in all
4739   // contexts, but that rule was removed by DR482.
4740   if (Cur->Equals(DC)) {
4741     if (Cur->isRecord()) {
4742       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4743                                       : diag::err_member_extra_qualification)
4744         << Name << FixItHint::CreateRemoval(SS.getRange());
4745       SS.clear();
4746     } else {
4747       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4748     }
4749     return false;
4750   }
4751 
4752   // Check whether the qualifying scope encloses the scope of the original
4753   // declaration.
4754   if (!Cur->Encloses(DC)) {
4755     if (Cur->isRecord())
4756       Diag(Loc, diag::err_member_qualification)
4757         << Name << SS.getRange();
4758     else if (isa<TranslationUnitDecl>(DC))
4759       Diag(Loc, diag::err_invalid_declarator_global_scope)
4760         << Name << SS.getRange();
4761     else if (isa<FunctionDecl>(Cur))
4762       Diag(Loc, diag::err_invalid_declarator_in_function)
4763         << Name << SS.getRange();
4764     else if (isa<BlockDecl>(Cur))
4765       Diag(Loc, diag::err_invalid_declarator_in_block)
4766         << Name << SS.getRange();
4767     else
4768       Diag(Loc, diag::err_invalid_declarator_scope)
4769       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4770 
4771     return true;
4772   }
4773 
4774   if (Cur->isRecord()) {
4775     // Cannot qualify members within a class.
4776     Diag(Loc, diag::err_member_qualification)
4777       << Name << SS.getRange();
4778     SS.clear();
4779 
4780     // C++ constructors and destructors with incorrect scopes can break
4781     // our AST invariants by having the wrong underlying types. If
4782     // that's the case, then drop this declaration entirely.
4783     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4784          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4785         !Context.hasSameType(Name.getCXXNameType(),
4786                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4787       return true;
4788 
4789     return false;
4790   }
4791 
4792   // C++11 [dcl.meaning]p1:
4793   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4794   //   not begin with a decltype-specifer"
4795   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4796   while (SpecLoc.getPrefix())
4797     SpecLoc = SpecLoc.getPrefix();
4798   if (dyn_cast_or_null<DecltypeType>(
4799         SpecLoc.getNestedNameSpecifier()->getAsType()))
4800     Diag(Loc, diag::err_decltype_in_declarator)
4801       << SpecLoc.getTypeLoc().getSourceRange();
4802 
4803   return false;
4804 }
4805 
4806 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4807                                   MultiTemplateParamsArg TemplateParamLists) {
4808   // TODO: consider using NameInfo for diagnostic.
4809   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4810   DeclarationName Name = NameInfo.getName();
4811 
4812   // All of these full declarators require an identifier.  If it doesn't have
4813   // one, the ParsedFreeStandingDeclSpec action should be used.
4814   if (!Name) {
4815     if (!D.isInvalidType())  // Reject this if we think it is valid.
4816       Diag(D.getDeclSpec().getLocStart(),
4817            diag::err_declarator_need_ident)
4818         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4819     return nullptr;
4820   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4821     return nullptr;
4822 
4823   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4824   // we find one that is.
4825   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4826          (S->getFlags() & Scope::TemplateParamScope) != 0)
4827     S = S->getParent();
4828 
4829   DeclContext *DC = CurContext;
4830   if (D.getCXXScopeSpec().isInvalid())
4831     D.setInvalidType();
4832   else if (D.getCXXScopeSpec().isSet()) {
4833     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4834                                         UPPC_DeclarationQualifier))
4835       return nullptr;
4836 
4837     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4838     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4839     if (!DC || isa<EnumDecl>(DC)) {
4840       // If we could not compute the declaration context, it's because the
4841       // declaration context is dependent but does not refer to a class,
4842       // class template, or class template partial specialization. Complain
4843       // and return early, to avoid the coming semantic disaster.
4844       Diag(D.getIdentifierLoc(),
4845            diag::err_template_qualified_declarator_no_match)
4846         << D.getCXXScopeSpec().getScopeRep()
4847         << D.getCXXScopeSpec().getRange();
4848       return nullptr;
4849     }
4850     bool IsDependentContext = DC->isDependentContext();
4851 
4852     if (!IsDependentContext &&
4853         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4854       return nullptr;
4855 
4856     // If a class is incomplete, do not parse entities inside it.
4857     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4858       Diag(D.getIdentifierLoc(),
4859            diag::err_member_def_undefined_record)
4860         << Name << DC << D.getCXXScopeSpec().getRange();
4861       return nullptr;
4862     }
4863     if (!D.getDeclSpec().isFriendSpecified()) {
4864       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4865                                       Name, D.getIdentifierLoc())) {
4866         if (DC->isRecord())
4867           return nullptr;
4868 
4869         D.setInvalidType();
4870       }
4871     }
4872 
4873     // Check whether we need to rebuild the type of the given
4874     // declaration in the current instantiation.
4875     if (EnteringContext && IsDependentContext &&
4876         TemplateParamLists.size() != 0) {
4877       ContextRAII SavedContext(*this, DC);
4878       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4879         D.setInvalidType();
4880     }
4881   }
4882 
4883   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4884   QualType R = TInfo->getType();
4885 
4886   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4887     // If this is a typedef, we'll end up spewing multiple diagnostics.
4888     // Just return early; it's safer. If this is a function, let the
4889     // "constructor cannot have a return type" diagnostic handle it.
4890     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4891       return nullptr;
4892 
4893   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4894                                       UPPC_DeclarationType))
4895     D.setInvalidType();
4896 
4897   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4898                         ForRedeclaration);
4899 
4900   // See if this is a redefinition of a variable in the same scope.
4901   if (!D.getCXXScopeSpec().isSet()) {
4902     bool IsLinkageLookup = false;
4903     bool CreateBuiltins = false;
4904 
4905     // If the declaration we're planning to build will be a function
4906     // or object with linkage, then look for another declaration with
4907     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4908     //
4909     // If the declaration we're planning to build will be declared with
4910     // external linkage in the translation unit, create any builtin with
4911     // the same name.
4912     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4913       /* Do nothing*/;
4914     else if (CurContext->isFunctionOrMethod() &&
4915              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4916               R->isFunctionType())) {
4917       IsLinkageLookup = true;
4918       CreateBuiltins =
4919           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4920     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4921                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4922       CreateBuiltins = true;
4923 
4924     if (IsLinkageLookup)
4925       Previous.clear(LookupRedeclarationWithLinkage);
4926 
4927     LookupName(Previous, S, CreateBuiltins);
4928   } else { // Something like "int foo::x;"
4929     LookupQualifiedName(Previous, DC);
4930 
4931     // C++ [dcl.meaning]p1:
4932     //   When the declarator-id is qualified, the declaration shall refer to a
4933     //  previously declared member of the class or namespace to which the
4934     //  qualifier refers (or, in the case of a namespace, of an element of the
4935     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4936     //  thereof; [...]
4937     //
4938     // Note that we already checked the context above, and that we do not have
4939     // enough information to make sure that Previous contains the declaration
4940     // we want to match. For example, given:
4941     //
4942     //   class X {
4943     //     void f();
4944     //     void f(float);
4945     //   };
4946     //
4947     //   void X::f(int) { } // ill-formed
4948     //
4949     // In this case, Previous will point to the overload set
4950     // containing the two f's declared in X, but neither of them
4951     // matches.
4952 
4953     // C++ [dcl.meaning]p1:
4954     //   [...] the member shall not merely have been introduced by a
4955     //   using-declaration in the scope of the class or namespace nominated by
4956     //   the nested-name-specifier of the declarator-id.
4957     RemoveUsingDecls(Previous);
4958   }
4959 
4960   if (Previous.isSingleResult() &&
4961       Previous.getFoundDecl()->isTemplateParameter()) {
4962     // Maybe we will complain about the shadowed template parameter.
4963     if (!D.isInvalidType())
4964       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4965                                       Previous.getFoundDecl());
4966 
4967     // Just pretend that we didn't see the previous declaration.
4968     Previous.clear();
4969   }
4970 
4971   // In C++, the previous declaration we find might be a tag type
4972   // (class or enum). In this case, the new declaration will hide the
4973   // tag type. Note that this does does not apply if we're declaring a
4974   // typedef (C++ [dcl.typedef]p4).
4975   if (Previous.isSingleTagDecl() &&
4976       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4977     Previous.clear();
4978 
4979   // Check that there are no default arguments other than in the parameters
4980   // of a function declaration (C++ only).
4981   if (getLangOpts().CPlusPlus)
4982     CheckExtraCXXDefaultArguments(D);
4983 
4984   if (D.getDeclSpec().isConceptSpecified()) {
4985     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
4986     // applied only to the definition of a function template or variable
4987     // template, declared in namespace scope
4988     if (!TemplateParamLists.size()) {
4989       Diag(D.getDeclSpec().getConceptSpecLoc(),
4990            diag:: err_concept_wrong_decl_kind);
4991       return nullptr;
4992     }
4993 
4994     if (!DC->getRedeclContext()->isFileContext()) {
4995       Diag(D.getIdentifierLoc(),
4996            diag::err_concept_decls_may_only_appear_in_namespace_scope);
4997       return nullptr;
4998     }
4999   }
5000 
5001   NamedDecl *New;
5002 
5003   bool AddToScope = true;
5004   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5005     if (TemplateParamLists.size()) {
5006       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5007       return nullptr;
5008     }
5009 
5010     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5011   } else if (R->isFunctionType()) {
5012     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5013                                   TemplateParamLists,
5014                                   AddToScope);
5015   } else {
5016     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5017                                   AddToScope);
5018   }
5019 
5020   if (!New)
5021     return nullptr;
5022 
5023   // If this has an identifier and is not an invalid redeclaration or
5024   // function template specialization, add it to the scope stack.
5025   if (New->getDeclName() && AddToScope &&
5026        !(D.isRedeclaration() && New->isInvalidDecl())) {
5027     // Only make a locally-scoped extern declaration visible if it is the first
5028     // declaration of this entity. Qualified lookup for such an entity should
5029     // only find this declaration if there is no visible declaration of it.
5030     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5031     PushOnScopeChains(New, S, AddToContext);
5032     if (!AddToContext)
5033       CurContext->addHiddenDecl(New);
5034   }
5035 
5036   return New;
5037 }
5038 
5039 /// Helper method to turn variable array types into constant array
5040 /// types in certain situations which would otherwise be errors (for
5041 /// GCC compatibility).
5042 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5043                                                     ASTContext &Context,
5044                                                     bool &SizeIsNegative,
5045                                                     llvm::APSInt &Oversized) {
5046   // This method tries to turn a variable array into a constant
5047   // array even when the size isn't an ICE.  This is necessary
5048   // for compatibility with code that depends on gcc's buggy
5049   // constant expression folding, like struct {char x[(int)(char*)2];}
5050   SizeIsNegative = false;
5051   Oversized = 0;
5052 
5053   if (T->isDependentType())
5054     return QualType();
5055 
5056   QualifierCollector Qs;
5057   const Type *Ty = Qs.strip(T);
5058 
5059   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5060     QualType Pointee = PTy->getPointeeType();
5061     QualType FixedType =
5062         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5063                                             Oversized);
5064     if (FixedType.isNull()) return FixedType;
5065     FixedType = Context.getPointerType(FixedType);
5066     return Qs.apply(Context, FixedType);
5067   }
5068   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5069     QualType Inner = PTy->getInnerType();
5070     QualType FixedType =
5071         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5072                                             Oversized);
5073     if (FixedType.isNull()) return FixedType;
5074     FixedType = Context.getParenType(FixedType);
5075     return Qs.apply(Context, FixedType);
5076   }
5077 
5078   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5079   if (!VLATy)
5080     return QualType();
5081   // FIXME: We should probably handle this case
5082   if (VLATy->getElementType()->isVariablyModifiedType())
5083     return QualType();
5084 
5085   llvm::APSInt Res;
5086   if (!VLATy->getSizeExpr() ||
5087       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5088     return QualType();
5089 
5090   // Check whether the array size is negative.
5091   if (Res.isSigned() && Res.isNegative()) {
5092     SizeIsNegative = true;
5093     return QualType();
5094   }
5095 
5096   // Check whether the array is too large to be addressed.
5097   unsigned ActiveSizeBits
5098     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5099                                               Res);
5100   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5101     Oversized = Res;
5102     return QualType();
5103   }
5104 
5105   return Context.getConstantArrayType(VLATy->getElementType(),
5106                                       Res, ArrayType::Normal, 0);
5107 }
5108 
5109 static void
5110 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5111   SrcTL = SrcTL.getUnqualifiedLoc();
5112   DstTL = DstTL.getUnqualifiedLoc();
5113   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5114     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5115     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5116                                       DstPTL.getPointeeLoc());
5117     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5118     return;
5119   }
5120   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5121     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5122     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5123                                       DstPTL.getInnerLoc());
5124     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5125     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5126     return;
5127   }
5128   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5129   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5130   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5131   TypeLoc DstElemTL = DstATL.getElementLoc();
5132   DstElemTL.initializeFullCopy(SrcElemTL);
5133   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5134   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5135   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5136 }
5137 
5138 /// Helper method to turn variable array types into constant array
5139 /// types in certain situations which would otherwise be errors (for
5140 /// GCC compatibility).
5141 static TypeSourceInfo*
5142 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5143                                               ASTContext &Context,
5144                                               bool &SizeIsNegative,
5145                                               llvm::APSInt &Oversized) {
5146   QualType FixedTy
5147     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5148                                           SizeIsNegative, Oversized);
5149   if (FixedTy.isNull())
5150     return nullptr;
5151   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5152   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5153                                     FixedTInfo->getTypeLoc());
5154   return FixedTInfo;
5155 }
5156 
5157 /// \brief Register the given locally-scoped extern "C" declaration so
5158 /// that it can be found later for redeclarations. We include any extern "C"
5159 /// declaration that is not visible in the translation unit here, not just
5160 /// function-scope declarations.
5161 void
5162 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5163   if (!getLangOpts().CPlusPlus &&
5164       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5165     // Don't need to track declarations in the TU in C.
5166     return;
5167 
5168   // Note that we have a locally-scoped external with this name.
5169   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5170 }
5171 
5172 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5173   // FIXME: We can have multiple results via __attribute__((overloadable)).
5174   auto Result = Context.getExternCContextDecl()->lookup(Name);
5175   return Result.empty() ? nullptr : *Result.begin();
5176 }
5177 
5178 /// \brief Diagnose function specifiers on a declaration of an identifier that
5179 /// does not identify a function.
5180 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5181   // FIXME: We should probably indicate the identifier in question to avoid
5182   // confusion for constructs like "inline int a(), b;"
5183   if (DS.isInlineSpecified())
5184     Diag(DS.getInlineSpecLoc(),
5185          diag::err_inline_non_function);
5186 
5187   if (DS.isVirtualSpecified())
5188     Diag(DS.getVirtualSpecLoc(),
5189          diag::err_virtual_non_function);
5190 
5191   if (DS.isExplicitSpecified())
5192     Diag(DS.getExplicitSpecLoc(),
5193          diag::err_explicit_non_function);
5194 
5195   if (DS.isNoreturnSpecified())
5196     Diag(DS.getNoreturnSpecLoc(),
5197          diag::err_noreturn_non_function);
5198 }
5199 
5200 NamedDecl*
5201 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5202                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5203   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5204   if (D.getCXXScopeSpec().isSet()) {
5205     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5206       << D.getCXXScopeSpec().getRange();
5207     D.setInvalidType();
5208     // Pretend we didn't see the scope specifier.
5209     DC = CurContext;
5210     Previous.clear();
5211   }
5212 
5213   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5214 
5215   if (D.getDeclSpec().isConstexprSpecified())
5216     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5217       << 1;
5218   if (D.getDeclSpec().isConceptSpecified())
5219     Diag(D.getDeclSpec().getConceptSpecLoc(),
5220          diag::err_concept_wrong_decl_kind);
5221 
5222   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5223     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5224       << D.getName().getSourceRange();
5225     return nullptr;
5226   }
5227 
5228   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5229   if (!NewTD) return nullptr;
5230 
5231   // Handle attributes prior to checking for duplicates in MergeVarDecl
5232   ProcessDeclAttributes(S, NewTD, D);
5233 
5234   CheckTypedefForVariablyModifiedType(S, NewTD);
5235 
5236   bool Redeclaration = D.isRedeclaration();
5237   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5238   D.setRedeclaration(Redeclaration);
5239   return ND;
5240 }
5241 
5242 void
5243 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5244   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5245   // then it shall have block scope.
5246   // Note that variably modified types must be fixed before merging the decl so
5247   // that redeclarations will match.
5248   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5249   QualType T = TInfo->getType();
5250   if (T->isVariablyModifiedType()) {
5251     getCurFunction()->setHasBranchProtectedScope();
5252 
5253     if (S->getFnParent() == nullptr) {
5254       bool SizeIsNegative;
5255       llvm::APSInt Oversized;
5256       TypeSourceInfo *FixedTInfo =
5257         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5258                                                       SizeIsNegative,
5259                                                       Oversized);
5260       if (FixedTInfo) {
5261         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5262         NewTD->setTypeSourceInfo(FixedTInfo);
5263       } else {
5264         if (SizeIsNegative)
5265           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5266         else if (T->isVariableArrayType())
5267           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5268         else if (Oversized.getBoolValue())
5269           Diag(NewTD->getLocation(), diag::err_array_too_large)
5270             << Oversized.toString(10);
5271         else
5272           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5273         NewTD->setInvalidDecl();
5274       }
5275     }
5276   }
5277 }
5278 
5279 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5280 /// declares a typedef-name, either using the 'typedef' type specifier or via
5281 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5282 NamedDecl*
5283 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5284                            LookupResult &Previous, bool &Redeclaration) {
5285   // Merge the decl with the existing one if appropriate. If the decl is
5286   // in an outer scope, it isn't the same thing.
5287   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5288                        /*AllowInlineNamespace*/false);
5289   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5290   if (!Previous.empty()) {
5291     Redeclaration = true;
5292     MergeTypedefNameDecl(S, NewTD, Previous);
5293   }
5294 
5295   // If this is the C FILE type, notify the AST context.
5296   if (IdentifierInfo *II = NewTD->getIdentifier())
5297     if (!NewTD->isInvalidDecl() &&
5298         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5299       if (II->isStr("FILE"))
5300         Context.setFILEDecl(NewTD);
5301       else if (II->isStr("jmp_buf"))
5302         Context.setjmp_bufDecl(NewTD);
5303       else if (II->isStr("sigjmp_buf"))
5304         Context.setsigjmp_bufDecl(NewTD);
5305       else if (II->isStr("ucontext_t"))
5306         Context.setucontext_tDecl(NewTD);
5307     }
5308 
5309   return NewTD;
5310 }
5311 
5312 /// \brief Determines whether the given declaration is an out-of-scope
5313 /// previous declaration.
5314 ///
5315 /// This routine should be invoked when name lookup has found a
5316 /// previous declaration (PrevDecl) that is not in the scope where a
5317 /// new declaration by the same name is being introduced. If the new
5318 /// declaration occurs in a local scope, previous declarations with
5319 /// linkage may still be considered previous declarations (C99
5320 /// 6.2.2p4-5, C++ [basic.link]p6).
5321 ///
5322 /// \param PrevDecl the previous declaration found by name
5323 /// lookup
5324 ///
5325 /// \param DC the context in which the new declaration is being
5326 /// declared.
5327 ///
5328 /// \returns true if PrevDecl is an out-of-scope previous declaration
5329 /// for a new delcaration with the same name.
5330 static bool
5331 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5332                                 ASTContext &Context) {
5333   if (!PrevDecl)
5334     return false;
5335 
5336   if (!PrevDecl->hasLinkage())
5337     return false;
5338 
5339   if (Context.getLangOpts().CPlusPlus) {
5340     // C++ [basic.link]p6:
5341     //   If there is a visible declaration of an entity with linkage
5342     //   having the same name and type, ignoring entities declared
5343     //   outside the innermost enclosing namespace scope, the block
5344     //   scope declaration declares that same entity and receives the
5345     //   linkage of the previous declaration.
5346     DeclContext *OuterContext = DC->getRedeclContext();
5347     if (!OuterContext->isFunctionOrMethod())
5348       // This rule only applies to block-scope declarations.
5349       return false;
5350 
5351     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5352     if (PrevOuterContext->isRecord())
5353       // We found a member function: ignore it.
5354       return false;
5355 
5356     // Find the innermost enclosing namespace for the new and
5357     // previous declarations.
5358     OuterContext = OuterContext->getEnclosingNamespaceContext();
5359     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5360 
5361     // The previous declaration is in a different namespace, so it
5362     // isn't the same function.
5363     if (!OuterContext->Equals(PrevOuterContext))
5364       return false;
5365   }
5366 
5367   return true;
5368 }
5369 
5370 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5371   CXXScopeSpec &SS = D.getCXXScopeSpec();
5372   if (!SS.isSet()) return;
5373   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5374 }
5375 
5376 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5377   QualType type = decl->getType();
5378   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5379   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5380     // Various kinds of declaration aren't allowed to be __autoreleasing.
5381     unsigned kind = -1U;
5382     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5383       if (var->hasAttr<BlocksAttr>())
5384         kind = 0; // __block
5385       else if (!var->hasLocalStorage())
5386         kind = 1; // global
5387     } else if (isa<ObjCIvarDecl>(decl)) {
5388       kind = 3; // ivar
5389     } else if (isa<FieldDecl>(decl)) {
5390       kind = 2; // field
5391     }
5392 
5393     if (kind != -1U) {
5394       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5395         << kind;
5396     }
5397   } else if (lifetime == Qualifiers::OCL_None) {
5398     // Try to infer lifetime.
5399     if (!type->isObjCLifetimeType())
5400       return false;
5401 
5402     lifetime = type->getObjCARCImplicitLifetime();
5403     type = Context.getLifetimeQualifiedType(type, lifetime);
5404     decl->setType(type);
5405   }
5406 
5407   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5408     // Thread-local variables cannot have lifetime.
5409     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5410         var->getTLSKind()) {
5411       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5412         << var->getType();
5413       return true;
5414     }
5415   }
5416 
5417   return false;
5418 }
5419 
5420 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5421   // Ensure that an auto decl is deduced otherwise the checks below might cache
5422   // the wrong linkage.
5423   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5424 
5425   // 'weak' only applies to declarations with external linkage.
5426   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5427     if (!ND.isExternallyVisible()) {
5428       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5429       ND.dropAttr<WeakAttr>();
5430     }
5431   }
5432   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5433     if (ND.isExternallyVisible()) {
5434       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5435       ND.dropAttr<WeakRefAttr>();
5436       ND.dropAttr<AliasAttr>();
5437     }
5438   }
5439 
5440   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5441     if (VD->hasInit()) {
5442       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5443         assert(VD->isThisDeclarationADefinition() &&
5444                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5445         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
5446         VD->dropAttr<AliasAttr>();
5447       }
5448     }
5449   }
5450 
5451   // 'selectany' only applies to externally visible variable declarations.
5452   // It does not apply to functions.
5453   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5454     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5455       S.Diag(Attr->getLocation(),
5456              diag::err_attribute_selectany_non_extern_data);
5457       ND.dropAttr<SelectAnyAttr>();
5458     }
5459   }
5460 
5461   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5462     // dll attributes require external linkage. Static locals may have external
5463     // linkage but still cannot be explicitly imported or exported.
5464     auto *VD = dyn_cast<VarDecl>(&ND);
5465     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5466       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5467         << &ND << Attr;
5468       ND.setInvalidDecl();
5469     }
5470   }
5471 
5472   // Virtual functions cannot be marked as 'notail'.
5473   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5474     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5475       if (MD->isVirtual()) {
5476         S.Diag(ND.getLocation(),
5477                diag::err_invalid_attribute_on_virtual_function)
5478             << Attr;
5479         ND.dropAttr<NotTailCalledAttr>();
5480       }
5481 }
5482 
5483 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5484                                            NamedDecl *NewDecl,
5485                                            bool IsSpecialization) {
5486   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5487     OldDecl = OldTD->getTemplatedDecl();
5488   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5489     NewDecl = NewTD->getTemplatedDecl();
5490 
5491   if (!OldDecl || !NewDecl)
5492     return;
5493 
5494   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5495   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5496   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5497   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5498 
5499   // dllimport and dllexport are inheritable attributes so we have to exclude
5500   // inherited attribute instances.
5501   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5502                     (NewExportAttr && !NewExportAttr->isInherited());
5503 
5504   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5505   // the only exception being explicit specializations.
5506   // Implicitly generated declarations are also excluded for now because there
5507   // is no other way to switch these to use dllimport or dllexport.
5508   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5509 
5510   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5511     // Allow with a warning for free functions and global variables.
5512     bool JustWarn = false;
5513     if (!OldDecl->isCXXClassMember()) {
5514       auto *VD = dyn_cast<VarDecl>(OldDecl);
5515       if (VD && !VD->getDescribedVarTemplate())
5516         JustWarn = true;
5517       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5518       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5519         JustWarn = true;
5520     }
5521 
5522     // We cannot change a declaration that's been used because IR has already
5523     // been emitted. Dllimported functions will still work though (modulo
5524     // address equality) as they can use the thunk.
5525     if (OldDecl->isUsed())
5526       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5527         JustWarn = false;
5528 
5529     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5530                                : diag::err_attribute_dll_redeclaration;
5531     S.Diag(NewDecl->getLocation(), DiagID)
5532         << NewDecl
5533         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5534     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5535     if (!JustWarn) {
5536       NewDecl->setInvalidDecl();
5537       return;
5538     }
5539   }
5540 
5541   // A redeclaration is not allowed to drop a dllimport attribute, the only
5542   // exceptions being inline function definitions, local extern declarations,
5543   // and qualified friend declarations.
5544   // NB: MSVC converts such a declaration to dllexport.
5545   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5546   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5547     // Ignore static data because out-of-line definitions are diagnosed
5548     // separately.
5549     IsStaticDataMember = VD->isStaticDataMember();
5550   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5551     IsInline = FD->isInlined();
5552     IsQualifiedFriend = FD->getQualifier() &&
5553                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5554   }
5555 
5556   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5557       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5558     S.Diag(NewDecl->getLocation(),
5559            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5560       << NewDecl << OldImportAttr;
5561     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5562     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5563     OldDecl->dropAttr<DLLImportAttr>();
5564     NewDecl->dropAttr<DLLImportAttr>();
5565   } else if (IsInline && OldImportAttr &&
5566              !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5567     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5568     OldDecl->dropAttr<DLLImportAttr>();
5569     NewDecl->dropAttr<DLLImportAttr>();
5570     S.Diag(NewDecl->getLocation(),
5571            diag::warn_dllimport_dropped_from_inline_function)
5572         << NewDecl << OldImportAttr;
5573   }
5574 }
5575 
5576 /// Given that we are within the definition of the given function,
5577 /// will that definition behave like C99's 'inline', where the
5578 /// definition is discarded except for optimization purposes?
5579 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5580   // Try to avoid calling GetGVALinkageForFunction.
5581 
5582   // All cases of this require the 'inline' keyword.
5583   if (!FD->isInlined()) return false;
5584 
5585   // This is only possible in C++ with the gnu_inline attribute.
5586   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5587     return false;
5588 
5589   // Okay, go ahead and call the relatively-more-expensive function.
5590 
5591 #ifndef NDEBUG
5592   // AST quite reasonably asserts that it's working on a function
5593   // definition.  We don't really have a way to tell it that we're
5594   // currently defining the function, so just lie to it in +Asserts
5595   // builds.  This is an awful hack.
5596   FD->setLazyBody(1);
5597 #endif
5598 
5599   bool isC99Inline =
5600       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5601 
5602 #ifndef NDEBUG
5603   FD->setLazyBody(0);
5604 #endif
5605 
5606   return isC99Inline;
5607 }
5608 
5609 /// Determine whether a variable is extern "C" prior to attaching
5610 /// an initializer. We can't just call isExternC() here, because that
5611 /// will also compute and cache whether the declaration is externally
5612 /// visible, which might change when we attach the initializer.
5613 ///
5614 /// This can only be used if the declaration is known to not be a
5615 /// redeclaration of an internal linkage declaration.
5616 ///
5617 /// For instance:
5618 ///
5619 ///   auto x = []{};
5620 ///
5621 /// Attaching the initializer here makes this declaration not externally
5622 /// visible, because its type has internal linkage.
5623 ///
5624 /// FIXME: This is a hack.
5625 template<typename T>
5626 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5627   if (S.getLangOpts().CPlusPlus) {
5628     // In C++, the overloadable attribute negates the effects of extern "C".
5629     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5630       return false;
5631 
5632     // So do CUDA's host/device attributes if overloading is enabled.
5633     if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
5634         (D->template hasAttr<CUDADeviceAttr>() ||
5635          D->template hasAttr<CUDAHostAttr>()))
5636       return false;
5637   }
5638   return D->isExternC();
5639 }
5640 
5641 static bool shouldConsiderLinkage(const VarDecl *VD) {
5642   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5643   if (DC->isFunctionOrMethod())
5644     return VD->hasExternalStorage();
5645   if (DC->isFileContext())
5646     return true;
5647   if (DC->isRecord())
5648     return false;
5649   llvm_unreachable("Unexpected context");
5650 }
5651 
5652 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5653   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5654   if (DC->isFileContext() || DC->isFunctionOrMethod())
5655     return true;
5656   if (DC->isRecord())
5657     return false;
5658   llvm_unreachable("Unexpected context");
5659 }
5660 
5661 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5662                           AttributeList::Kind Kind) {
5663   for (const AttributeList *L = AttrList; L; L = L->getNext())
5664     if (L->getKind() == Kind)
5665       return true;
5666   return false;
5667 }
5668 
5669 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5670                           AttributeList::Kind Kind) {
5671   // Check decl attributes on the DeclSpec.
5672   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5673     return true;
5674 
5675   // Walk the declarator structure, checking decl attributes that were in a type
5676   // position to the decl itself.
5677   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5678     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5679       return true;
5680   }
5681 
5682   // Finally, check attributes on the decl itself.
5683   return hasParsedAttr(S, PD.getAttributes(), Kind);
5684 }
5685 
5686 /// Adjust the \c DeclContext for a function or variable that might be a
5687 /// function-local external declaration.
5688 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5689   if (!DC->isFunctionOrMethod())
5690     return false;
5691 
5692   // If this is a local extern function or variable declared within a function
5693   // template, don't add it into the enclosing namespace scope until it is
5694   // instantiated; it might have a dependent type right now.
5695   if (DC->isDependentContext())
5696     return true;
5697 
5698   // C++11 [basic.link]p7:
5699   //   When a block scope declaration of an entity with linkage is not found to
5700   //   refer to some other declaration, then that entity is a member of the
5701   //   innermost enclosing namespace.
5702   //
5703   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5704   // semantically-enclosing namespace, not a lexically-enclosing one.
5705   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5706     DC = DC->getParent();
5707   return true;
5708 }
5709 
5710 /// \brief Returns true if given declaration has external C language linkage.
5711 static bool isDeclExternC(const Decl *D) {
5712   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5713     return FD->isExternC();
5714   if (const auto *VD = dyn_cast<VarDecl>(D))
5715     return VD->isExternC();
5716 
5717   llvm_unreachable("Unknown type of decl!");
5718 }
5719 
5720 NamedDecl *
5721 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5722                               TypeSourceInfo *TInfo, LookupResult &Previous,
5723                               MultiTemplateParamsArg TemplateParamLists,
5724                               bool &AddToScope) {
5725   QualType R = TInfo->getType();
5726   DeclarationName Name = GetNameForDeclarator(D).getName();
5727 
5728   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5729   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5730   // argument.
5731   if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) {
5732     Diag(D.getIdentifierLoc(),
5733          diag::err_opencl_type_can_only_be_used_as_function_parameter)
5734         << R;
5735     D.setInvalidType();
5736     return nullptr;
5737   }
5738 
5739   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5740   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5741 
5742   // dllimport globals without explicit storage class are treated as extern. We
5743   // have to change the storage class this early to get the right DeclContext.
5744   if (SC == SC_None && !DC->isRecord() &&
5745       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5746       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5747     SC = SC_Extern;
5748 
5749   DeclContext *OriginalDC = DC;
5750   bool IsLocalExternDecl = SC == SC_Extern &&
5751                            adjustContextForLocalExternDecl(DC);
5752 
5753   if (getLangOpts().OpenCL) {
5754     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5755     QualType NR = R;
5756     while (NR->isPointerType()) {
5757       if (NR->isFunctionPointerType()) {
5758         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5759         D.setInvalidType();
5760         break;
5761       }
5762       NR = NR->getPointeeType();
5763     }
5764 
5765     if (!getOpenCLOptions().cl_khr_fp16) {
5766       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5767       // half array type (unless the cl_khr_fp16 extension is enabled).
5768       if (Context.getBaseElementType(R)->isHalfType()) {
5769         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5770         D.setInvalidType();
5771       }
5772     }
5773   }
5774 
5775   if (SCSpec == DeclSpec::SCS_mutable) {
5776     // mutable can only appear on non-static class members, so it's always
5777     // an error here
5778     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5779     D.setInvalidType();
5780     SC = SC_None;
5781   }
5782 
5783   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5784       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5785                               D.getDeclSpec().getStorageClassSpecLoc())) {
5786     // In C++11, the 'register' storage class specifier is deprecated.
5787     // Suppress the warning in system macros, it's used in macros in some
5788     // popular C system headers, such as in glibc's htonl() macro.
5789     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5790          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5791                                    : diag::warn_deprecated_register)
5792       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5793   }
5794 
5795   IdentifierInfo *II = Name.getAsIdentifierInfo();
5796   if (!II) {
5797     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5798       << Name;
5799     return nullptr;
5800   }
5801 
5802   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5803 
5804   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5805     // C99 6.9p2: The storage-class specifiers auto and register shall not
5806     // appear in the declaration specifiers in an external declaration.
5807     // Global Register+Asm is a GNU extension we support.
5808     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5809       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5810       D.setInvalidType();
5811     }
5812   }
5813 
5814   if (getLangOpts().OpenCL) {
5815     // OpenCL v1.2 s6.9.b p4:
5816     // The sampler type cannot be used with the __local and __global address
5817     // space qualifiers.
5818     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5819       R.getAddressSpace() == LangAS::opencl_global)) {
5820       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5821     }
5822 
5823     // OpenCL 1.2 spec, p6.9 r:
5824     // The event type cannot be used to declare a program scope variable.
5825     // The event type cannot be used with the __local, __constant and __global
5826     // address space qualifiers.
5827     if (R->isEventT()) {
5828       if (S->getParent() == nullptr) {
5829         Diag(D.getLocStart(), diag::err_event_t_global_var);
5830         D.setInvalidType();
5831       }
5832 
5833       if (R.getAddressSpace()) {
5834         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5835         D.setInvalidType();
5836       }
5837     }
5838   }
5839 
5840   bool IsExplicitSpecialization = false;
5841   bool IsVariableTemplateSpecialization = false;
5842   bool IsPartialSpecialization = false;
5843   bool IsVariableTemplate = false;
5844   VarDecl *NewVD = nullptr;
5845   VarTemplateDecl *NewTemplate = nullptr;
5846   TemplateParameterList *TemplateParams = nullptr;
5847   if (!getLangOpts().CPlusPlus) {
5848     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5849                             D.getIdentifierLoc(), II,
5850                             R, TInfo, SC);
5851 
5852     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5853       ParsingInitForAutoVars.insert(NewVD);
5854 
5855     if (D.isInvalidType())
5856       NewVD->setInvalidDecl();
5857   } else {
5858     bool Invalid = false;
5859 
5860     if (DC->isRecord() && !CurContext->isRecord()) {
5861       // This is an out-of-line definition of a static data member.
5862       switch (SC) {
5863       case SC_None:
5864         break;
5865       case SC_Static:
5866         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5867              diag::err_static_out_of_line)
5868           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5869         break;
5870       case SC_Auto:
5871       case SC_Register:
5872       case SC_Extern:
5873         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5874         // to names of variables declared in a block or to function parameters.
5875         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5876         // of class members
5877 
5878         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5879              diag::err_storage_class_for_static_member)
5880           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5881         break;
5882       case SC_PrivateExtern:
5883         llvm_unreachable("C storage class in c++!");
5884       }
5885     }
5886 
5887     if (SC == SC_Static && CurContext->isRecord()) {
5888       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5889         if (RD->isLocalClass())
5890           Diag(D.getIdentifierLoc(),
5891                diag::err_static_data_member_not_allowed_in_local_class)
5892             << Name << RD->getDeclName();
5893 
5894         // C++98 [class.union]p1: If a union contains a static data member,
5895         // the program is ill-formed. C++11 drops this restriction.
5896         if (RD->isUnion())
5897           Diag(D.getIdentifierLoc(),
5898                getLangOpts().CPlusPlus11
5899                  ? diag::warn_cxx98_compat_static_data_member_in_union
5900                  : diag::ext_static_data_member_in_union) << Name;
5901         // We conservatively disallow static data members in anonymous structs.
5902         else if (!RD->getDeclName())
5903           Diag(D.getIdentifierLoc(),
5904                diag::err_static_data_member_not_allowed_in_anon_struct)
5905             << Name << RD->isUnion();
5906       }
5907     }
5908 
5909     // Match up the template parameter lists with the scope specifier, then
5910     // determine whether we have a template or a template specialization.
5911     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5912         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5913         D.getCXXScopeSpec(),
5914         D.getName().getKind() == UnqualifiedId::IK_TemplateId
5915             ? D.getName().TemplateId
5916             : nullptr,
5917         TemplateParamLists,
5918         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5919 
5920     if (TemplateParams) {
5921       if (!TemplateParams->size() &&
5922           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5923         // There is an extraneous 'template<>' for this variable. Complain
5924         // about it, but allow the declaration of the variable.
5925         Diag(TemplateParams->getTemplateLoc(),
5926              diag::err_template_variable_noparams)
5927           << II
5928           << SourceRange(TemplateParams->getTemplateLoc(),
5929                          TemplateParams->getRAngleLoc());
5930         TemplateParams = nullptr;
5931       } else {
5932         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5933           // This is an explicit specialization or a partial specialization.
5934           // FIXME: Check that we can declare a specialization here.
5935           IsVariableTemplateSpecialization = true;
5936           IsPartialSpecialization = TemplateParams->size() > 0;
5937         } else { // if (TemplateParams->size() > 0)
5938           // This is a template declaration.
5939           IsVariableTemplate = true;
5940 
5941           // Check that we can declare a template here.
5942           if (CheckTemplateDeclScope(S, TemplateParams))
5943             return nullptr;
5944 
5945           // Only C++1y supports variable templates (N3651).
5946           Diag(D.getIdentifierLoc(),
5947                getLangOpts().CPlusPlus14
5948                    ? diag::warn_cxx11_compat_variable_template
5949                    : diag::ext_variable_template);
5950         }
5951       }
5952     } else {
5953       assert(
5954           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5955           "should have a 'template<>' for this decl");
5956     }
5957 
5958     if (IsVariableTemplateSpecialization) {
5959       SourceLocation TemplateKWLoc =
5960           TemplateParamLists.size() > 0
5961               ? TemplateParamLists[0]->getTemplateLoc()
5962               : SourceLocation();
5963       DeclResult Res = ActOnVarTemplateSpecialization(
5964           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5965           IsPartialSpecialization);
5966       if (Res.isInvalid())
5967         return nullptr;
5968       NewVD = cast<VarDecl>(Res.get());
5969       AddToScope = false;
5970     } else
5971       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5972                               D.getIdentifierLoc(), II, R, TInfo, SC);
5973 
5974     // If this is supposed to be a variable template, create it as such.
5975     if (IsVariableTemplate) {
5976       NewTemplate =
5977           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5978                                   TemplateParams, NewVD);
5979       NewVD->setDescribedVarTemplate(NewTemplate);
5980     }
5981 
5982     // If this decl has an auto type in need of deduction, make a note of the
5983     // Decl so we can diagnose uses of it in its own initializer.
5984     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5985       ParsingInitForAutoVars.insert(NewVD);
5986 
5987     if (D.isInvalidType() || Invalid) {
5988       NewVD->setInvalidDecl();
5989       if (NewTemplate)
5990         NewTemplate->setInvalidDecl();
5991     }
5992 
5993     SetNestedNameSpecifier(NewVD, D);
5994 
5995     // If we have any template parameter lists that don't directly belong to
5996     // the variable (matching the scope specifier), store them.
5997     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5998     if (TemplateParamLists.size() > VDTemplateParamLists)
5999       NewVD->setTemplateParameterListsInfo(
6000           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6001 
6002     if (D.getDeclSpec().isConstexprSpecified())
6003       NewVD->setConstexpr(true);
6004 
6005     if (D.getDeclSpec().isConceptSpecified()) {
6006       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6007         VTD->setConcept();
6008 
6009       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6010       // be declared with the thread_local, inline, friend, or constexpr
6011       // specifiers, [...]
6012       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6013         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6014              diag::err_concept_decl_invalid_specifiers)
6015             << 0 << 0;
6016         NewVD->setInvalidDecl(true);
6017       }
6018 
6019       if (D.getDeclSpec().isConstexprSpecified()) {
6020         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6021              diag::err_concept_decl_invalid_specifiers)
6022             << 0 << 3;
6023         NewVD->setInvalidDecl(true);
6024       }
6025 
6026       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6027       // applied only to the definition of a function template or variable
6028       // template, declared in namespace scope.
6029       if (IsVariableTemplateSpecialization) {
6030         Diag(D.getDeclSpec().getConceptSpecLoc(),
6031              diag::err_concept_specified_specialization)
6032             << (IsPartialSpecialization ? 2 : 1);
6033       }
6034 
6035       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6036       // following restrictions:
6037       // - The declared type shall have the type bool.
6038       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6039           !NewVD->isInvalidDecl()) {
6040         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6041         NewVD->setInvalidDecl(true);
6042       }
6043     }
6044   }
6045 
6046   // Set the lexical context. If the declarator has a C++ scope specifier, the
6047   // lexical context will be different from the semantic context.
6048   NewVD->setLexicalDeclContext(CurContext);
6049   if (NewTemplate)
6050     NewTemplate->setLexicalDeclContext(CurContext);
6051 
6052   if (IsLocalExternDecl)
6053     NewVD->setLocalExternDecl();
6054 
6055   bool EmitTLSUnsupportedError = false;
6056   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6057     // C++11 [dcl.stc]p4:
6058     //   When thread_local is applied to a variable of block scope the
6059     //   storage-class-specifier static is implied if it does not appear
6060     //   explicitly.
6061     // Core issue: 'static' is not implied if the variable is declared
6062     //   'extern'.
6063     if (NewVD->hasLocalStorage() &&
6064         (SCSpec != DeclSpec::SCS_unspecified ||
6065          TSCS != DeclSpec::TSCS_thread_local ||
6066          !DC->isFunctionOrMethod()))
6067       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6068            diag::err_thread_non_global)
6069         << DeclSpec::getSpecifierName(TSCS);
6070     else if (!Context.getTargetInfo().isTLSSupported()) {
6071       if (getLangOpts().CUDA) {
6072         // Postpone error emission until we've collected attributes required to
6073         // figure out whether it's a host or device variable and whether the
6074         // error should be ignored.
6075         EmitTLSUnsupportedError = true;
6076         // We still need to mark the variable as TLS so it shows up in AST with
6077         // proper storage class for other tools to use even if we're not going
6078         // to emit any code for it.
6079         NewVD->setTSCSpec(TSCS);
6080       } else
6081         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6082              diag::err_thread_unsupported);
6083     } else
6084       NewVD->setTSCSpec(TSCS);
6085   }
6086 
6087   // C99 6.7.4p3
6088   //   An inline definition of a function with external linkage shall
6089   //   not contain a definition of a modifiable object with static or
6090   //   thread storage duration...
6091   // We only apply this when the function is required to be defined
6092   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6093   // that a local variable with thread storage duration still has to
6094   // be marked 'static'.  Also note that it's possible to get these
6095   // semantics in C++ using __attribute__((gnu_inline)).
6096   if (SC == SC_Static && S->getFnParent() != nullptr &&
6097       !NewVD->getType().isConstQualified()) {
6098     FunctionDecl *CurFD = getCurFunctionDecl();
6099     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6100       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6101            diag::warn_static_local_in_extern_inline);
6102       MaybeSuggestAddingStaticToDecl(CurFD);
6103     }
6104   }
6105 
6106   if (D.getDeclSpec().isModulePrivateSpecified()) {
6107     if (IsVariableTemplateSpecialization)
6108       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6109           << (IsPartialSpecialization ? 1 : 0)
6110           << FixItHint::CreateRemoval(
6111                  D.getDeclSpec().getModulePrivateSpecLoc());
6112     else if (IsExplicitSpecialization)
6113       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6114         << 2
6115         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6116     else if (NewVD->hasLocalStorage())
6117       Diag(NewVD->getLocation(), diag::err_module_private_local)
6118         << 0 << NewVD->getDeclName()
6119         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6120         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6121     else {
6122       NewVD->setModulePrivate();
6123       if (NewTemplate)
6124         NewTemplate->setModulePrivate();
6125     }
6126   }
6127 
6128   // Handle attributes prior to checking for duplicates in MergeVarDecl
6129   ProcessDeclAttributes(S, NewVD, D);
6130 
6131   if (getLangOpts().CUDA) {
6132     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6133       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6134            diag::err_thread_unsupported);
6135     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6136     // storage [duration]."
6137     if (SC == SC_None && S->getFnParent() != nullptr &&
6138         (NewVD->hasAttr<CUDASharedAttr>() ||
6139          NewVD->hasAttr<CUDAConstantAttr>())) {
6140       NewVD->setStorageClass(SC_Static);
6141     }
6142   }
6143 
6144   // Ensure that dllimport globals without explicit storage class are treated as
6145   // extern. The storage class is set above using parsed attributes. Now we can
6146   // check the VarDecl itself.
6147   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6148          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6149          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6150 
6151   // In auto-retain/release, infer strong retension for variables of
6152   // retainable type.
6153   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6154     NewVD->setInvalidDecl();
6155 
6156   // Handle GNU asm-label extension (encoded as an attribute).
6157   if (Expr *E = (Expr*)D.getAsmLabel()) {
6158     // The parser guarantees this is a string.
6159     StringLiteral *SE = cast<StringLiteral>(E);
6160     StringRef Label = SE->getString();
6161     if (S->getFnParent() != nullptr) {
6162       switch (SC) {
6163       case SC_None:
6164       case SC_Auto:
6165         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6166         break;
6167       case SC_Register:
6168         // Local Named register
6169         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6170             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6171           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6172         break;
6173       case SC_Static:
6174       case SC_Extern:
6175       case SC_PrivateExtern:
6176         break;
6177       }
6178     } else if (SC == SC_Register) {
6179       // Global Named register
6180       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6181         const auto &TI = Context.getTargetInfo();
6182         bool HasSizeMismatch;
6183 
6184         if (!TI.isValidGCCRegisterName(Label))
6185           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6186         else if (!TI.validateGlobalRegisterVariable(Label,
6187                                                     Context.getTypeSize(R),
6188                                                     HasSizeMismatch))
6189           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6190         else if (HasSizeMismatch)
6191           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6192       }
6193 
6194       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6195         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6196         NewVD->setInvalidDecl(true);
6197       }
6198     }
6199 
6200     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6201                                                 Context, Label, 0));
6202   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6203     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6204       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6205     if (I != ExtnameUndeclaredIdentifiers.end()) {
6206       if (isDeclExternC(NewVD)) {
6207         NewVD->addAttr(I->second);
6208         ExtnameUndeclaredIdentifiers.erase(I);
6209       } else
6210         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6211             << /*Variable*/1 << NewVD;
6212     }
6213   }
6214 
6215   // Diagnose shadowed variables before filtering for scope.
6216   if (D.getCXXScopeSpec().isEmpty())
6217     CheckShadow(S, NewVD, Previous);
6218 
6219   // Don't consider existing declarations that are in a different
6220   // scope and are out-of-semantic-context declarations (if the new
6221   // declaration has linkage).
6222   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6223                        D.getCXXScopeSpec().isNotEmpty() ||
6224                        IsExplicitSpecialization ||
6225                        IsVariableTemplateSpecialization);
6226 
6227   // Check whether the previous declaration is in the same block scope. This
6228   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6229   if (getLangOpts().CPlusPlus &&
6230       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6231     NewVD->setPreviousDeclInSameBlockScope(
6232         Previous.isSingleResult() && !Previous.isShadowed() &&
6233         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6234 
6235   if (!getLangOpts().CPlusPlus) {
6236     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6237   } else {
6238     // If this is an explicit specialization of a static data member, check it.
6239     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6240         CheckMemberSpecialization(NewVD, Previous))
6241       NewVD->setInvalidDecl();
6242 
6243     // Merge the decl with the existing one if appropriate.
6244     if (!Previous.empty()) {
6245       if (Previous.isSingleResult() &&
6246           isa<FieldDecl>(Previous.getFoundDecl()) &&
6247           D.getCXXScopeSpec().isSet()) {
6248         // The user tried to define a non-static data member
6249         // out-of-line (C++ [dcl.meaning]p1).
6250         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6251           << D.getCXXScopeSpec().getRange();
6252         Previous.clear();
6253         NewVD->setInvalidDecl();
6254       }
6255     } else if (D.getCXXScopeSpec().isSet()) {
6256       // No previous declaration in the qualifying scope.
6257       Diag(D.getIdentifierLoc(), diag::err_no_member)
6258         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6259         << D.getCXXScopeSpec().getRange();
6260       NewVD->setInvalidDecl();
6261     }
6262 
6263     if (!IsVariableTemplateSpecialization)
6264       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6265 
6266     if (NewTemplate) {
6267       VarTemplateDecl *PrevVarTemplate =
6268           NewVD->getPreviousDecl()
6269               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6270               : nullptr;
6271 
6272       // Check the template parameter list of this declaration, possibly
6273       // merging in the template parameter list from the previous variable
6274       // template declaration.
6275       if (CheckTemplateParameterList(
6276               TemplateParams,
6277               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6278                               : nullptr,
6279               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6280                DC->isDependentContext())
6281                   ? TPC_ClassTemplateMember
6282                   : TPC_VarTemplate))
6283         NewVD->setInvalidDecl();
6284 
6285       // If we are providing an explicit specialization of a static variable
6286       // template, make a note of that.
6287       if (PrevVarTemplate &&
6288           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6289         PrevVarTemplate->setMemberSpecialization();
6290     }
6291   }
6292 
6293   ProcessPragmaWeak(S, NewVD);
6294 
6295   // If this is the first declaration of an extern C variable, update
6296   // the map of such variables.
6297   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6298       isIncompleteDeclExternC(*this, NewVD))
6299     RegisterLocallyScopedExternCDecl(NewVD, S);
6300 
6301   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6302     Decl *ManglingContextDecl;
6303     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6304             NewVD->getDeclContext(), ManglingContextDecl)) {
6305       Context.setManglingNumber(
6306           NewVD, MCtx->getManglingNumber(
6307                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6308       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6309     }
6310   }
6311 
6312   // Special handling of variable named 'main'.
6313   if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6314       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6315       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6316 
6317     // C++ [basic.start.main]p3
6318     // A program that declares a variable main at global scope is ill-formed.
6319     if (getLangOpts().CPlusPlus)
6320       Diag(D.getLocStart(), diag::err_main_global_variable);
6321 
6322     // In C, and external-linkage variable named main results in undefined
6323     // behavior.
6324     else if (NewVD->hasExternalFormalLinkage())
6325       Diag(D.getLocStart(), diag::warn_main_redefined);
6326   }
6327 
6328   if (D.isRedeclaration() && !Previous.empty()) {
6329     checkDLLAttributeRedeclaration(
6330         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6331         IsExplicitSpecialization);
6332   }
6333 
6334   if (NewTemplate) {
6335     if (NewVD->isInvalidDecl())
6336       NewTemplate->setInvalidDecl();
6337     ActOnDocumentableDecl(NewTemplate);
6338     return NewTemplate;
6339   }
6340 
6341   return NewVD;
6342 }
6343 
6344 /// \brief Diagnose variable or built-in function shadowing.  Implements
6345 /// -Wshadow.
6346 ///
6347 /// This method is called whenever a VarDecl is added to a "useful"
6348 /// scope.
6349 ///
6350 /// \param S the scope in which the shadowing name is being declared
6351 /// \param R the lookup of the name
6352 ///
6353 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6354   // Return if warning is ignored.
6355   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6356     return;
6357 
6358   // Don't diagnose declarations at file scope.
6359   if (D->hasGlobalStorage())
6360     return;
6361 
6362   DeclContext *NewDC = D->getDeclContext();
6363 
6364   // Only diagnose if we're shadowing an unambiguous field or variable.
6365   if (R.getResultKind() != LookupResult::Found)
6366     return;
6367 
6368   NamedDecl* ShadowedDecl = R.getFoundDecl();
6369   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6370     return;
6371 
6372   // Fields are not shadowed by variables in C++ static methods.
6373   if (isa<FieldDecl>(ShadowedDecl))
6374     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6375       if (MD->isStatic())
6376         return;
6377 
6378   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6379     if (shadowedVar->isExternC()) {
6380       // For shadowing external vars, make sure that we point to the global
6381       // declaration, not a locally scoped extern declaration.
6382       for (auto I : shadowedVar->redecls())
6383         if (I->isFileVarDecl()) {
6384           ShadowedDecl = I;
6385           break;
6386         }
6387     }
6388 
6389   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6390 
6391   // Only warn about certain kinds of shadowing for class members.
6392   if (NewDC && NewDC->isRecord()) {
6393     // In particular, don't warn about shadowing non-class members.
6394     if (!OldDC->isRecord())
6395       return;
6396 
6397     // TODO: should we warn about static data members shadowing
6398     // static data members from base classes?
6399 
6400     // TODO: don't diagnose for inaccessible shadowed members.
6401     // This is hard to do perfectly because we might friend the
6402     // shadowing context, but that's just a false negative.
6403   }
6404 
6405   // Determine what kind of declaration we're shadowing.
6406   unsigned Kind;
6407   if (isa<RecordDecl>(OldDC)) {
6408     if (isa<FieldDecl>(ShadowedDecl))
6409       Kind = 3; // field
6410     else
6411       Kind = 2; // static data member
6412   } else if (OldDC->isFileContext())
6413     Kind = 1; // global
6414   else
6415     Kind = 0; // local
6416 
6417   DeclarationName Name = R.getLookupName();
6418 
6419   // Emit warning and note.
6420   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6421     return;
6422   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6423   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6424 }
6425 
6426 /// \brief Check -Wshadow without the advantage of a previous lookup.
6427 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6428   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6429     return;
6430 
6431   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6432                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6433   LookupName(R, S);
6434   CheckShadow(S, D, R);
6435 }
6436 
6437 /// Check for conflict between this global or extern "C" declaration and
6438 /// previous global or extern "C" declarations. This is only used in C++.
6439 template<typename T>
6440 static bool checkGlobalOrExternCConflict(
6441     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6442   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6443   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6444 
6445   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6446     // The common case: this global doesn't conflict with any extern "C"
6447     // declaration.
6448     return false;
6449   }
6450 
6451   if (Prev) {
6452     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6453       // Both the old and new declarations have C language linkage. This is a
6454       // redeclaration.
6455       Previous.clear();
6456       Previous.addDecl(Prev);
6457       return true;
6458     }
6459 
6460     // This is a global, non-extern "C" declaration, and there is a previous
6461     // non-global extern "C" declaration. Diagnose if this is a variable
6462     // declaration.
6463     if (!isa<VarDecl>(ND))
6464       return false;
6465   } else {
6466     // The declaration is extern "C". Check for any declaration in the
6467     // translation unit which might conflict.
6468     if (IsGlobal) {
6469       // We have already performed the lookup into the translation unit.
6470       IsGlobal = false;
6471       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6472            I != E; ++I) {
6473         if (isa<VarDecl>(*I)) {
6474           Prev = *I;
6475           break;
6476         }
6477       }
6478     } else {
6479       DeclContext::lookup_result R =
6480           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6481       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6482            I != E; ++I) {
6483         if (isa<VarDecl>(*I)) {
6484           Prev = *I;
6485           break;
6486         }
6487         // FIXME: If we have any other entity with this name in global scope,
6488         // the declaration is ill-formed, but that is a defect: it breaks the
6489         // 'stat' hack, for instance. Only variables can have mangled name
6490         // clashes with extern "C" declarations, so only they deserve a
6491         // diagnostic.
6492       }
6493     }
6494 
6495     if (!Prev)
6496       return false;
6497   }
6498 
6499   // Use the first declaration's location to ensure we point at something which
6500   // is lexically inside an extern "C" linkage-spec.
6501   assert(Prev && "should have found a previous declaration to diagnose");
6502   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6503     Prev = FD->getFirstDecl();
6504   else
6505     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6506 
6507   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6508     << IsGlobal << ND;
6509   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6510     << IsGlobal;
6511   return false;
6512 }
6513 
6514 /// Apply special rules for handling extern "C" declarations. Returns \c true
6515 /// if we have found that this is a redeclaration of some prior entity.
6516 ///
6517 /// Per C++ [dcl.link]p6:
6518 ///   Two declarations [for a function or variable] with C language linkage
6519 ///   with the same name that appear in different scopes refer to the same
6520 ///   [entity]. An entity with C language linkage shall not be declared with
6521 ///   the same name as an entity in global scope.
6522 template<typename T>
6523 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6524                                                   LookupResult &Previous) {
6525   if (!S.getLangOpts().CPlusPlus) {
6526     // In C, when declaring a global variable, look for a corresponding 'extern'
6527     // variable declared in function scope. We don't need this in C++, because
6528     // we find local extern decls in the surrounding file-scope DeclContext.
6529     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6530       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6531         Previous.clear();
6532         Previous.addDecl(Prev);
6533         return true;
6534       }
6535     }
6536     return false;
6537   }
6538 
6539   // A declaration in the translation unit can conflict with an extern "C"
6540   // declaration.
6541   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6542     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6543 
6544   // An extern "C" declaration can conflict with a declaration in the
6545   // translation unit or can be a redeclaration of an extern "C" declaration
6546   // in another scope.
6547   if (isIncompleteDeclExternC(S,ND))
6548     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6549 
6550   // Neither global nor extern "C": nothing to do.
6551   return false;
6552 }
6553 
6554 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6555   // If the decl is already known invalid, don't check it.
6556   if (NewVD->isInvalidDecl())
6557     return;
6558 
6559   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6560   QualType T = TInfo->getType();
6561 
6562   // Defer checking an 'auto' type until its initializer is attached.
6563   if (T->isUndeducedType())
6564     return;
6565 
6566   if (NewVD->hasAttrs())
6567     CheckAlignasUnderalignment(NewVD);
6568 
6569   if (T->isObjCObjectType()) {
6570     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6571       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6572     T = Context.getObjCObjectPointerType(T);
6573     NewVD->setType(T);
6574   }
6575 
6576   // Emit an error if an address space was applied to decl with local storage.
6577   // This includes arrays of objects with address space qualifiers, but not
6578   // automatic variables that point to other address spaces.
6579   // ISO/IEC TR 18037 S5.1.2
6580   if (!getLangOpts().OpenCL
6581       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6582     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6583     NewVD->setInvalidDecl();
6584     return;
6585   }
6586 
6587   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6588   // scope.
6589   if (getLangOpts().OpenCLVersion == 120 &&
6590       !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6591       NewVD->isStaticLocal()) {
6592     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6593     NewVD->setInvalidDecl();
6594     return;
6595   }
6596 
6597   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6598   // __constant address space.
6599   // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6600   // variables inside a function can also be declared in the global
6601   // address space.
6602   if (getLangOpts().OpenCL) {
6603     if (NewVD->isFileVarDecl()) {
6604       if (!T->isSamplerT() &&
6605           !(T.getAddressSpace() == LangAS::opencl_constant ||
6606             (T.getAddressSpace() == LangAS::opencl_global &&
6607              getLangOpts().OpenCLVersion == 200))) {
6608         if (getLangOpts().OpenCLVersion == 200)
6609           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6610               << "global or constant";
6611         else
6612           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6613               << "constant";
6614         NewVD->setInvalidDecl();
6615         return;
6616       }
6617     } else {
6618       // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6619       // variables inside a function can also be declared in the global
6620       // address space.
6621       if (NewVD->isStaticLocal() &&
6622           !(T.getAddressSpace() == LangAS::opencl_constant ||
6623             (T.getAddressSpace() == LangAS::opencl_global &&
6624              getLangOpts().OpenCLVersion == 200))) {
6625         if (getLangOpts().OpenCLVersion == 200)
6626           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6627               << "global or constant";
6628         else
6629           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6630               << "constant";
6631         NewVD->setInvalidDecl();
6632         return;
6633       }
6634       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6635       // in functions.
6636       if (T.getAddressSpace() == LangAS::opencl_constant ||
6637           T.getAddressSpace() == LangAS::opencl_local) {
6638         FunctionDecl *FD = getCurFunctionDecl();
6639         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6640           if (T.getAddressSpace() == LangAS::opencl_constant)
6641             Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable)
6642                 << "constant";
6643           else
6644             Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable)
6645                 << "local";
6646           NewVD->setInvalidDecl();
6647           return;
6648         }
6649       }
6650     }
6651   }
6652 
6653   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6654       && !NewVD->hasAttr<BlocksAttr>()) {
6655     if (getLangOpts().getGC() != LangOptions::NonGC)
6656       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6657     else {
6658       assert(!getLangOpts().ObjCAutoRefCount);
6659       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6660     }
6661   }
6662 
6663   bool isVM = T->isVariablyModifiedType();
6664   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6665       NewVD->hasAttr<BlocksAttr>())
6666     getCurFunction()->setHasBranchProtectedScope();
6667 
6668   if ((isVM && NewVD->hasLinkage()) ||
6669       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6670     bool SizeIsNegative;
6671     llvm::APSInt Oversized;
6672     TypeSourceInfo *FixedTInfo =
6673       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6674                                                     SizeIsNegative, Oversized);
6675     if (!FixedTInfo && T->isVariableArrayType()) {
6676       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6677       // FIXME: This won't give the correct result for
6678       // int a[10][n];
6679       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6680 
6681       if (NewVD->isFileVarDecl())
6682         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6683         << SizeRange;
6684       else if (NewVD->isStaticLocal())
6685         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6686         << SizeRange;
6687       else
6688         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6689         << SizeRange;
6690       NewVD->setInvalidDecl();
6691       return;
6692     }
6693 
6694     if (!FixedTInfo) {
6695       if (NewVD->isFileVarDecl())
6696         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6697       else
6698         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6699       NewVD->setInvalidDecl();
6700       return;
6701     }
6702 
6703     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6704     NewVD->setType(FixedTInfo->getType());
6705     NewVD->setTypeSourceInfo(FixedTInfo);
6706   }
6707 
6708   if (T->isVoidType()) {
6709     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6710     //                    of objects and functions.
6711     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6712       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6713         << T;
6714       NewVD->setInvalidDecl();
6715       return;
6716     }
6717   }
6718 
6719   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6720     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6721     NewVD->setInvalidDecl();
6722     return;
6723   }
6724 
6725   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6726     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6727     NewVD->setInvalidDecl();
6728     return;
6729   }
6730 
6731   if (NewVD->isConstexpr() && !T->isDependentType() &&
6732       RequireLiteralType(NewVD->getLocation(), T,
6733                          diag::err_constexpr_var_non_literal)) {
6734     NewVD->setInvalidDecl();
6735     return;
6736   }
6737 
6738   // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported.
6739   if (LangOpts.OpenCL && T->isBlockPointerType()) {
6740     const BlockPointerType *BlkTy = T->getAs<BlockPointerType>();
6741     const FunctionProtoType *FTy =
6742         BlkTy->getPointeeType()->getAs<FunctionProtoType>();
6743     if (FTy->isVariadic()) {
6744       Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic)
6745           << T << NewVD->getSourceRange();
6746       NewVD->setInvalidDecl();
6747       return;
6748     }
6749   }
6750 }
6751 
6752 /// \brief Perform semantic checking on a newly-created variable
6753 /// declaration.
6754 ///
6755 /// This routine performs all of the type-checking required for a
6756 /// variable declaration once it has been built. It is used both to
6757 /// check variables after they have been parsed and their declarators
6758 /// have been translated into a declaration, and to check variables
6759 /// that have been instantiated from a template.
6760 ///
6761 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6762 ///
6763 /// Returns true if the variable declaration is a redeclaration.
6764 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6765   CheckVariableDeclarationType(NewVD);
6766 
6767   // If the decl is already known invalid, don't check it.
6768   if (NewVD->isInvalidDecl())
6769     return false;
6770 
6771   // If we did not find anything by this name, look for a non-visible
6772   // extern "C" declaration with the same name.
6773   if (Previous.empty() &&
6774       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6775     Previous.setShadowed();
6776 
6777   if (!Previous.empty()) {
6778     MergeVarDecl(NewVD, Previous);
6779     return true;
6780   }
6781   return false;
6782 }
6783 
6784 namespace {
6785 struct FindOverriddenMethod {
6786   Sema *S;
6787   CXXMethodDecl *Method;
6788 
6789   /// Member lookup function that determines whether a given C++
6790   /// method overrides a method in a base class, to be used with
6791   /// CXXRecordDecl::lookupInBases().
6792   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6793     RecordDecl *BaseRecord =
6794         Specifier->getType()->getAs<RecordType>()->getDecl();
6795 
6796     DeclarationName Name = Method->getDeclName();
6797 
6798     // FIXME: Do we care about other names here too?
6799     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6800       // We really want to find the base class destructor here.
6801       QualType T = S->Context.getTypeDeclType(BaseRecord);
6802       CanQualType CT = S->Context.getCanonicalType(T);
6803 
6804       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
6805     }
6806 
6807     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6808          Path.Decls = Path.Decls.slice(1)) {
6809       NamedDecl *D = Path.Decls.front();
6810       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6811         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
6812           return true;
6813       }
6814     }
6815 
6816     return false;
6817   }
6818 };
6819 
6820 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6821 } // end anonymous namespace
6822 
6823 /// \brief Report an error regarding overriding, along with any relevant
6824 /// overriden methods.
6825 ///
6826 /// \param DiagID the primary error to report.
6827 /// \param MD the overriding method.
6828 /// \param OEK which overrides to include as notes.
6829 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6830                             OverrideErrorKind OEK = OEK_All) {
6831   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6832   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6833                                       E = MD->end_overridden_methods();
6834        I != E; ++I) {
6835     // This check (& the OEK parameter) could be replaced by a predicate, but
6836     // without lambdas that would be overkill. This is still nicer than writing
6837     // out the diag loop 3 times.
6838     if ((OEK == OEK_All) ||
6839         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6840         (OEK == OEK_Deleted && (*I)->isDeleted()))
6841       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6842   }
6843 }
6844 
6845 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6846 /// and if so, check that it's a valid override and remember it.
6847 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6848   // Look for methods in base classes that this method might override.
6849   CXXBasePaths Paths;
6850   FindOverriddenMethod FOM;
6851   FOM.Method = MD;
6852   FOM.S = this;
6853   bool hasDeletedOverridenMethods = false;
6854   bool hasNonDeletedOverridenMethods = false;
6855   bool AddedAny = false;
6856   if (DC->lookupInBases(FOM, Paths)) {
6857     for (auto *I : Paths.found_decls()) {
6858       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6859         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6860         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6861             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6862             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6863             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6864           hasDeletedOverridenMethods |= OldMD->isDeleted();
6865           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6866           AddedAny = true;
6867         }
6868       }
6869     }
6870   }
6871 
6872   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6873     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6874   }
6875   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6876     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6877   }
6878 
6879   return AddedAny;
6880 }
6881 
6882 namespace {
6883   // Struct for holding all of the extra arguments needed by
6884   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6885   struct ActOnFDArgs {
6886     Scope *S;
6887     Declarator &D;
6888     MultiTemplateParamsArg TemplateParamLists;
6889     bool AddToScope;
6890   };
6891 } // end anonymous namespace
6892 
6893 namespace {
6894 
6895 // Callback to only accept typo corrections that have a non-zero edit distance.
6896 // Also only accept corrections that have the same parent decl.
6897 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6898  public:
6899   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6900                             CXXRecordDecl *Parent)
6901       : Context(Context), OriginalFD(TypoFD),
6902         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6903 
6904   bool ValidateCandidate(const TypoCorrection &candidate) override {
6905     if (candidate.getEditDistance() == 0)
6906       return false;
6907 
6908     SmallVector<unsigned, 1> MismatchedParams;
6909     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6910                                           CDeclEnd = candidate.end();
6911          CDecl != CDeclEnd; ++CDecl) {
6912       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6913 
6914       if (FD && !FD->hasBody() &&
6915           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6916         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6917           CXXRecordDecl *Parent = MD->getParent();
6918           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6919             return true;
6920         } else if (!ExpectedParent) {
6921           return true;
6922         }
6923       }
6924     }
6925 
6926     return false;
6927   }
6928 
6929  private:
6930   ASTContext &Context;
6931   FunctionDecl *OriginalFD;
6932   CXXRecordDecl *ExpectedParent;
6933 };
6934 
6935 } // end anonymous namespace
6936 
6937 /// \brief Generate diagnostics for an invalid function redeclaration.
6938 ///
6939 /// This routine handles generating the diagnostic messages for an invalid
6940 /// function redeclaration, including finding possible similar declarations
6941 /// or performing typo correction if there are no previous declarations with
6942 /// the same name.
6943 ///
6944 /// Returns a NamedDecl iff typo correction was performed and substituting in
6945 /// the new declaration name does not cause new errors.
6946 static NamedDecl *DiagnoseInvalidRedeclaration(
6947     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6948     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6949   DeclarationName Name = NewFD->getDeclName();
6950   DeclContext *NewDC = NewFD->getDeclContext();
6951   SmallVector<unsigned, 1> MismatchedParams;
6952   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6953   TypoCorrection Correction;
6954   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6955   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6956                                    : diag::err_member_decl_does_not_match;
6957   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6958                     IsLocalFriend ? Sema::LookupLocalFriendName
6959                                   : Sema::LookupOrdinaryName,
6960                     Sema::ForRedeclaration);
6961 
6962   NewFD->setInvalidDecl();
6963   if (IsLocalFriend)
6964     SemaRef.LookupName(Prev, S);
6965   else
6966     SemaRef.LookupQualifiedName(Prev, NewDC);
6967   assert(!Prev.isAmbiguous() &&
6968          "Cannot have an ambiguity in previous-declaration lookup");
6969   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6970   if (!Prev.empty()) {
6971     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6972          Func != FuncEnd; ++Func) {
6973       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6974       if (FD &&
6975           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6976         // Add 1 to the index so that 0 can mean the mismatch didn't
6977         // involve a parameter
6978         unsigned ParamNum =
6979             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6980         NearMatches.push_back(std::make_pair(FD, ParamNum));
6981       }
6982     }
6983   // If the qualified name lookup yielded nothing, try typo correction
6984   } else if ((Correction = SemaRef.CorrectTypo(
6985                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6986                   &ExtraArgs.D.getCXXScopeSpec(),
6987                   llvm::make_unique<DifferentNameValidatorCCC>(
6988                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
6989                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6990     // Set up everything for the call to ActOnFunctionDeclarator
6991     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6992                               ExtraArgs.D.getIdentifierLoc());
6993     Previous.clear();
6994     Previous.setLookupName(Correction.getCorrection());
6995     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6996                                     CDeclEnd = Correction.end();
6997          CDecl != CDeclEnd; ++CDecl) {
6998       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6999       if (FD && !FD->hasBody() &&
7000           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7001         Previous.addDecl(FD);
7002       }
7003     }
7004     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7005 
7006     NamedDecl *Result;
7007     // Retry building the function declaration with the new previous
7008     // declarations, and with errors suppressed.
7009     {
7010       // Trap errors.
7011       Sema::SFINAETrap Trap(SemaRef);
7012 
7013       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7014       // pieces need to verify the typo-corrected C++ declaration and hopefully
7015       // eliminate the need for the parameter pack ExtraArgs.
7016       Result = SemaRef.ActOnFunctionDeclarator(
7017           ExtraArgs.S, ExtraArgs.D,
7018           Correction.getCorrectionDecl()->getDeclContext(),
7019           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7020           ExtraArgs.AddToScope);
7021 
7022       if (Trap.hasErrorOccurred())
7023         Result = nullptr;
7024     }
7025 
7026     if (Result) {
7027       // Determine which correction we picked.
7028       Decl *Canonical = Result->getCanonicalDecl();
7029       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7030            I != E; ++I)
7031         if ((*I)->getCanonicalDecl() == Canonical)
7032           Correction.setCorrectionDecl(*I);
7033 
7034       SemaRef.diagnoseTypo(
7035           Correction,
7036           SemaRef.PDiag(IsLocalFriend
7037                           ? diag::err_no_matching_local_friend_suggest
7038                           : diag::err_member_decl_does_not_match_suggest)
7039             << Name << NewDC << IsDefinition);
7040       return Result;
7041     }
7042 
7043     // Pretend the typo correction never occurred
7044     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7045                               ExtraArgs.D.getIdentifierLoc());
7046     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7047     Previous.clear();
7048     Previous.setLookupName(Name);
7049   }
7050 
7051   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7052       << Name << NewDC << IsDefinition << NewFD->getLocation();
7053 
7054   bool NewFDisConst = false;
7055   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7056     NewFDisConst = NewMD->isConst();
7057 
7058   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7059        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7060        NearMatch != NearMatchEnd; ++NearMatch) {
7061     FunctionDecl *FD = NearMatch->first;
7062     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7063     bool FDisConst = MD && MD->isConst();
7064     bool IsMember = MD || !IsLocalFriend;
7065 
7066     // FIXME: These notes are poorly worded for the local friend case.
7067     if (unsigned Idx = NearMatch->second) {
7068       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7069       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7070       if (Loc.isInvalid()) Loc = FD->getLocation();
7071       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7072                                  : diag::note_local_decl_close_param_match)
7073         << Idx << FDParam->getType()
7074         << NewFD->getParamDecl(Idx - 1)->getType();
7075     } else if (FDisConst != NewFDisConst) {
7076       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7077           << NewFDisConst << FD->getSourceRange().getEnd();
7078     } else
7079       SemaRef.Diag(FD->getLocation(),
7080                    IsMember ? diag::note_member_def_close_match
7081                             : diag::note_local_decl_close_match);
7082   }
7083   return nullptr;
7084 }
7085 
7086 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7087   switch (D.getDeclSpec().getStorageClassSpec()) {
7088   default: llvm_unreachable("Unknown storage class!");
7089   case DeclSpec::SCS_auto:
7090   case DeclSpec::SCS_register:
7091   case DeclSpec::SCS_mutable:
7092     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7093                  diag::err_typecheck_sclass_func);
7094     D.setInvalidType();
7095     break;
7096   case DeclSpec::SCS_unspecified: break;
7097   case DeclSpec::SCS_extern:
7098     if (D.getDeclSpec().isExternInLinkageSpec())
7099       return SC_None;
7100     return SC_Extern;
7101   case DeclSpec::SCS_static: {
7102     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7103       // C99 6.7.1p5:
7104       //   The declaration of an identifier for a function that has
7105       //   block scope shall have no explicit storage-class specifier
7106       //   other than extern
7107       // See also (C++ [dcl.stc]p4).
7108       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7109                    diag::err_static_block_func);
7110       break;
7111     } else
7112       return SC_Static;
7113   }
7114   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7115   }
7116 
7117   // No explicit storage class has already been returned
7118   return SC_None;
7119 }
7120 
7121 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7122                                            DeclContext *DC, QualType &R,
7123                                            TypeSourceInfo *TInfo,
7124                                            StorageClass SC,
7125                                            bool &IsVirtualOkay) {
7126   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7127   DeclarationName Name = NameInfo.getName();
7128 
7129   FunctionDecl *NewFD = nullptr;
7130   bool isInline = D.getDeclSpec().isInlineSpecified();
7131 
7132   if (!SemaRef.getLangOpts().CPlusPlus) {
7133     // Determine whether the function was written with a
7134     // prototype. This true when:
7135     //   - there is a prototype in the declarator, or
7136     //   - the type R of the function is some kind of typedef or other reference
7137     //     to a type name (which eventually refers to a function type).
7138     bool HasPrototype =
7139       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7140       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7141 
7142     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7143                                  D.getLocStart(), NameInfo, R,
7144                                  TInfo, SC, isInline,
7145                                  HasPrototype, false);
7146     if (D.isInvalidType())
7147       NewFD->setInvalidDecl();
7148 
7149     return NewFD;
7150   }
7151 
7152   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7153   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7154 
7155   // Check that the return type is not an abstract class type.
7156   // For record types, this is done by the AbstractClassUsageDiagnoser once
7157   // the class has been completely parsed.
7158   if (!DC->isRecord() &&
7159       SemaRef.RequireNonAbstractType(
7160           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7161           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7162     D.setInvalidType();
7163 
7164   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7165     // This is a C++ constructor declaration.
7166     assert(DC->isRecord() &&
7167            "Constructors can only be declared in a member context");
7168 
7169     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7170     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7171                                       D.getLocStart(), NameInfo,
7172                                       R, TInfo, isExplicit, isInline,
7173                                       /*isImplicitlyDeclared=*/false,
7174                                       isConstexpr);
7175 
7176   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7177     // This is a C++ destructor declaration.
7178     if (DC->isRecord()) {
7179       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7180       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7181       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7182                                         SemaRef.Context, Record,
7183                                         D.getLocStart(),
7184                                         NameInfo, R, TInfo, isInline,
7185                                         /*isImplicitlyDeclared=*/false);
7186 
7187       // If the class is complete, then we now create the implicit exception
7188       // specification. If the class is incomplete or dependent, we can't do
7189       // it yet.
7190       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7191           Record->getDefinition() && !Record->isBeingDefined() &&
7192           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7193         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7194       }
7195 
7196       IsVirtualOkay = true;
7197       return NewDD;
7198 
7199     } else {
7200       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7201       D.setInvalidType();
7202 
7203       // Create a FunctionDecl to satisfy the function definition parsing
7204       // code path.
7205       return FunctionDecl::Create(SemaRef.Context, DC,
7206                                   D.getLocStart(),
7207                                   D.getIdentifierLoc(), Name, R, TInfo,
7208                                   SC, isInline,
7209                                   /*hasPrototype=*/true, isConstexpr);
7210     }
7211 
7212   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7213     if (!DC->isRecord()) {
7214       SemaRef.Diag(D.getIdentifierLoc(),
7215            diag::err_conv_function_not_member);
7216       return nullptr;
7217     }
7218 
7219     SemaRef.CheckConversionDeclarator(D, R, SC);
7220     IsVirtualOkay = true;
7221     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7222                                      D.getLocStart(), NameInfo,
7223                                      R, TInfo, isInline, isExplicit,
7224                                      isConstexpr, SourceLocation());
7225 
7226   } else if (DC->isRecord()) {
7227     // If the name of the function is the same as the name of the record,
7228     // then this must be an invalid constructor that has a return type.
7229     // (The parser checks for a return type and makes the declarator a
7230     // constructor if it has no return type).
7231     if (Name.getAsIdentifierInfo() &&
7232         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7233       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7234         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7235         << SourceRange(D.getIdentifierLoc());
7236       return nullptr;
7237     }
7238 
7239     // This is a C++ method declaration.
7240     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7241                                                cast<CXXRecordDecl>(DC),
7242                                                D.getLocStart(), NameInfo, R,
7243                                                TInfo, SC, isInline,
7244                                                isConstexpr, SourceLocation());
7245     IsVirtualOkay = !Ret->isStatic();
7246     return Ret;
7247   } else {
7248     bool isFriend =
7249         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7250     if (!isFriend && SemaRef.CurContext->isRecord())
7251       return nullptr;
7252 
7253     // Determine whether the function was written with a
7254     // prototype. This true when:
7255     //   - we're in C++ (where every function has a prototype),
7256     return FunctionDecl::Create(SemaRef.Context, DC,
7257                                 D.getLocStart(),
7258                                 NameInfo, R, TInfo, SC, isInline,
7259                                 true/*HasPrototype*/, isConstexpr);
7260   }
7261 }
7262 
7263 enum OpenCLParamType {
7264   ValidKernelParam,
7265   PtrPtrKernelParam,
7266   PtrKernelParam,
7267   PrivatePtrKernelParam,
7268   InvalidKernelParam,
7269   RecordKernelParam
7270 };
7271 
7272 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7273   if (PT->isPointerType()) {
7274     QualType PointeeType = PT->getPointeeType();
7275     if (PointeeType->isPointerType())
7276       return PtrPtrKernelParam;
7277     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7278                                               : PtrKernelParam;
7279   }
7280 
7281   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7282   // be used as builtin types.
7283 
7284   if (PT->isImageType())
7285     return PtrKernelParam;
7286 
7287   if (PT->isBooleanType())
7288     return InvalidKernelParam;
7289 
7290   if (PT->isEventT())
7291     return InvalidKernelParam;
7292 
7293   if (PT->isHalfType())
7294     return InvalidKernelParam;
7295 
7296   if (PT->isRecordType())
7297     return RecordKernelParam;
7298 
7299   return ValidKernelParam;
7300 }
7301 
7302 static void checkIsValidOpenCLKernelParameter(
7303   Sema &S,
7304   Declarator &D,
7305   ParmVarDecl *Param,
7306   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7307   QualType PT = Param->getType();
7308 
7309   // Cache the valid types we encounter to avoid rechecking structs that are
7310   // used again
7311   if (ValidTypes.count(PT.getTypePtr()))
7312     return;
7313 
7314   switch (getOpenCLKernelParameterType(PT)) {
7315   case PtrPtrKernelParam:
7316     // OpenCL v1.2 s6.9.a:
7317     // A kernel function argument cannot be declared as a
7318     // pointer to a pointer type.
7319     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7320     D.setInvalidType();
7321     return;
7322 
7323   case PrivatePtrKernelParam:
7324     // OpenCL v1.2 s6.9.a:
7325     // A kernel function argument cannot be declared as a
7326     // pointer to the private address space.
7327     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7328     D.setInvalidType();
7329     return;
7330 
7331     // OpenCL v1.2 s6.9.k:
7332     // Arguments to kernel functions in a program cannot be declared with the
7333     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7334     // uintptr_t or a struct and/or union that contain fields declared to be
7335     // one of these built-in scalar types.
7336 
7337   case InvalidKernelParam:
7338     // OpenCL v1.2 s6.8 n:
7339     // A kernel function argument cannot be declared
7340     // of event_t type.
7341     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7342     D.setInvalidType();
7343     return;
7344 
7345   case PtrKernelParam:
7346   case ValidKernelParam:
7347     ValidTypes.insert(PT.getTypePtr());
7348     return;
7349 
7350   case RecordKernelParam:
7351     break;
7352   }
7353 
7354   // Track nested structs we will inspect
7355   SmallVector<const Decl *, 4> VisitStack;
7356 
7357   // Track where we are in the nested structs. Items will migrate from
7358   // VisitStack to HistoryStack as we do the DFS for bad field.
7359   SmallVector<const FieldDecl *, 4> HistoryStack;
7360   HistoryStack.push_back(nullptr);
7361 
7362   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7363   VisitStack.push_back(PD);
7364 
7365   assert(VisitStack.back() && "First decl null?");
7366 
7367   do {
7368     const Decl *Next = VisitStack.pop_back_val();
7369     if (!Next) {
7370       assert(!HistoryStack.empty());
7371       // Found a marker, we have gone up a level
7372       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7373         ValidTypes.insert(Hist->getType().getTypePtr());
7374 
7375       continue;
7376     }
7377 
7378     // Adds everything except the original parameter declaration (which is not a
7379     // field itself) to the history stack.
7380     const RecordDecl *RD;
7381     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7382       HistoryStack.push_back(Field);
7383       RD = Field->getType()->castAs<RecordType>()->getDecl();
7384     } else {
7385       RD = cast<RecordDecl>(Next);
7386     }
7387 
7388     // Add a null marker so we know when we've gone back up a level
7389     VisitStack.push_back(nullptr);
7390 
7391     for (const auto *FD : RD->fields()) {
7392       QualType QT = FD->getType();
7393 
7394       if (ValidTypes.count(QT.getTypePtr()))
7395         continue;
7396 
7397       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7398       if (ParamType == ValidKernelParam)
7399         continue;
7400 
7401       if (ParamType == RecordKernelParam) {
7402         VisitStack.push_back(FD);
7403         continue;
7404       }
7405 
7406       // OpenCL v1.2 s6.9.p:
7407       // Arguments to kernel functions that are declared to be a struct or union
7408       // do not allow OpenCL objects to be passed as elements of the struct or
7409       // union.
7410       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7411           ParamType == PrivatePtrKernelParam) {
7412         S.Diag(Param->getLocation(),
7413                diag::err_record_with_pointers_kernel_param)
7414           << PT->isUnionType()
7415           << PT;
7416       } else {
7417         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7418       }
7419 
7420       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7421         << PD->getDeclName();
7422 
7423       // We have an error, now let's go back up through history and show where
7424       // the offending field came from
7425       for (ArrayRef<const FieldDecl *>::const_iterator
7426                I = HistoryStack.begin() + 1,
7427                E = HistoryStack.end();
7428            I != E; ++I) {
7429         const FieldDecl *OuterField = *I;
7430         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7431           << OuterField->getType();
7432       }
7433 
7434       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7435         << QT->isPointerType()
7436         << QT;
7437       D.setInvalidType();
7438       return;
7439     }
7440   } while (!VisitStack.empty());
7441 }
7442 
7443 NamedDecl*
7444 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7445                               TypeSourceInfo *TInfo, LookupResult &Previous,
7446                               MultiTemplateParamsArg TemplateParamLists,
7447                               bool &AddToScope) {
7448   QualType R = TInfo->getType();
7449 
7450   assert(R.getTypePtr()->isFunctionType());
7451 
7452   // TODO: consider using NameInfo for diagnostic.
7453   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7454   DeclarationName Name = NameInfo.getName();
7455   StorageClass SC = getFunctionStorageClass(*this, D);
7456 
7457   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7458     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7459          diag::err_invalid_thread)
7460       << DeclSpec::getSpecifierName(TSCS);
7461 
7462   if (D.isFirstDeclarationOfMember())
7463     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7464                            D.getIdentifierLoc());
7465 
7466   bool isFriend = false;
7467   FunctionTemplateDecl *FunctionTemplate = nullptr;
7468   bool isExplicitSpecialization = false;
7469   bool isFunctionTemplateSpecialization = false;
7470 
7471   bool isDependentClassScopeExplicitSpecialization = false;
7472   bool HasExplicitTemplateArgs = false;
7473   TemplateArgumentListInfo TemplateArgs;
7474 
7475   bool isVirtualOkay = false;
7476 
7477   DeclContext *OriginalDC = DC;
7478   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7479 
7480   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7481                                               isVirtualOkay);
7482   if (!NewFD) return nullptr;
7483 
7484   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7485     NewFD->setTopLevelDeclInObjCContainer();
7486 
7487   // Set the lexical context. If this is a function-scope declaration, or has a
7488   // C++ scope specifier, or is the object of a friend declaration, the lexical
7489   // context will be different from the semantic context.
7490   NewFD->setLexicalDeclContext(CurContext);
7491 
7492   if (IsLocalExternDecl)
7493     NewFD->setLocalExternDecl();
7494 
7495   if (getLangOpts().CPlusPlus) {
7496     bool isInline = D.getDeclSpec().isInlineSpecified();
7497     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7498     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7499     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7500     bool isConcept = D.getDeclSpec().isConceptSpecified();
7501     isFriend = D.getDeclSpec().isFriendSpecified();
7502     if (isFriend && !isInline && D.isFunctionDefinition()) {
7503       // C++ [class.friend]p5
7504       //   A function can be defined in a friend declaration of a
7505       //   class . . . . Such a function is implicitly inline.
7506       NewFD->setImplicitlyInline();
7507     }
7508 
7509     // If this is a method defined in an __interface, and is not a constructor
7510     // or an overloaded operator, then set the pure flag (isVirtual will already
7511     // return true).
7512     if (const CXXRecordDecl *Parent =
7513           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7514       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7515         NewFD->setPure(true);
7516 
7517       // C++ [class.union]p2
7518       //   A union can have member functions, but not virtual functions.
7519       if (isVirtual && Parent->isUnion())
7520         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7521     }
7522 
7523     SetNestedNameSpecifier(NewFD, D);
7524     isExplicitSpecialization = false;
7525     isFunctionTemplateSpecialization = false;
7526     if (D.isInvalidType())
7527       NewFD->setInvalidDecl();
7528 
7529     // Match up the template parameter lists with the scope specifier, then
7530     // determine whether we have a template or a template specialization.
7531     bool Invalid = false;
7532     if (TemplateParameterList *TemplateParams =
7533             MatchTemplateParametersToScopeSpecifier(
7534                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7535                 D.getCXXScopeSpec(),
7536                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7537                     ? D.getName().TemplateId
7538                     : nullptr,
7539                 TemplateParamLists, isFriend, isExplicitSpecialization,
7540                 Invalid)) {
7541       if (TemplateParams->size() > 0) {
7542         // This is a function template
7543 
7544         // Check that we can declare a template here.
7545         if (CheckTemplateDeclScope(S, TemplateParams))
7546           NewFD->setInvalidDecl();
7547 
7548         // A destructor cannot be a template.
7549         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7550           Diag(NewFD->getLocation(), diag::err_destructor_template);
7551           NewFD->setInvalidDecl();
7552         }
7553 
7554         // If we're adding a template to a dependent context, we may need to
7555         // rebuilding some of the types used within the template parameter list,
7556         // now that we know what the current instantiation is.
7557         if (DC->isDependentContext()) {
7558           ContextRAII SavedContext(*this, DC);
7559           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7560             Invalid = true;
7561         }
7562 
7563         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7564                                                         NewFD->getLocation(),
7565                                                         Name, TemplateParams,
7566                                                         NewFD);
7567         FunctionTemplate->setLexicalDeclContext(CurContext);
7568         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7569 
7570         // For source fidelity, store the other template param lists.
7571         if (TemplateParamLists.size() > 1) {
7572           NewFD->setTemplateParameterListsInfo(Context,
7573                                                TemplateParamLists.drop_back(1));
7574         }
7575       } else {
7576         // This is a function template specialization.
7577         isFunctionTemplateSpecialization = true;
7578         // For source fidelity, store all the template param lists.
7579         if (TemplateParamLists.size() > 0)
7580           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7581 
7582         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7583         if (isFriend) {
7584           // We want to remove the "template<>", found here.
7585           SourceRange RemoveRange = TemplateParams->getSourceRange();
7586 
7587           // If we remove the template<> and the name is not a
7588           // template-id, we're actually silently creating a problem:
7589           // the friend declaration will refer to an untemplated decl,
7590           // and clearly the user wants a template specialization.  So
7591           // we need to insert '<>' after the name.
7592           SourceLocation InsertLoc;
7593           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7594             InsertLoc = D.getName().getSourceRange().getEnd();
7595             InsertLoc = getLocForEndOfToken(InsertLoc);
7596           }
7597 
7598           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7599             << Name << RemoveRange
7600             << FixItHint::CreateRemoval(RemoveRange)
7601             << FixItHint::CreateInsertion(InsertLoc, "<>");
7602         }
7603       }
7604     }
7605     else {
7606       // All template param lists were matched against the scope specifier:
7607       // this is NOT (an explicit specialization of) a template.
7608       if (TemplateParamLists.size() > 0)
7609         // For source fidelity, store all the template param lists.
7610         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7611     }
7612 
7613     if (Invalid) {
7614       NewFD->setInvalidDecl();
7615       if (FunctionTemplate)
7616         FunctionTemplate->setInvalidDecl();
7617     }
7618 
7619     // C++ [dcl.fct.spec]p5:
7620     //   The virtual specifier shall only be used in declarations of
7621     //   nonstatic class member functions that appear within a
7622     //   member-specification of a class declaration; see 10.3.
7623     //
7624     if (isVirtual && !NewFD->isInvalidDecl()) {
7625       if (!isVirtualOkay) {
7626         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7627              diag::err_virtual_non_function);
7628       } else if (!CurContext->isRecord()) {
7629         // 'virtual' was specified outside of the class.
7630         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7631              diag::err_virtual_out_of_class)
7632           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7633       } else if (NewFD->getDescribedFunctionTemplate()) {
7634         // C++ [temp.mem]p3:
7635         //  A member function template shall not be virtual.
7636         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7637              diag::err_virtual_member_function_template)
7638           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7639       } else {
7640         // Okay: Add virtual to the method.
7641         NewFD->setVirtualAsWritten(true);
7642       }
7643 
7644       if (getLangOpts().CPlusPlus14 &&
7645           NewFD->getReturnType()->isUndeducedType())
7646         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7647     }
7648 
7649     if (getLangOpts().CPlusPlus14 &&
7650         (NewFD->isDependentContext() ||
7651          (isFriend && CurContext->isDependentContext())) &&
7652         NewFD->getReturnType()->isUndeducedType()) {
7653       // If the function template is referenced directly (for instance, as a
7654       // member of the current instantiation), pretend it has a dependent type.
7655       // This is not really justified by the standard, but is the only sane
7656       // thing to do.
7657       // FIXME: For a friend function, we have not marked the function as being
7658       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7659       const FunctionProtoType *FPT =
7660           NewFD->getType()->castAs<FunctionProtoType>();
7661       QualType Result =
7662           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7663       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7664                                              FPT->getExtProtoInfo()));
7665     }
7666 
7667     // C++ [dcl.fct.spec]p3:
7668     //  The inline specifier shall not appear on a block scope function
7669     //  declaration.
7670     if (isInline && !NewFD->isInvalidDecl()) {
7671       if (CurContext->isFunctionOrMethod()) {
7672         // 'inline' is not allowed on block scope function declaration.
7673         Diag(D.getDeclSpec().getInlineSpecLoc(),
7674              diag::err_inline_declaration_block_scope) << Name
7675           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7676       }
7677     }
7678 
7679     // C++ [dcl.fct.spec]p6:
7680     //  The explicit specifier shall be used only in the declaration of a
7681     //  constructor or conversion function within its class definition;
7682     //  see 12.3.1 and 12.3.2.
7683     if (isExplicit && !NewFD->isInvalidDecl()) {
7684       if (!CurContext->isRecord()) {
7685         // 'explicit' was specified outside of the class.
7686         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7687              diag::err_explicit_out_of_class)
7688           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7689       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7690                  !isa<CXXConversionDecl>(NewFD)) {
7691         // 'explicit' was specified on a function that wasn't a constructor
7692         // or conversion function.
7693         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7694              diag::err_explicit_non_ctor_or_conv_function)
7695           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7696       }
7697     }
7698 
7699     if (isConstexpr) {
7700       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7701       // are implicitly inline.
7702       NewFD->setImplicitlyInline();
7703 
7704       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7705       // be either constructors or to return a literal type. Therefore,
7706       // destructors cannot be declared constexpr.
7707       if (isa<CXXDestructorDecl>(NewFD))
7708         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7709     }
7710 
7711     if (isConcept) {
7712       // This is a function concept.
7713       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
7714         FTD->setConcept();
7715 
7716       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7717       // applied only to the definition of a function template [...]
7718       if (!D.isFunctionDefinition()) {
7719         Diag(D.getDeclSpec().getConceptSpecLoc(),
7720              diag::err_function_concept_not_defined);
7721         NewFD->setInvalidDecl();
7722       }
7723 
7724       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7725       // have no exception-specification and is treated as if it were specified
7726       // with noexcept(true) (15.4). [...]
7727       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7728         if (FPT->hasExceptionSpec()) {
7729           SourceRange Range;
7730           if (D.isFunctionDeclarator())
7731             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7732           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7733               << FixItHint::CreateRemoval(Range);
7734           NewFD->setInvalidDecl();
7735         } else {
7736           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7737         }
7738 
7739         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7740         // following restrictions:
7741         // - The declared return type shall have the type bool.
7742         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
7743           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
7744           NewFD->setInvalidDecl();
7745         }
7746 
7747         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7748         // following restrictions:
7749         // - The declaration's parameter list shall be equivalent to an empty
7750         //   parameter list.
7751         if (FPT->getNumParams() > 0 || FPT->isVariadic())
7752           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7753       }
7754 
7755       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7756       // implicity defined to be a constexpr declaration (implicitly inline)
7757       NewFD->setImplicitlyInline();
7758 
7759       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7760       // be declared with the thread_local, inline, friend, or constexpr
7761       // specifiers, [...]
7762       if (isInline) {
7763         Diag(D.getDeclSpec().getInlineSpecLoc(),
7764              diag::err_concept_decl_invalid_specifiers)
7765             << 1 << 1;
7766         NewFD->setInvalidDecl(true);
7767       }
7768 
7769       if (isFriend) {
7770         Diag(D.getDeclSpec().getFriendSpecLoc(),
7771              diag::err_concept_decl_invalid_specifiers)
7772             << 1 << 2;
7773         NewFD->setInvalidDecl(true);
7774       }
7775 
7776       if (isConstexpr) {
7777         Diag(D.getDeclSpec().getConstexprSpecLoc(),
7778              diag::err_concept_decl_invalid_specifiers)
7779             << 1 << 3;
7780         NewFD->setInvalidDecl(true);
7781       }
7782 
7783       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7784       // applied only to the definition of a function template or variable
7785       // template, declared in namespace scope.
7786       if (isFunctionTemplateSpecialization) {
7787         Diag(D.getDeclSpec().getConceptSpecLoc(),
7788              diag::err_concept_specified_specialization) << 1;
7789       }
7790     }
7791 
7792     // If __module_private__ was specified, mark the function accordingly.
7793     if (D.getDeclSpec().isModulePrivateSpecified()) {
7794       if (isFunctionTemplateSpecialization) {
7795         SourceLocation ModulePrivateLoc
7796           = D.getDeclSpec().getModulePrivateSpecLoc();
7797         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7798           << 0
7799           << FixItHint::CreateRemoval(ModulePrivateLoc);
7800       } else {
7801         NewFD->setModulePrivate();
7802         if (FunctionTemplate)
7803           FunctionTemplate->setModulePrivate();
7804       }
7805     }
7806 
7807     if (isFriend) {
7808       if (FunctionTemplate) {
7809         FunctionTemplate->setObjectOfFriendDecl();
7810         FunctionTemplate->setAccess(AS_public);
7811       }
7812       NewFD->setObjectOfFriendDecl();
7813       NewFD->setAccess(AS_public);
7814     }
7815 
7816     // If a function is defined as defaulted or deleted, mark it as such now.
7817     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7818     // definition kind to FDK_Definition.
7819     switch (D.getFunctionDefinitionKind()) {
7820       case FDK_Declaration:
7821       case FDK_Definition:
7822         break;
7823 
7824       case FDK_Defaulted:
7825         NewFD->setDefaulted();
7826         break;
7827 
7828       case FDK_Deleted:
7829         NewFD->setDeletedAsWritten();
7830         break;
7831     }
7832 
7833     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7834         D.isFunctionDefinition()) {
7835       // C++ [class.mfct]p2:
7836       //   A member function may be defined (8.4) in its class definition, in
7837       //   which case it is an inline member function (7.1.2)
7838       NewFD->setImplicitlyInline();
7839     }
7840 
7841     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7842         !CurContext->isRecord()) {
7843       // C++ [class.static]p1:
7844       //   A data or function member of a class may be declared static
7845       //   in a class definition, in which case it is a static member of
7846       //   the class.
7847 
7848       // Complain about the 'static' specifier if it's on an out-of-line
7849       // member function definition.
7850       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7851            diag::err_static_out_of_line)
7852         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7853     }
7854 
7855     // C++11 [except.spec]p15:
7856     //   A deallocation function with no exception-specification is treated
7857     //   as if it were specified with noexcept(true).
7858     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7859     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7860          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7861         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7862       NewFD->setType(Context.getFunctionType(
7863           FPT->getReturnType(), FPT->getParamTypes(),
7864           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7865   }
7866 
7867   // Filter out previous declarations that don't match the scope.
7868   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7869                        D.getCXXScopeSpec().isNotEmpty() ||
7870                        isExplicitSpecialization ||
7871                        isFunctionTemplateSpecialization);
7872 
7873   // Handle GNU asm-label extension (encoded as an attribute).
7874   if (Expr *E = (Expr*) D.getAsmLabel()) {
7875     // The parser guarantees this is a string.
7876     StringLiteral *SE = cast<StringLiteral>(E);
7877     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7878                                                 SE->getString(), 0));
7879   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7880     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7881       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7882     if (I != ExtnameUndeclaredIdentifiers.end()) {
7883       if (isDeclExternC(NewFD)) {
7884         NewFD->addAttr(I->second);
7885         ExtnameUndeclaredIdentifiers.erase(I);
7886       } else
7887         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
7888             << /*Variable*/0 << NewFD;
7889     }
7890   }
7891 
7892   // Copy the parameter declarations from the declarator D to the function
7893   // declaration NewFD, if they are available.  First scavenge them into Params.
7894   SmallVector<ParmVarDecl*, 16> Params;
7895   if (D.isFunctionDeclarator()) {
7896     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7897 
7898     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7899     // function that takes no arguments, not a function that takes a
7900     // single void argument.
7901     // We let through "const void" here because Sema::GetTypeForDeclarator
7902     // already checks for that case.
7903     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7904       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7905         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7906         assert(Param->getDeclContext() != NewFD && "Was set before ?");
7907         Param->setDeclContext(NewFD);
7908         Params.push_back(Param);
7909 
7910         if (Param->isInvalidDecl())
7911           NewFD->setInvalidDecl();
7912       }
7913     }
7914   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7915     // When we're declaring a function with a typedef, typeof, etc as in the
7916     // following example, we'll need to synthesize (unnamed)
7917     // parameters for use in the declaration.
7918     //
7919     // @code
7920     // typedef void fn(int);
7921     // fn f;
7922     // @endcode
7923 
7924     // Synthesize a parameter for each argument type.
7925     for (const auto &AI : FT->param_types()) {
7926       ParmVarDecl *Param =
7927           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7928       Param->setScopeInfo(0, Params.size());
7929       Params.push_back(Param);
7930     }
7931   } else {
7932     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7933            "Should not need args for typedef of non-prototype fn");
7934   }
7935 
7936   // Finally, we know we have the right number of parameters, install them.
7937   NewFD->setParams(Params);
7938 
7939   // Find all anonymous symbols defined during the declaration of this function
7940   // and add to NewFD. This lets us track decls such 'enum Y' in:
7941   //
7942   //   void f(enum Y {AA} x) {}
7943   //
7944   // which would otherwise incorrectly end up in the translation unit scope.
7945   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7946   DeclsInPrototypeScope.clear();
7947 
7948   if (D.getDeclSpec().isNoreturnSpecified())
7949     NewFD->addAttr(
7950         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7951                                        Context, 0));
7952 
7953   // Functions returning a variably modified type violate C99 6.7.5.2p2
7954   // because all functions have linkage.
7955   if (!NewFD->isInvalidDecl() &&
7956       NewFD->getReturnType()->isVariablyModifiedType()) {
7957     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7958     NewFD->setInvalidDecl();
7959   }
7960 
7961   // Apply an implicit SectionAttr if #pragma code_seg is active.
7962   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
7963       !NewFD->hasAttr<SectionAttr>()) {
7964     NewFD->addAttr(
7965         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7966                                     CodeSegStack.CurrentValue->getString(),
7967                                     CodeSegStack.CurrentPragmaLocation));
7968     if (UnifySection(CodeSegStack.CurrentValue->getString(),
7969                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
7970                          ASTContext::PSF_Read,
7971                      NewFD))
7972       NewFD->dropAttr<SectionAttr>();
7973   }
7974 
7975   // Handle attributes.
7976   ProcessDeclAttributes(S, NewFD, D);
7977 
7978   if (getLangOpts().OpenCL) {
7979     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7980     // type declaration will generate a compilation error.
7981     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
7982     if (AddressSpace == LangAS::opencl_local ||
7983         AddressSpace == LangAS::opencl_global ||
7984         AddressSpace == LangAS::opencl_constant) {
7985       Diag(NewFD->getLocation(),
7986            diag::err_opencl_return_value_with_address_space);
7987       NewFD->setInvalidDecl();
7988     }
7989   }
7990 
7991   if (!getLangOpts().CPlusPlus) {
7992     // Perform semantic checking on the function declaration.
7993     bool isExplicitSpecialization=false;
7994     if (!NewFD->isInvalidDecl() && NewFD->isMain())
7995       CheckMain(NewFD, D.getDeclSpec());
7996 
7997     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7998       CheckMSVCRTEntryPoint(NewFD);
7999 
8000     if (!NewFD->isInvalidDecl())
8001       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8002                                                   isExplicitSpecialization));
8003     else if (!Previous.empty())
8004       // Recover gracefully from an invalid redeclaration.
8005       D.setRedeclaration(true);
8006     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8007             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8008            "previous declaration set still overloaded");
8009 
8010     // Diagnose no-prototype function declarations with calling conventions that
8011     // don't support variadic calls. Only do this in C and do it after merging
8012     // possibly prototyped redeclarations.
8013     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8014     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8015       CallingConv CC = FT->getExtInfo().getCC();
8016       if (!supportsVariadicCall(CC)) {
8017         // Windows system headers sometimes accidentally use stdcall without
8018         // (void) parameters, so we relax this to a warning.
8019         int DiagID =
8020             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8021         Diag(NewFD->getLocation(), DiagID)
8022             << FunctionType::getNameForCallConv(CC);
8023       }
8024     }
8025   } else {
8026     // C++11 [replacement.functions]p3:
8027     //  The program's definitions shall not be specified as inline.
8028     //
8029     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8030     //
8031     // Suppress the diagnostic if the function is __attribute__((used)), since
8032     // that forces an external definition to be emitted.
8033     if (D.getDeclSpec().isInlineSpecified() &&
8034         NewFD->isReplaceableGlobalAllocationFunction() &&
8035         !NewFD->hasAttr<UsedAttr>())
8036       Diag(D.getDeclSpec().getInlineSpecLoc(),
8037            diag::ext_operator_new_delete_declared_inline)
8038         << NewFD->getDeclName();
8039 
8040     // If the declarator is a template-id, translate the parser's template
8041     // argument list into our AST format.
8042     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8043       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8044       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8045       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8046       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8047                                          TemplateId->NumArgs);
8048       translateTemplateArguments(TemplateArgsPtr,
8049                                  TemplateArgs);
8050 
8051       HasExplicitTemplateArgs = true;
8052 
8053       if (NewFD->isInvalidDecl()) {
8054         HasExplicitTemplateArgs = false;
8055       } else if (FunctionTemplate) {
8056         // Function template with explicit template arguments.
8057         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8058           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8059 
8060         HasExplicitTemplateArgs = false;
8061       } else {
8062         assert((isFunctionTemplateSpecialization ||
8063                 D.getDeclSpec().isFriendSpecified()) &&
8064                "should have a 'template<>' for this decl");
8065         // "friend void foo<>(int);" is an implicit specialization decl.
8066         isFunctionTemplateSpecialization = true;
8067       }
8068     } else if (isFriend && isFunctionTemplateSpecialization) {
8069       // This combination is only possible in a recovery case;  the user
8070       // wrote something like:
8071       //   template <> friend void foo(int);
8072       // which we're recovering from as if the user had written:
8073       //   friend void foo<>(int);
8074       // Go ahead and fake up a template id.
8075       HasExplicitTemplateArgs = true;
8076       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8077       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8078     }
8079 
8080     // If it's a friend (and only if it's a friend), it's possible
8081     // that either the specialized function type or the specialized
8082     // template is dependent, and therefore matching will fail.  In
8083     // this case, don't check the specialization yet.
8084     bool InstantiationDependent = false;
8085     if (isFunctionTemplateSpecialization && isFriend &&
8086         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8087          TemplateSpecializationType::anyDependentTemplateArguments(
8088             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
8089             InstantiationDependent))) {
8090       assert(HasExplicitTemplateArgs &&
8091              "friend function specialization without template args");
8092       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8093                                                        Previous))
8094         NewFD->setInvalidDecl();
8095     } else if (isFunctionTemplateSpecialization) {
8096       if (CurContext->isDependentContext() && CurContext->isRecord()
8097           && !isFriend) {
8098         isDependentClassScopeExplicitSpecialization = true;
8099         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8100           diag::ext_function_specialization_in_class :
8101           diag::err_function_specialization_in_class)
8102           << NewFD->getDeclName();
8103       } else if (CheckFunctionTemplateSpecialization(NewFD,
8104                                   (HasExplicitTemplateArgs ? &TemplateArgs
8105                                                            : nullptr),
8106                                                      Previous))
8107         NewFD->setInvalidDecl();
8108 
8109       // C++ [dcl.stc]p1:
8110       //   A storage-class-specifier shall not be specified in an explicit
8111       //   specialization (14.7.3)
8112       FunctionTemplateSpecializationInfo *Info =
8113           NewFD->getTemplateSpecializationInfo();
8114       if (Info && SC != SC_None) {
8115         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8116           Diag(NewFD->getLocation(),
8117                diag::err_explicit_specialization_inconsistent_storage_class)
8118             << SC
8119             << FixItHint::CreateRemoval(
8120                                       D.getDeclSpec().getStorageClassSpecLoc());
8121 
8122         else
8123           Diag(NewFD->getLocation(),
8124                diag::ext_explicit_specialization_storage_class)
8125             << FixItHint::CreateRemoval(
8126                                       D.getDeclSpec().getStorageClassSpecLoc());
8127       }
8128     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8129       if (CheckMemberSpecialization(NewFD, Previous))
8130           NewFD->setInvalidDecl();
8131     }
8132 
8133     // Perform semantic checking on the function declaration.
8134     if (!isDependentClassScopeExplicitSpecialization) {
8135       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8136         CheckMain(NewFD, D.getDeclSpec());
8137 
8138       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8139         CheckMSVCRTEntryPoint(NewFD);
8140 
8141       if (!NewFD->isInvalidDecl())
8142         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8143                                                     isExplicitSpecialization));
8144       else if (!Previous.empty())
8145         // Recover gracefully from an invalid redeclaration.
8146         D.setRedeclaration(true);
8147     }
8148 
8149     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8150             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8151            "previous declaration set still overloaded");
8152 
8153     NamedDecl *PrincipalDecl = (FunctionTemplate
8154                                 ? cast<NamedDecl>(FunctionTemplate)
8155                                 : NewFD);
8156 
8157     if (isFriend && D.isRedeclaration()) {
8158       AccessSpecifier Access = AS_public;
8159       if (!NewFD->isInvalidDecl())
8160         Access = NewFD->getPreviousDecl()->getAccess();
8161 
8162       NewFD->setAccess(Access);
8163       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8164     }
8165 
8166     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8167         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8168       PrincipalDecl->setNonMemberOperator();
8169 
8170     // If we have a function template, check the template parameter
8171     // list. This will check and merge default template arguments.
8172     if (FunctionTemplate) {
8173       FunctionTemplateDecl *PrevTemplate =
8174                                      FunctionTemplate->getPreviousDecl();
8175       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8176                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8177                                     : nullptr,
8178                             D.getDeclSpec().isFriendSpecified()
8179                               ? (D.isFunctionDefinition()
8180                                    ? TPC_FriendFunctionTemplateDefinition
8181                                    : TPC_FriendFunctionTemplate)
8182                               : (D.getCXXScopeSpec().isSet() &&
8183                                  DC && DC->isRecord() &&
8184                                  DC->isDependentContext())
8185                                   ? TPC_ClassTemplateMember
8186                                   : TPC_FunctionTemplate);
8187     }
8188 
8189     if (NewFD->isInvalidDecl()) {
8190       // Ignore all the rest of this.
8191     } else if (!D.isRedeclaration()) {
8192       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8193                                        AddToScope };
8194       // Fake up an access specifier if it's supposed to be a class member.
8195       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8196         NewFD->setAccess(AS_public);
8197 
8198       // Qualified decls generally require a previous declaration.
8199       if (D.getCXXScopeSpec().isSet()) {
8200         // ...with the major exception of templated-scope or
8201         // dependent-scope friend declarations.
8202 
8203         // TODO: we currently also suppress this check in dependent
8204         // contexts because (1) the parameter depth will be off when
8205         // matching friend templates and (2) we might actually be
8206         // selecting a friend based on a dependent factor.  But there
8207         // are situations where these conditions don't apply and we
8208         // can actually do this check immediately.
8209         if (isFriend &&
8210             (TemplateParamLists.size() ||
8211              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8212              CurContext->isDependentContext())) {
8213           // ignore these
8214         } else {
8215           // The user tried to provide an out-of-line definition for a
8216           // function that is a member of a class or namespace, but there
8217           // was no such member function declared (C++ [class.mfct]p2,
8218           // C++ [namespace.memdef]p2). For example:
8219           //
8220           // class X {
8221           //   void f() const;
8222           // };
8223           //
8224           // void X::f() { } // ill-formed
8225           //
8226           // Complain about this problem, and attempt to suggest close
8227           // matches (e.g., those that differ only in cv-qualifiers and
8228           // whether the parameter types are references).
8229 
8230           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8231                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8232             AddToScope = ExtraArgs.AddToScope;
8233             return Result;
8234           }
8235         }
8236 
8237         // Unqualified local friend declarations are required to resolve
8238         // to something.
8239       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8240         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8241                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8242           AddToScope = ExtraArgs.AddToScope;
8243           return Result;
8244         }
8245       }
8246     } else if (!D.isFunctionDefinition() &&
8247                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8248                !isFriend && !isFunctionTemplateSpecialization &&
8249                !isExplicitSpecialization) {
8250       // An out-of-line member function declaration must also be a
8251       // definition (C++ [class.mfct]p2).
8252       // Note that this is not the case for explicit specializations of
8253       // function templates or member functions of class templates, per
8254       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8255       // extension for compatibility with old SWIG code which likes to
8256       // generate them.
8257       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8258         << D.getCXXScopeSpec().getRange();
8259     }
8260   }
8261 
8262   ProcessPragmaWeak(S, NewFD);
8263   checkAttributesAfterMerging(*this, *NewFD);
8264 
8265   AddKnownFunctionAttributes(NewFD);
8266 
8267   if (NewFD->hasAttr<OverloadableAttr>() &&
8268       !NewFD->getType()->getAs<FunctionProtoType>()) {
8269     Diag(NewFD->getLocation(),
8270          diag::err_attribute_overloadable_no_prototype)
8271       << NewFD;
8272 
8273     // Turn this into a variadic function with no parameters.
8274     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8275     FunctionProtoType::ExtProtoInfo EPI(
8276         Context.getDefaultCallingConvention(true, false));
8277     EPI.Variadic = true;
8278     EPI.ExtInfo = FT->getExtInfo();
8279 
8280     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8281     NewFD->setType(R);
8282   }
8283 
8284   // If there's a #pragma GCC visibility in scope, and this isn't a class
8285   // member, set the visibility of this function.
8286   if (!DC->isRecord() && NewFD->isExternallyVisible())
8287     AddPushedVisibilityAttribute(NewFD);
8288 
8289   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8290   // marking the function.
8291   AddCFAuditedAttribute(NewFD);
8292 
8293   // If this is a function definition, check if we have to apply optnone due to
8294   // a pragma.
8295   if(D.isFunctionDefinition())
8296     AddRangeBasedOptnone(NewFD);
8297 
8298   // If this is the first declaration of an extern C variable, update
8299   // the map of such variables.
8300   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8301       isIncompleteDeclExternC(*this, NewFD))
8302     RegisterLocallyScopedExternCDecl(NewFD, S);
8303 
8304   // Set this FunctionDecl's range up to the right paren.
8305   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8306 
8307   if (D.isRedeclaration() && !Previous.empty()) {
8308     checkDLLAttributeRedeclaration(
8309         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8310         isExplicitSpecialization || isFunctionTemplateSpecialization);
8311   }
8312 
8313   if (getLangOpts().CPlusPlus) {
8314     if (FunctionTemplate) {
8315       if (NewFD->isInvalidDecl())
8316         FunctionTemplate->setInvalidDecl();
8317       return FunctionTemplate;
8318     }
8319   }
8320 
8321   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8322     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8323     if ((getLangOpts().OpenCLVersion >= 120)
8324         && (SC == SC_Static)) {
8325       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8326       D.setInvalidType();
8327     }
8328 
8329     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8330     if (!NewFD->getReturnType()->isVoidType()) {
8331       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8332       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8333           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8334                                 : FixItHint());
8335       D.setInvalidType();
8336     }
8337 
8338     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8339     for (auto Param : NewFD->params())
8340       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8341   }
8342   for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
8343        PE = NewFD->param_end(); PI != PE; ++PI) {
8344     ParmVarDecl *Param = *PI;
8345     QualType PT = Param->getType();
8346 
8347     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8348     // types.
8349     if (getLangOpts().OpenCLVersion >= 200) {
8350       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8351         QualType ElemTy = PipeTy->getElementType();
8352           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8353             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8354             D.setInvalidType();
8355           }
8356       }
8357     }
8358   }
8359 
8360   MarkUnusedFileScopedDecl(NewFD);
8361 
8362   if (getLangOpts().CUDA) {
8363     IdentifierInfo *II = NewFD->getIdentifier();
8364     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8365         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8366       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8367         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8368 
8369       Context.setcudaConfigureCallDecl(NewFD);
8370     }
8371 
8372     // Variadic functions, other than a *declaration* of printf, are not allowed
8373     // in device-side CUDA code, unless someone passed
8374     // -fcuda-allow-variadic-functions.
8375     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8376         (NewFD->hasAttr<CUDADeviceAttr>() ||
8377          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8378         !(II && II->isStr("printf") && NewFD->isExternC() &&
8379           !D.isFunctionDefinition())) {
8380       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8381     }
8382   }
8383 
8384   // Here we have an function template explicit specialization at class scope.
8385   // The actually specialization will be postponed to template instatiation
8386   // time via the ClassScopeFunctionSpecializationDecl node.
8387   if (isDependentClassScopeExplicitSpecialization) {
8388     ClassScopeFunctionSpecializationDecl *NewSpec =
8389                          ClassScopeFunctionSpecializationDecl::Create(
8390                                 Context, CurContext, SourceLocation(),
8391                                 cast<CXXMethodDecl>(NewFD),
8392                                 HasExplicitTemplateArgs, TemplateArgs);
8393     CurContext->addDecl(NewSpec);
8394     AddToScope = false;
8395   }
8396 
8397   return NewFD;
8398 }
8399 
8400 /// \brief Perform semantic checking of a new function declaration.
8401 ///
8402 /// Performs semantic analysis of the new function declaration
8403 /// NewFD. This routine performs all semantic checking that does not
8404 /// require the actual declarator involved in the declaration, and is
8405 /// used both for the declaration of functions as they are parsed
8406 /// (called via ActOnDeclarator) and for the declaration of functions
8407 /// that have been instantiated via C++ template instantiation (called
8408 /// via InstantiateDecl).
8409 ///
8410 /// \param IsExplicitSpecialization whether this new function declaration is
8411 /// an explicit specialization of the previous declaration.
8412 ///
8413 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8414 ///
8415 /// \returns true if the function declaration is a redeclaration.
8416 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8417                                     LookupResult &Previous,
8418                                     bool IsExplicitSpecialization) {
8419   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8420          "Variably modified return types are not handled here");
8421 
8422   // Determine whether the type of this function should be merged with
8423   // a previous visible declaration. This never happens for functions in C++,
8424   // and always happens in C if the previous declaration was visible.
8425   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8426                                !Previous.isShadowed();
8427 
8428   bool Redeclaration = false;
8429   NamedDecl *OldDecl = nullptr;
8430 
8431   // Merge or overload the declaration with an existing declaration of
8432   // the same name, if appropriate.
8433   if (!Previous.empty()) {
8434     // Determine whether NewFD is an overload of PrevDecl or
8435     // a declaration that requires merging. If it's an overload,
8436     // there's no more work to do here; we'll just add the new
8437     // function to the scope.
8438     if (!AllowOverloadingOfFunction(Previous, Context)) {
8439       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8440       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8441         Redeclaration = true;
8442         OldDecl = Candidate;
8443       }
8444     } else {
8445       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8446                             /*NewIsUsingDecl*/ false)) {
8447       case Ovl_Match:
8448         Redeclaration = true;
8449         break;
8450 
8451       case Ovl_NonFunction:
8452         Redeclaration = true;
8453         break;
8454 
8455       case Ovl_Overload:
8456         Redeclaration = false;
8457         break;
8458       }
8459 
8460       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8461         // If a function name is overloadable in C, then every function
8462         // with that name must be marked "overloadable".
8463         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8464           << Redeclaration << NewFD;
8465         NamedDecl *OverloadedDecl = nullptr;
8466         if (Redeclaration)
8467           OverloadedDecl = OldDecl;
8468         else if (!Previous.empty())
8469           OverloadedDecl = Previous.getRepresentativeDecl();
8470         if (OverloadedDecl)
8471           Diag(OverloadedDecl->getLocation(),
8472                diag::note_attribute_overloadable_prev_overload);
8473         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8474       }
8475     }
8476   }
8477 
8478   // Check for a previous extern "C" declaration with this name.
8479   if (!Redeclaration &&
8480       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8481     if (!Previous.empty()) {
8482       // This is an extern "C" declaration with the same name as a previous
8483       // declaration, and thus redeclares that entity...
8484       Redeclaration = true;
8485       OldDecl = Previous.getFoundDecl();
8486       MergeTypeWithPrevious = false;
8487 
8488       // ... except in the presence of __attribute__((overloadable)).
8489       if (OldDecl->hasAttr<OverloadableAttr>()) {
8490         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8491           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8492             << Redeclaration << NewFD;
8493           Diag(Previous.getFoundDecl()->getLocation(),
8494                diag::note_attribute_overloadable_prev_overload);
8495           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8496         }
8497         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8498           Redeclaration = false;
8499           OldDecl = nullptr;
8500         }
8501       }
8502     }
8503   }
8504 
8505   // C++11 [dcl.constexpr]p8:
8506   //   A constexpr specifier for a non-static member function that is not
8507   //   a constructor declares that member function to be const.
8508   //
8509   // This needs to be delayed until we know whether this is an out-of-line
8510   // definition of a static member function.
8511   //
8512   // This rule is not present in C++1y, so we produce a backwards
8513   // compatibility warning whenever it happens in C++11.
8514   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8515   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8516       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8517       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8518     CXXMethodDecl *OldMD = nullptr;
8519     if (OldDecl)
8520       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8521     if (!OldMD || !OldMD->isStatic()) {
8522       const FunctionProtoType *FPT =
8523         MD->getType()->castAs<FunctionProtoType>();
8524       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8525       EPI.TypeQuals |= Qualifiers::Const;
8526       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8527                                           FPT->getParamTypes(), EPI));
8528 
8529       // Warn that we did this, if we're not performing template instantiation.
8530       // In that case, we'll have warned already when the template was defined.
8531       if (ActiveTemplateInstantiations.empty()) {
8532         SourceLocation AddConstLoc;
8533         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8534                 .IgnoreParens().getAs<FunctionTypeLoc>())
8535           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8536 
8537         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8538           << FixItHint::CreateInsertion(AddConstLoc, " const");
8539       }
8540     }
8541   }
8542 
8543   if (Redeclaration) {
8544     // NewFD and OldDecl represent declarations that need to be
8545     // merged.
8546     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8547       NewFD->setInvalidDecl();
8548       return Redeclaration;
8549     }
8550 
8551     Previous.clear();
8552     Previous.addDecl(OldDecl);
8553 
8554     if (FunctionTemplateDecl *OldTemplateDecl
8555                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8556       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8557       FunctionTemplateDecl *NewTemplateDecl
8558         = NewFD->getDescribedFunctionTemplate();
8559       assert(NewTemplateDecl && "Template/non-template mismatch");
8560       if (CXXMethodDecl *Method
8561             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8562         Method->setAccess(OldTemplateDecl->getAccess());
8563         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8564       }
8565 
8566       // If this is an explicit specialization of a member that is a function
8567       // template, mark it as a member specialization.
8568       if (IsExplicitSpecialization &&
8569           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8570         NewTemplateDecl->setMemberSpecialization();
8571         assert(OldTemplateDecl->isMemberSpecialization());
8572       }
8573 
8574     } else {
8575       // This needs to happen first so that 'inline' propagates.
8576       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8577 
8578       if (isa<CXXMethodDecl>(NewFD))
8579         NewFD->setAccess(OldDecl->getAccess());
8580     }
8581   }
8582 
8583   // Semantic checking for this function declaration (in isolation).
8584 
8585   if (getLangOpts().CPlusPlus) {
8586     // C++-specific checks.
8587     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8588       CheckConstructor(Constructor);
8589     } else if (CXXDestructorDecl *Destructor =
8590                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8591       CXXRecordDecl *Record = Destructor->getParent();
8592       QualType ClassType = Context.getTypeDeclType(Record);
8593 
8594       // FIXME: Shouldn't we be able to perform this check even when the class
8595       // type is dependent? Both gcc and edg can handle that.
8596       if (!ClassType->isDependentType()) {
8597         DeclarationName Name
8598           = Context.DeclarationNames.getCXXDestructorName(
8599                                         Context.getCanonicalType(ClassType));
8600         if (NewFD->getDeclName() != Name) {
8601           Diag(NewFD->getLocation(), diag::err_destructor_name);
8602           NewFD->setInvalidDecl();
8603           return Redeclaration;
8604         }
8605       }
8606     } else if (CXXConversionDecl *Conversion
8607                = dyn_cast<CXXConversionDecl>(NewFD)) {
8608       ActOnConversionDeclarator(Conversion);
8609     }
8610 
8611     // Find any virtual functions that this function overrides.
8612     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8613       if (!Method->isFunctionTemplateSpecialization() &&
8614           !Method->getDescribedFunctionTemplate() &&
8615           Method->isCanonicalDecl()) {
8616         if (AddOverriddenMethods(Method->getParent(), Method)) {
8617           // If the function was marked as "static", we have a problem.
8618           if (NewFD->getStorageClass() == SC_Static) {
8619             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8620           }
8621         }
8622       }
8623 
8624       if (Method->isStatic())
8625         checkThisInStaticMemberFunctionType(Method);
8626     }
8627 
8628     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8629     if (NewFD->isOverloadedOperator() &&
8630         CheckOverloadedOperatorDeclaration(NewFD)) {
8631       NewFD->setInvalidDecl();
8632       return Redeclaration;
8633     }
8634 
8635     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8636     if (NewFD->getLiteralIdentifier() &&
8637         CheckLiteralOperatorDeclaration(NewFD)) {
8638       NewFD->setInvalidDecl();
8639       return Redeclaration;
8640     }
8641 
8642     // In C++, check default arguments now that we have merged decls. Unless
8643     // the lexical context is the class, because in this case this is done
8644     // during delayed parsing anyway.
8645     if (!CurContext->isRecord())
8646       CheckCXXDefaultArguments(NewFD);
8647 
8648     // If this function declares a builtin function, check the type of this
8649     // declaration against the expected type for the builtin.
8650     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8651       ASTContext::GetBuiltinTypeError Error;
8652       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8653       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8654       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8655         // The type of this function differs from the type of the builtin,
8656         // so forget about the builtin entirely.
8657         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8658       }
8659     }
8660 
8661     // If this function is declared as being extern "C", then check to see if
8662     // the function returns a UDT (class, struct, or union type) that is not C
8663     // compatible, and if it does, warn the user.
8664     // But, issue any diagnostic on the first declaration only.
8665     if (Previous.empty() && NewFD->isExternC()) {
8666       QualType R = NewFD->getReturnType();
8667       if (R->isIncompleteType() && !R->isVoidType())
8668         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8669             << NewFD << R;
8670       else if (!R.isPODType(Context) && !R->isVoidType() &&
8671                !R->isObjCObjectPointerType())
8672         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8673     }
8674   }
8675   return Redeclaration;
8676 }
8677 
8678 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8679   // C++11 [basic.start.main]p3:
8680   //   A program that [...] declares main to be inline, static or
8681   //   constexpr is ill-formed.
8682   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8683   //   appear in a declaration of main.
8684   // static main is not an error under C99, but we should warn about it.
8685   // We accept _Noreturn main as an extension.
8686   if (FD->getStorageClass() == SC_Static)
8687     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8688          ? diag::err_static_main : diag::warn_static_main)
8689       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8690   if (FD->isInlineSpecified())
8691     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8692       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8693   if (DS.isNoreturnSpecified()) {
8694     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8695     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8696     Diag(NoreturnLoc, diag::ext_noreturn_main);
8697     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8698       << FixItHint::CreateRemoval(NoreturnRange);
8699   }
8700   if (FD->isConstexpr()) {
8701     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8702       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8703     FD->setConstexpr(false);
8704   }
8705 
8706   if (getLangOpts().OpenCL) {
8707     Diag(FD->getLocation(), diag::err_opencl_no_main)
8708         << FD->hasAttr<OpenCLKernelAttr>();
8709     FD->setInvalidDecl();
8710     return;
8711   }
8712 
8713   QualType T = FD->getType();
8714   assert(T->isFunctionType() && "function decl is not of function type");
8715   const FunctionType* FT = T->castAs<FunctionType>();
8716 
8717   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8718     // In C with GNU extensions we allow main() to have non-integer return
8719     // type, but we should warn about the extension, and we disable the
8720     // implicit-return-zero rule.
8721 
8722     // GCC in C mode accepts qualified 'int'.
8723     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8724       FD->setHasImplicitReturnZero(true);
8725     else {
8726       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8727       SourceRange RTRange = FD->getReturnTypeSourceRange();
8728       if (RTRange.isValid())
8729         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8730             << FixItHint::CreateReplacement(RTRange, "int");
8731     }
8732   } else {
8733     // In C and C++, main magically returns 0 if you fall off the end;
8734     // set the flag which tells us that.
8735     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8736 
8737     // All the standards say that main() should return 'int'.
8738     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8739       FD->setHasImplicitReturnZero(true);
8740     else {
8741       // Otherwise, this is just a flat-out error.
8742       SourceRange RTRange = FD->getReturnTypeSourceRange();
8743       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8744           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8745                                 : FixItHint());
8746       FD->setInvalidDecl(true);
8747     }
8748   }
8749 
8750   // Treat protoless main() as nullary.
8751   if (isa<FunctionNoProtoType>(FT)) return;
8752 
8753   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8754   unsigned nparams = FTP->getNumParams();
8755   assert(FD->getNumParams() == nparams);
8756 
8757   bool HasExtraParameters = (nparams > 3);
8758 
8759   if (FTP->isVariadic()) {
8760     Diag(FD->getLocation(), diag::ext_variadic_main);
8761     // FIXME: if we had information about the location of the ellipsis, we
8762     // could add a FixIt hint to remove it as a parameter.
8763   }
8764 
8765   // Darwin passes an undocumented fourth argument of type char**.  If
8766   // other platforms start sprouting these, the logic below will start
8767   // getting shifty.
8768   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8769     HasExtraParameters = false;
8770 
8771   if (HasExtraParameters) {
8772     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8773     FD->setInvalidDecl(true);
8774     nparams = 3;
8775   }
8776 
8777   // FIXME: a lot of the following diagnostics would be improved
8778   // if we had some location information about types.
8779 
8780   QualType CharPP =
8781     Context.getPointerType(Context.getPointerType(Context.CharTy));
8782   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8783 
8784   for (unsigned i = 0; i < nparams; ++i) {
8785     QualType AT = FTP->getParamType(i);
8786 
8787     bool mismatch = true;
8788 
8789     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8790       mismatch = false;
8791     else if (Expected[i] == CharPP) {
8792       // As an extension, the following forms are okay:
8793       //   char const **
8794       //   char const * const *
8795       //   char * const *
8796 
8797       QualifierCollector qs;
8798       const PointerType* PT;
8799       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8800           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8801           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8802                               Context.CharTy)) {
8803         qs.removeConst();
8804         mismatch = !qs.empty();
8805       }
8806     }
8807 
8808     if (mismatch) {
8809       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8810       // TODO: suggest replacing given type with expected type
8811       FD->setInvalidDecl(true);
8812     }
8813   }
8814 
8815   if (nparams == 1 && !FD->isInvalidDecl()) {
8816     Diag(FD->getLocation(), diag::warn_main_one_arg);
8817   }
8818 
8819   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8820     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8821     FD->setInvalidDecl();
8822   }
8823 }
8824 
8825 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8826   QualType T = FD->getType();
8827   assert(T->isFunctionType() && "function decl is not of function type");
8828   const FunctionType *FT = T->castAs<FunctionType>();
8829 
8830   // Set an implicit return of 'zero' if the function can return some integral,
8831   // enumeration, pointer or nullptr type.
8832   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8833       FT->getReturnType()->isAnyPointerType() ||
8834       FT->getReturnType()->isNullPtrType())
8835     // DllMain is exempt because a return value of zero means it failed.
8836     if (FD->getName() != "DllMain")
8837       FD->setHasImplicitReturnZero(true);
8838 
8839   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8840     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8841     FD->setInvalidDecl();
8842   }
8843 }
8844 
8845 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8846   // FIXME: Need strict checking.  In C89, we need to check for
8847   // any assignment, increment, decrement, function-calls, or
8848   // commas outside of a sizeof.  In C99, it's the same list,
8849   // except that the aforementioned are allowed in unevaluated
8850   // expressions.  Everything else falls under the
8851   // "may accept other forms of constant expressions" exception.
8852   // (We never end up here for C++, so the constant expression
8853   // rules there don't matter.)
8854   const Expr *Culprit;
8855   if (Init->isConstantInitializer(Context, false, &Culprit))
8856     return false;
8857   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8858     << Culprit->getSourceRange();
8859   return true;
8860 }
8861 
8862 namespace {
8863   // Visits an initialization expression to see if OrigDecl is evaluated in
8864   // its own initialization and throws a warning if it does.
8865   class SelfReferenceChecker
8866       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8867     Sema &S;
8868     Decl *OrigDecl;
8869     bool isRecordType;
8870     bool isPODType;
8871     bool isReferenceType;
8872 
8873     bool isInitList;
8874     llvm::SmallVector<unsigned, 4> InitFieldIndex;
8875 
8876   public:
8877     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8878 
8879     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8880                                                     S(S), OrigDecl(OrigDecl) {
8881       isPODType = false;
8882       isRecordType = false;
8883       isReferenceType = false;
8884       isInitList = false;
8885       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8886         isPODType = VD->getType().isPODType(S.Context);
8887         isRecordType = VD->getType()->isRecordType();
8888         isReferenceType = VD->getType()->isReferenceType();
8889       }
8890     }
8891 
8892     // For most expressions, just call the visitor.  For initializer lists,
8893     // track the index of the field being initialized since fields are
8894     // initialized in order allowing use of previously initialized fields.
8895     void CheckExpr(Expr *E) {
8896       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8897       if (!InitList) {
8898         Visit(E);
8899         return;
8900       }
8901 
8902       // Track and increment the index here.
8903       isInitList = true;
8904       InitFieldIndex.push_back(0);
8905       for (auto Child : InitList->children()) {
8906         CheckExpr(cast<Expr>(Child));
8907         ++InitFieldIndex.back();
8908       }
8909       InitFieldIndex.pop_back();
8910     }
8911 
8912     // Returns true if MemberExpr is checked and no futher checking is needed.
8913     // Returns false if additional checking is required.
8914     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8915       llvm::SmallVector<FieldDecl*, 4> Fields;
8916       Expr *Base = E;
8917       bool ReferenceField = false;
8918 
8919       // Get the field memebers used.
8920       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8921         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8922         if (!FD)
8923           return false;
8924         Fields.push_back(FD);
8925         if (FD->getType()->isReferenceType())
8926           ReferenceField = true;
8927         Base = ME->getBase()->IgnoreParenImpCasts();
8928       }
8929 
8930       // Keep checking only if the base Decl is the same.
8931       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8932       if (!DRE || DRE->getDecl() != OrigDecl)
8933         return false;
8934 
8935       // A reference field can be bound to an unininitialized field.
8936       if (CheckReference && !ReferenceField)
8937         return true;
8938 
8939       // Convert FieldDecls to their index number.
8940       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8941       for (const FieldDecl *I : llvm::reverse(Fields))
8942         UsedFieldIndex.push_back(I->getFieldIndex());
8943 
8944       // See if a warning is needed by checking the first difference in index
8945       // numbers.  If field being used has index less than the field being
8946       // initialized, then the use is safe.
8947       for (auto UsedIter = UsedFieldIndex.begin(),
8948                 UsedEnd = UsedFieldIndex.end(),
8949                 OrigIter = InitFieldIndex.begin(),
8950                 OrigEnd = InitFieldIndex.end();
8951            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8952         if (*UsedIter < *OrigIter)
8953           return true;
8954         if (*UsedIter > *OrigIter)
8955           break;
8956       }
8957 
8958       // TODO: Add a different warning which will print the field names.
8959       HandleDeclRefExpr(DRE);
8960       return true;
8961     }
8962 
8963     // For most expressions, the cast is directly above the DeclRefExpr.
8964     // For conditional operators, the cast can be outside the conditional
8965     // operator if both expressions are DeclRefExpr's.
8966     void HandleValue(Expr *E) {
8967       E = E->IgnoreParens();
8968       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8969         HandleDeclRefExpr(DRE);
8970         return;
8971       }
8972 
8973       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8974         Visit(CO->getCond());
8975         HandleValue(CO->getTrueExpr());
8976         HandleValue(CO->getFalseExpr());
8977         return;
8978       }
8979 
8980       if (BinaryConditionalOperator *BCO =
8981               dyn_cast<BinaryConditionalOperator>(E)) {
8982         Visit(BCO->getCond());
8983         HandleValue(BCO->getFalseExpr());
8984         return;
8985       }
8986 
8987       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8988         HandleValue(OVE->getSourceExpr());
8989         return;
8990       }
8991 
8992       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8993         if (BO->getOpcode() == BO_Comma) {
8994           Visit(BO->getLHS());
8995           HandleValue(BO->getRHS());
8996           return;
8997         }
8998       }
8999 
9000       if (isa<MemberExpr>(E)) {
9001         if (isInitList) {
9002           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9003                                       false /*CheckReference*/))
9004             return;
9005         }
9006 
9007         Expr *Base = E->IgnoreParenImpCasts();
9008         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9009           // Check for static member variables and don't warn on them.
9010           if (!isa<FieldDecl>(ME->getMemberDecl()))
9011             return;
9012           Base = ME->getBase()->IgnoreParenImpCasts();
9013         }
9014         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9015           HandleDeclRefExpr(DRE);
9016         return;
9017       }
9018 
9019       Visit(E);
9020     }
9021 
9022     // Reference types not handled in HandleValue are handled here since all
9023     // uses of references are bad, not just r-value uses.
9024     void VisitDeclRefExpr(DeclRefExpr *E) {
9025       if (isReferenceType)
9026         HandleDeclRefExpr(E);
9027     }
9028 
9029     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9030       if (E->getCastKind() == CK_LValueToRValue) {
9031         HandleValue(E->getSubExpr());
9032         return;
9033       }
9034 
9035       Inherited::VisitImplicitCastExpr(E);
9036     }
9037 
9038     void VisitMemberExpr(MemberExpr *E) {
9039       if (isInitList) {
9040         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9041           return;
9042       }
9043 
9044       // Don't warn on arrays since they can be treated as pointers.
9045       if (E->getType()->canDecayToPointerType()) return;
9046 
9047       // Warn when a non-static method call is followed by non-static member
9048       // field accesses, which is followed by a DeclRefExpr.
9049       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9050       bool Warn = (MD && !MD->isStatic());
9051       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9052       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9053         if (!isa<FieldDecl>(ME->getMemberDecl()))
9054           Warn = false;
9055         Base = ME->getBase()->IgnoreParenImpCasts();
9056       }
9057 
9058       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9059         if (Warn)
9060           HandleDeclRefExpr(DRE);
9061         return;
9062       }
9063 
9064       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9065       // Visit that expression.
9066       Visit(Base);
9067     }
9068 
9069     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9070       Expr *Callee = E->getCallee();
9071 
9072       if (isa<UnresolvedLookupExpr>(Callee))
9073         return Inherited::VisitCXXOperatorCallExpr(E);
9074 
9075       Visit(Callee);
9076       for (auto Arg: E->arguments())
9077         HandleValue(Arg->IgnoreParenImpCasts());
9078     }
9079 
9080     void VisitUnaryOperator(UnaryOperator *E) {
9081       // For POD record types, addresses of its own members are well-defined.
9082       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9083           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9084         if (!isPODType)
9085           HandleValue(E->getSubExpr());
9086         return;
9087       }
9088 
9089       if (E->isIncrementDecrementOp()) {
9090         HandleValue(E->getSubExpr());
9091         return;
9092       }
9093 
9094       Inherited::VisitUnaryOperator(E);
9095     }
9096 
9097     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9098 
9099     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9100       if (E->getConstructor()->isCopyConstructor()) {
9101         Expr *ArgExpr = E->getArg(0);
9102         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9103           if (ILE->getNumInits() == 1)
9104             ArgExpr = ILE->getInit(0);
9105         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9106           if (ICE->getCastKind() == CK_NoOp)
9107             ArgExpr = ICE->getSubExpr();
9108         HandleValue(ArgExpr);
9109         return;
9110       }
9111       Inherited::VisitCXXConstructExpr(E);
9112     }
9113 
9114     void VisitCallExpr(CallExpr *E) {
9115       // Treat std::move as a use.
9116       if (E->getNumArgs() == 1) {
9117         if (FunctionDecl *FD = E->getDirectCallee()) {
9118           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9119               FD->getIdentifier()->isStr("move")) {
9120             HandleValue(E->getArg(0));
9121             return;
9122           }
9123         }
9124       }
9125 
9126       Inherited::VisitCallExpr(E);
9127     }
9128 
9129     void VisitBinaryOperator(BinaryOperator *E) {
9130       if (E->isCompoundAssignmentOp()) {
9131         HandleValue(E->getLHS());
9132         Visit(E->getRHS());
9133         return;
9134       }
9135 
9136       Inherited::VisitBinaryOperator(E);
9137     }
9138 
9139     // A custom visitor for BinaryConditionalOperator is needed because the
9140     // regular visitor would check the condition and true expression separately
9141     // but both point to the same place giving duplicate diagnostics.
9142     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9143       Visit(E->getCond());
9144       Visit(E->getFalseExpr());
9145     }
9146 
9147     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9148       Decl* ReferenceDecl = DRE->getDecl();
9149       if (OrigDecl != ReferenceDecl) return;
9150       unsigned diag;
9151       if (isReferenceType) {
9152         diag = diag::warn_uninit_self_reference_in_reference_init;
9153       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9154         diag = diag::warn_static_self_reference_in_init;
9155       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9156                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9157                  DRE->getDecl()->getType()->isRecordType()) {
9158         diag = diag::warn_uninit_self_reference_in_init;
9159       } else {
9160         // Local variables will be handled by the CFG analysis.
9161         return;
9162       }
9163 
9164       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9165                             S.PDiag(diag)
9166                               << DRE->getNameInfo().getName()
9167                               << OrigDecl->getLocation()
9168                               << DRE->getSourceRange());
9169     }
9170   };
9171 
9172   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9173   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9174                                  bool DirectInit) {
9175     // Parameters arguments are occassionially constructed with itself,
9176     // for instance, in recursive functions.  Skip them.
9177     if (isa<ParmVarDecl>(OrigDecl))
9178       return;
9179 
9180     E = E->IgnoreParens();
9181 
9182     // Skip checking T a = a where T is not a record or reference type.
9183     // Doing so is a way to silence uninitialized warnings.
9184     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9185       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9186         if (ICE->getCastKind() == CK_LValueToRValue)
9187           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9188             if (DRE->getDecl() == OrigDecl)
9189               return;
9190 
9191     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9192   }
9193 } // end anonymous namespace
9194 
9195 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9196                                             DeclarationName Name, QualType Type,
9197                                             TypeSourceInfo *TSI,
9198                                             SourceRange Range, bool DirectInit,
9199                                             Expr *Init) {
9200   bool IsInitCapture = !VDecl;
9201   assert((!VDecl || !VDecl->isInitCapture()) &&
9202          "init captures are expected to be deduced prior to initialization");
9203 
9204   ArrayRef<Expr *> DeduceInits = Init;
9205   if (DirectInit) {
9206     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9207       DeduceInits = PL->exprs();
9208     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9209       DeduceInits = IL->inits();
9210   }
9211 
9212   // Deduction only works if we have exactly one source expression.
9213   if (DeduceInits.empty()) {
9214     // It isn't possible to write this directly, but it is possible to
9215     // end up in this situation with "auto x(some_pack...);"
9216     Diag(Init->getLocStart(), IsInitCapture
9217                                   ? diag::err_init_capture_no_expression
9218                                   : diag::err_auto_var_init_no_expression)
9219         << Name << Type << Range;
9220     return QualType();
9221   }
9222 
9223   if (DeduceInits.size() > 1) {
9224     Diag(DeduceInits[1]->getLocStart(),
9225          IsInitCapture ? diag::err_init_capture_multiple_expressions
9226                        : diag::err_auto_var_init_multiple_expressions)
9227         << Name << Type << Range;
9228     return QualType();
9229   }
9230 
9231   Expr *DeduceInit = DeduceInits[0];
9232   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9233     Diag(Init->getLocStart(), IsInitCapture
9234                                   ? diag::err_init_capture_paren_braces
9235                                   : diag::err_auto_var_init_paren_braces)
9236         << isa<InitListExpr>(Init) << Name << Type << Range;
9237     return QualType();
9238   }
9239 
9240   // Expressions default to 'id' when we're in a debugger.
9241   bool DefaultedAnyToId = false;
9242   if (getLangOpts().DebuggerCastResultToId &&
9243       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9244     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9245     if (Result.isInvalid()) {
9246       return QualType();
9247     }
9248     Init = Result.get();
9249     DefaultedAnyToId = true;
9250   }
9251 
9252   QualType DeducedType;
9253   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9254     if (!IsInitCapture)
9255       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9256     else if (isa<InitListExpr>(Init))
9257       Diag(Range.getBegin(),
9258            diag::err_init_capture_deduction_failure_from_init_list)
9259           << Name
9260           << (DeduceInit->getType().isNull() ? TSI->getType()
9261                                              : DeduceInit->getType())
9262           << DeduceInit->getSourceRange();
9263     else
9264       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9265           << Name << TSI->getType()
9266           << (DeduceInit->getType().isNull() ? TSI->getType()
9267                                              : DeduceInit->getType())
9268           << DeduceInit->getSourceRange();
9269   }
9270 
9271   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9272   // 'id' instead of a specific object type prevents most of our usual
9273   // checks.
9274   // We only want to warn outside of template instantiations, though:
9275   // inside a template, the 'id' could have come from a parameter.
9276   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9277       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9278     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9279     Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9280   }
9281 
9282   return DeducedType;
9283 }
9284 
9285 /// AddInitializerToDecl - Adds the initializer Init to the
9286 /// declaration dcl. If DirectInit is true, this is C++ direct
9287 /// initialization rather than copy initialization.
9288 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9289                                 bool DirectInit, bool TypeMayContainAuto) {
9290   // If there is no declaration, there was an error parsing it.  Just ignore
9291   // the initializer.
9292   if (!RealDecl || RealDecl->isInvalidDecl()) {
9293     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9294     return;
9295   }
9296 
9297   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9298     // Pure-specifiers are handled in ActOnPureSpecifier.
9299     Diag(Method->getLocation(), diag::err_member_function_initialization)
9300       << Method->getDeclName() << Init->getSourceRange();
9301     Method->setInvalidDecl();
9302     return;
9303   }
9304 
9305   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9306   if (!VDecl) {
9307     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9308     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9309     RealDecl->setInvalidDecl();
9310     return;
9311   }
9312 
9313   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9314   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9315     // Attempt typo correction early so that the type of the init expression can
9316     // be deduced based on the chosen correction if the original init contains a
9317     // TypoExpr.
9318     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9319     if (!Res.isUsable()) {
9320       RealDecl->setInvalidDecl();
9321       return;
9322     }
9323     Init = Res.get();
9324 
9325     QualType DeducedType = deduceVarTypeFromInitializer(
9326         VDecl, VDecl->getDeclName(), VDecl->getType(),
9327         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9328     if (DeducedType.isNull()) {
9329       RealDecl->setInvalidDecl();
9330       return;
9331     }
9332 
9333     VDecl->setType(DeducedType);
9334     assert(VDecl->isLinkageValid());
9335 
9336     // In ARC, infer lifetime.
9337     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9338       VDecl->setInvalidDecl();
9339 
9340     // If this is a redeclaration, check that the type we just deduced matches
9341     // the previously declared type.
9342     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9343       // We never need to merge the type, because we cannot form an incomplete
9344       // array of auto, nor deduce such a type.
9345       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9346     }
9347 
9348     // Check the deduced type is valid for a variable declaration.
9349     CheckVariableDeclarationType(VDecl);
9350     if (VDecl->isInvalidDecl())
9351       return;
9352   }
9353 
9354   // dllimport cannot be used on variable definitions.
9355   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9356     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9357     VDecl->setInvalidDecl();
9358     return;
9359   }
9360 
9361   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9362     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9363     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9364     VDecl->setInvalidDecl();
9365     return;
9366   }
9367 
9368   if (!VDecl->getType()->isDependentType()) {
9369     // A definition must end up with a complete type, which means it must be
9370     // complete with the restriction that an array type might be completed by
9371     // the initializer; note that later code assumes this restriction.
9372     QualType BaseDeclType = VDecl->getType();
9373     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9374       BaseDeclType = Array->getElementType();
9375     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9376                             diag::err_typecheck_decl_incomplete_type)) {
9377       RealDecl->setInvalidDecl();
9378       return;
9379     }
9380 
9381     // The variable can not have an abstract class type.
9382     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9383                                diag::err_abstract_type_in_decl,
9384                                AbstractVariableType))
9385       VDecl->setInvalidDecl();
9386   }
9387 
9388   VarDecl *Def;
9389   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9390     NamedDecl *Hidden = nullptr;
9391     if (!hasVisibleDefinition(Def, &Hidden) &&
9392         (VDecl->getFormalLinkage() == InternalLinkage ||
9393          VDecl->getDescribedVarTemplate() ||
9394          VDecl->getNumTemplateParameterLists() ||
9395          VDecl->getDeclContext()->isDependentContext())) {
9396       // The previous definition is hidden, and multiple definitions are
9397       // permitted (in separate TUs). Form another definition of it.
9398     } else {
9399       Diag(VDecl->getLocation(), diag::err_redefinition)
9400         << VDecl->getDeclName();
9401       Diag(Def->getLocation(), diag::note_previous_definition);
9402       VDecl->setInvalidDecl();
9403       return;
9404     }
9405   }
9406 
9407   if (getLangOpts().CPlusPlus) {
9408     // C++ [class.static.data]p4
9409     //   If a static data member is of const integral or const
9410     //   enumeration type, its declaration in the class definition can
9411     //   specify a constant-initializer which shall be an integral
9412     //   constant expression (5.19). In that case, the member can appear
9413     //   in integral constant expressions. The member shall still be
9414     //   defined in a namespace scope if it is used in the program and the
9415     //   namespace scope definition shall not contain an initializer.
9416     //
9417     // We already performed a redefinition check above, but for static
9418     // data members we also need to check whether there was an in-class
9419     // declaration with an initializer.
9420     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9421       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9422           << VDecl->getDeclName();
9423       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9424            diag::note_previous_initializer)
9425           << 0;
9426       return;
9427     }
9428 
9429     if (VDecl->hasLocalStorage())
9430       getCurFunction()->setHasBranchProtectedScope();
9431 
9432     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9433       VDecl->setInvalidDecl();
9434       return;
9435     }
9436   }
9437 
9438   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9439   // a kernel function cannot be initialized."
9440   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9441     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9442     VDecl->setInvalidDecl();
9443     return;
9444   }
9445 
9446   // Get the decls type and save a reference for later, since
9447   // CheckInitializerTypes may change it.
9448   QualType DclT = VDecl->getType(), SavT = DclT;
9449 
9450   // Expressions default to 'id' when we're in a debugger
9451   // and we are assigning it to a variable of Objective-C pointer type.
9452   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9453       Init->getType() == Context.UnknownAnyTy) {
9454     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9455     if (Result.isInvalid()) {
9456       VDecl->setInvalidDecl();
9457       return;
9458     }
9459     Init = Result.get();
9460   }
9461 
9462   // Perform the initialization.
9463   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9464   if (!VDecl->isInvalidDecl()) {
9465     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9466     InitializationKind Kind =
9467         DirectInit
9468             ? CXXDirectInit
9469                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9470                                                      Init->getLocStart(),
9471                                                      Init->getLocEnd())
9472                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9473             : InitializationKind::CreateCopy(VDecl->getLocation(),
9474                                              Init->getLocStart());
9475 
9476     MultiExprArg Args = Init;
9477     if (CXXDirectInit)
9478       Args = MultiExprArg(CXXDirectInit->getExprs(),
9479                           CXXDirectInit->getNumExprs());
9480 
9481     // Try to correct any TypoExprs in the initialization arguments.
9482     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9483       ExprResult Res = CorrectDelayedTyposInExpr(
9484           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9485             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9486             return Init.Failed() ? ExprError() : E;
9487           });
9488       if (Res.isInvalid()) {
9489         VDecl->setInvalidDecl();
9490       } else if (Res.get() != Args[Idx]) {
9491         Args[Idx] = Res.get();
9492       }
9493     }
9494     if (VDecl->isInvalidDecl())
9495       return;
9496 
9497     InitializationSequence InitSeq(*this, Entity, Kind, Args);
9498     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9499     if (Result.isInvalid()) {
9500       VDecl->setInvalidDecl();
9501       return;
9502     }
9503 
9504     Init = Result.getAs<Expr>();
9505   }
9506 
9507   // Check for self-references within variable initializers.
9508   // Variables declared within a function/method body (except for references)
9509   // are handled by a dataflow analysis.
9510   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9511       VDecl->getType()->isReferenceType()) {
9512     CheckSelfReference(*this, RealDecl, Init, DirectInit);
9513   }
9514 
9515   // If the type changed, it means we had an incomplete type that was
9516   // completed by the initializer. For example:
9517   //   int ary[] = { 1, 3, 5 };
9518   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9519   if (!VDecl->isInvalidDecl() && (DclT != SavT))
9520     VDecl->setType(DclT);
9521 
9522   if (!VDecl->isInvalidDecl()) {
9523     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9524 
9525     if (VDecl->hasAttr<BlocksAttr>())
9526       checkRetainCycles(VDecl, Init);
9527 
9528     // It is safe to assign a weak reference into a strong variable.
9529     // Although this code can still have problems:
9530     //   id x = self.weakProp;
9531     //   id y = self.weakProp;
9532     // we do not warn to warn spuriously when 'x' and 'y' are on separate
9533     // paths through the function. This should be revisited if
9534     // -Wrepeated-use-of-weak is made flow-sensitive.
9535     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9536         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9537                          Init->getLocStart()))
9538       getCurFunction()->markSafeWeakUse(Init);
9539   }
9540 
9541   // The initialization is usually a full-expression.
9542   //
9543   // FIXME: If this is a braced initialization of an aggregate, it is not
9544   // an expression, and each individual field initializer is a separate
9545   // full-expression. For instance, in:
9546   //
9547   //   struct Temp { ~Temp(); };
9548   //   struct S { S(Temp); };
9549   //   struct T { S a, b; } t = { Temp(), Temp() }
9550   //
9551   // we should destroy the first Temp before constructing the second.
9552   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9553                                           false,
9554                                           VDecl->isConstexpr());
9555   if (Result.isInvalid()) {
9556     VDecl->setInvalidDecl();
9557     return;
9558   }
9559   Init = Result.get();
9560 
9561   // Attach the initializer to the decl.
9562   VDecl->setInit(Init);
9563 
9564   if (VDecl->isLocalVarDecl()) {
9565     // C99 6.7.8p4: All the expressions in an initializer for an object that has
9566     // static storage duration shall be constant expressions or string literals.
9567     // C++ does not have this restriction.
9568     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9569       const Expr *Culprit;
9570       if (VDecl->getStorageClass() == SC_Static)
9571         CheckForConstantInitializer(Init, DclT);
9572       // C89 is stricter than C99 for non-static aggregate types.
9573       // C89 6.5.7p3: All the expressions [...] in an initializer list
9574       // for an object that has aggregate or union type shall be
9575       // constant expressions.
9576       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9577                isa<InitListExpr>(Init) &&
9578                !Init->isConstantInitializer(Context, false, &Culprit))
9579         Diag(Culprit->getExprLoc(),
9580              diag::ext_aggregate_init_not_constant)
9581           << Culprit->getSourceRange();
9582     }
9583   } else if (VDecl->isStaticDataMember() &&
9584              VDecl->getLexicalDeclContext()->isRecord()) {
9585     // This is an in-class initialization for a static data member, e.g.,
9586     //
9587     // struct S {
9588     //   static const int value = 17;
9589     // };
9590 
9591     // C++ [class.mem]p4:
9592     //   A member-declarator can contain a constant-initializer only
9593     //   if it declares a static member (9.4) of const integral or
9594     //   const enumeration type, see 9.4.2.
9595     //
9596     // C++11 [class.static.data]p3:
9597     //   If a non-volatile const static data member is of integral or
9598     //   enumeration type, its declaration in the class definition can
9599     //   specify a brace-or-equal-initializer in which every initalizer-clause
9600     //   that is an assignment-expression is a constant expression. A static
9601     //   data member of literal type can be declared in the class definition
9602     //   with the constexpr specifier; if so, its declaration shall specify a
9603     //   brace-or-equal-initializer in which every initializer-clause that is
9604     //   an assignment-expression is a constant expression.
9605 
9606     // Do nothing on dependent types.
9607     if (DclT->isDependentType()) {
9608 
9609     // Allow any 'static constexpr' members, whether or not they are of literal
9610     // type. We separately check that every constexpr variable is of literal
9611     // type.
9612     } else if (VDecl->isConstexpr()) {
9613 
9614     // Require constness.
9615     } else if (!DclT.isConstQualified()) {
9616       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9617         << Init->getSourceRange();
9618       VDecl->setInvalidDecl();
9619 
9620     // We allow integer constant expressions in all cases.
9621     } else if (DclT->isIntegralOrEnumerationType()) {
9622       // Check whether the expression is a constant expression.
9623       SourceLocation Loc;
9624       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9625         // In C++11, a non-constexpr const static data member with an
9626         // in-class initializer cannot be volatile.
9627         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9628       else if (Init->isValueDependent())
9629         ; // Nothing to check.
9630       else if (Init->isIntegerConstantExpr(Context, &Loc))
9631         ; // Ok, it's an ICE!
9632       else if (Init->isEvaluatable(Context)) {
9633         // If we can constant fold the initializer through heroics, accept it,
9634         // but report this as a use of an extension for -pedantic.
9635         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9636           << Init->getSourceRange();
9637       } else {
9638         // Otherwise, this is some crazy unknown case.  Report the issue at the
9639         // location provided by the isIntegerConstantExpr failed check.
9640         Diag(Loc, diag::err_in_class_initializer_non_constant)
9641           << Init->getSourceRange();
9642         VDecl->setInvalidDecl();
9643       }
9644 
9645     // We allow foldable floating-point constants as an extension.
9646     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9647       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9648       // it anyway and provide a fixit to add the 'constexpr'.
9649       if (getLangOpts().CPlusPlus11) {
9650         Diag(VDecl->getLocation(),
9651              diag::ext_in_class_initializer_float_type_cxx11)
9652             << DclT << Init->getSourceRange();
9653         Diag(VDecl->getLocStart(),
9654              diag::note_in_class_initializer_float_type_cxx11)
9655             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9656       } else {
9657         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9658           << DclT << Init->getSourceRange();
9659 
9660         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9661           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9662             << Init->getSourceRange();
9663           VDecl->setInvalidDecl();
9664         }
9665       }
9666 
9667     // Suggest adding 'constexpr' in C++11 for literal types.
9668     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9669       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9670         << DclT << Init->getSourceRange()
9671         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9672       VDecl->setConstexpr(true);
9673 
9674     } else {
9675       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9676         << DclT << Init->getSourceRange();
9677       VDecl->setInvalidDecl();
9678     }
9679   } else if (VDecl->isFileVarDecl()) {
9680     if (VDecl->getStorageClass() == SC_Extern &&
9681         (!getLangOpts().CPlusPlus ||
9682          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9683            VDecl->isExternC())) &&
9684         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9685       Diag(VDecl->getLocation(), diag::warn_extern_init);
9686 
9687     // C99 6.7.8p4. All file scoped initializers need to be constant.
9688     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9689       CheckForConstantInitializer(Init, DclT);
9690   }
9691 
9692   // We will represent direct-initialization similarly to copy-initialization:
9693   //    int x(1);  -as-> int x = 1;
9694   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9695   //
9696   // Clients that want to distinguish between the two forms, can check for
9697   // direct initializer using VarDecl::getInitStyle().
9698   // A major benefit is that clients that don't particularly care about which
9699   // exactly form was it (like the CodeGen) can handle both cases without
9700   // special case code.
9701 
9702   // C++ 8.5p11:
9703   // The form of initialization (using parentheses or '=') is generally
9704   // insignificant, but does matter when the entity being initialized has a
9705   // class type.
9706   if (CXXDirectInit) {
9707     assert(DirectInit && "Call-style initializer must be direct init.");
9708     VDecl->setInitStyle(VarDecl::CallInit);
9709   } else if (DirectInit) {
9710     // This must be list-initialization. No other way is direct-initialization.
9711     VDecl->setInitStyle(VarDecl::ListInit);
9712   }
9713 
9714   CheckCompleteVariableDeclaration(VDecl);
9715 }
9716 
9717 /// ActOnInitializerError - Given that there was an error parsing an
9718 /// initializer for the given declaration, try to return to some form
9719 /// of sanity.
9720 void Sema::ActOnInitializerError(Decl *D) {
9721   // Our main concern here is re-establishing invariants like "a
9722   // variable's type is either dependent or complete".
9723   if (!D || D->isInvalidDecl()) return;
9724 
9725   VarDecl *VD = dyn_cast<VarDecl>(D);
9726   if (!VD) return;
9727 
9728   // Auto types are meaningless if we can't make sense of the initializer.
9729   if (ParsingInitForAutoVars.count(D)) {
9730     D->setInvalidDecl();
9731     return;
9732   }
9733 
9734   QualType Ty = VD->getType();
9735   if (Ty->isDependentType()) return;
9736 
9737   // Require a complete type.
9738   if (RequireCompleteType(VD->getLocation(),
9739                           Context.getBaseElementType(Ty),
9740                           diag::err_typecheck_decl_incomplete_type)) {
9741     VD->setInvalidDecl();
9742     return;
9743   }
9744 
9745   // Require a non-abstract type.
9746   if (RequireNonAbstractType(VD->getLocation(), Ty,
9747                              diag::err_abstract_type_in_decl,
9748                              AbstractVariableType)) {
9749     VD->setInvalidDecl();
9750     return;
9751   }
9752 
9753   // Don't bother complaining about constructors or destructors,
9754   // though.
9755 }
9756 
9757 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9758                                   bool TypeMayContainAuto) {
9759   // If there is no declaration, there was an error parsing it. Just ignore it.
9760   if (!RealDecl)
9761     return;
9762 
9763   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9764     QualType Type = Var->getType();
9765 
9766     // C++11 [dcl.spec.auto]p3
9767     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9768       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9769         << Var->getDeclName() << Type;
9770       Var->setInvalidDecl();
9771       return;
9772     }
9773 
9774     // C++11 [class.static.data]p3: A static data member can be declared with
9775     // the constexpr specifier; if so, its declaration shall specify
9776     // a brace-or-equal-initializer.
9777     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9778     // the definition of a variable [...] or the declaration of a static data
9779     // member.
9780     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9781       if (Var->isStaticDataMember())
9782         Diag(Var->getLocation(),
9783              diag::err_constexpr_static_mem_var_requires_init)
9784           << Var->getDeclName();
9785       else
9786         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9787       Var->setInvalidDecl();
9788       return;
9789     }
9790 
9791     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
9792     // definition having the concept specifier is called a variable concept. A
9793     // concept definition refers to [...] a variable concept and its initializer.
9794     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
9795       if (VTD->isConcept()) {
9796         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
9797         Var->setInvalidDecl();
9798         return;
9799       }
9800     }
9801 
9802     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9803     // be initialized.
9804     if (!Var->isInvalidDecl() &&
9805         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9806         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9807       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9808       Var->setInvalidDecl();
9809       return;
9810     }
9811 
9812     switch (Var->isThisDeclarationADefinition()) {
9813     case VarDecl::Definition:
9814       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9815         break;
9816 
9817       // We have an out-of-line definition of a static data member
9818       // that has an in-class initializer, so we type-check this like
9819       // a declaration.
9820       //
9821       // Fall through
9822 
9823     case VarDecl::DeclarationOnly:
9824       // It's only a declaration.
9825 
9826       // Block scope. C99 6.7p7: If an identifier for an object is
9827       // declared with no linkage (C99 6.2.2p6), the type for the
9828       // object shall be complete.
9829       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9830           !Var->hasLinkage() && !Var->isInvalidDecl() &&
9831           RequireCompleteType(Var->getLocation(), Type,
9832                               diag::err_typecheck_decl_incomplete_type))
9833         Var->setInvalidDecl();
9834 
9835       // Make sure that the type is not abstract.
9836       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9837           RequireNonAbstractType(Var->getLocation(), Type,
9838                                  diag::err_abstract_type_in_decl,
9839                                  AbstractVariableType))
9840         Var->setInvalidDecl();
9841       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9842           Var->getStorageClass() == SC_PrivateExtern) {
9843         Diag(Var->getLocation(), diag::warn_private_extern);
9844         Diag(Var->getLocation(), diag::note_private_extern);
9845       }
9846 
9847       return;
9848 
9849     case VarDecl::TentativeDefinition:
9850       // File scope. C99 6.9.2p2: A declaration of an identifier for an
9851       // object that has file scope without an initializer, and without a
9852       // storage-class specifier or with the storage-class specifier "static",
9853       // constitutes a tentative definition. Note: A tentative definition with
9854       // external linkage is valid (C99 6.2.2p5).
9855       if (!Var->isInvalidDecl()) {
9856         if (const IncompleteArrayType *ArrayT
9857                                     = Context.getAsIncompleteArrayType(Type)) {
9858           if (RequireCompleteType(Var->getLocation(),
9859                                   ArrayT->getElementType(),
9860                                   diag::err_illegal_decl_array_incomplete_type))
9861             Var->setInvalidDecl();
9862         } else if (Var->getStorageClass() == SC_Static) {
9863           // C99 6.9.2p3: If the declaration of an identifier for an object is
9864           // a tentative definition and has internal linkage (C99 6.2.2p3), the
9865           // declared type shall not be an incomplete type.
9866           // NOTE: code such as the following
9867           //     static struct s;
9868           //     struct s { int a; };
9869           // is accepted by gcc. Hence here we issue a warning instead of
9870           // an error and we do not invalidate the static declaration.
9871           // NOTE: to avoid multiple warnings, only check the first declaration.
9872           if (Var->isFirstDecl())
9873             RequireCompleteType(Var->getLocation(), Type,
9874                                 diag::ext_typecheck_decl_incomplete_type);
9875         }
9876       }
9877 
9878       // Record the tentative definition; we're done.
9879       if (!Var->isInvalidDecl())
9880         TentativeDefinitions.push_back(Var);
9881       return;
9882     }
9883 
9884     // Provide a specific diagnostic for uninitialized variable
9885     // definitions with incomplete array type.
9886     if (Type->isIncompleteArrayType()) {
9887       Diag(Var->getLocation(),
9888            diag::err_typecheck_incomplete_array_needs_initializer);
9889       Var->setInvalidDecl();
9890       return;
9891     }
9892 
9893     // Provide a specific diagnostic for uninitialized variable
9894     // definitions with reference type.
9895     if (Type->isReferenceType()) {
9896       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9897         << Var->getDeclName()
9898         << SourceRange(Var->getLocation(), Var->getLocation());
9899       Var->setInvalidDecl();
9900       return;
9901     }
9902 
9903     // Do not attempt to type-check the default initializer for a
9904     // variable with dependent type.
9905     if (Type->isDependentType())
9906       return;
9907 
9908     if (Var->isInvalidDecl())
9909       return;
9910 
9911     if (!Var->hasAttr<AliasAttr>()) {
9912       if (RequireCompleteType(Var->getLocation(),
9913                               Context.getBaseElementType(Type),
9914                               diag::err_typecheck_decl_incomplete_type)) {
9915         Var->setInvalidDecl();
9916         return;
9917       }
9918     } else {
9919       return;
9920     }
9921 
9922     // The variable can not have an abstract class type.
9923     if (RequireNonAbstractType(Var->getLocation(), Type,
9924                                diag::err_abstract_type_in_decl,
9925                                AbstractVariableType)) {
9926       Var->setInvalidDecl();
9927       return;
9928     }
9929 
9930     // Check for jumps past the implicit initializer.  C++0x
9931     // clarifies that this applies to a "variable with automatic
9932     // storage duration", not a "local variable".
9933     // C++11 [stmt.dcl]p3
9934     //   A program that jumps from a point where a variable with automatic
9935     //   storage duration is not in scope to a point where it is in scope is
9936     //   ill-formed unless the variable has scalar type, class type with a
9937     //   trivial default constructor and a trivial destructor, a cv-qualified
9938     //   version of one of these types, or an array of one of the preceding
9939     //   types and is declared without an initializer.
9940     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9941       if (const RecordType *Record
9942             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
9943         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9944         // Mark the function for further checking even if the looser rules of
9945         // C++11 do not require such checks, so that we can diagnose
9946         // incompatibilities with C++98.
9947         if (!CXXRecord->isPOD())
9948           getCurFunction()->setHasBranchProtectedScope();
9949       }
9950     }
9951 
9952     // C++03 [dcl.init]p9:
9953     //   If no initializer is specified for an object, and the
9954     //   object is of (possibly cv-qualified) non-POD class type (or
9955     //   array thereof), the object shall be default-initialized; if
9956     //   the object is of const-qualified type, the underlying class
9957     //   type shall have a user-declared default
9958     //   constructor. Otherwise, if no initializer is specified for
9959     //   a non- static object, the object and its subobjects, if
9960     //   any, have an indeterminate initial value); if the object
9961     //   or any of its subobjects are of const-qualified type, the
9962     //   program is ill-formed.
9963     // C++0x [dcl.init]p11:
9964     //   If no initializer is specified for an object, the object is
9965     //   default-initialized; [...].
9966     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
9967     InitializationKind Kind
9968       = InitializationKind::CreateDefault(Var->getLocation());
9969 
9970     InitializationSequence InitSeq(*this, Entity, Kind, None);
9971     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
9972     if (Init.isInvalid())
9973       Var->setInvalidDecl();
9974     else if (Init.get()) {
9975       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
9976       // This is important for template substitution.
9977       Var->setInitStyle(VarDecl::CallInit);
9978     }
9979 
9980     CheckCompleteVariableDeclaration(Var);
9981   }
9982 }
9983 
9984 void Sema::ActOnCXXForRangeDecl(Decl *D) {
9985   // If there is no declaration, there was an error parsing it. Ignore it.
9986   if (!D)
9987     return;
9988 
9989   VarDecl *VD = dyn_cast<VarDecl>(D);
9990   if (!VD) {
9991     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9992     D->setInvalidDecl();
9993     return;
9994   }
9995 
9996   VD->setCXXForRangeDecl(true);
9997 
9998   // for-range-declaration cannot be given a storage class specifier.
9999   int Error = -1;
10000   switch (VD->getStorageClass()) {
10001   case SC_None:
10002     break;
10003   case SC_Extern:
10004     Error = 0;
10005     break;
10006   case SC_Static:
10007     Error = 1;
10008     break;
10009   case SC_PrivateExtern:
10010     Error = 2;
10011     break;
10012   case SC_Auto:
10013     Error = 3;
10014     break;
10015   case SC_Register:
10016     Error = 4;
10017     break;
10018   }
10019   if (Error != -1) {
10020     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10021       << VD->getDeclName() << Error;
10022     D->setInvalidDecl();
10023   }
10024 }
10025 
10026 StmtResult
10027 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10028                                  IdentifierInfo *Ident,
10029                                  ParsedAttributes &Attrs,
10030                                  SourceLocation AttrEnd) {
10031   // C++1y [stmt.iter]p1:
10032   //   A range-based for statement of the form
10033   //      for ( for-range-identifier : for-range-initializer ) statement
10034   //   is equivalent to
10035   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10036   DeclSpec DS(Attrs.getPool().getFactory());
10037 
10038   const char *PrevSpec;
10039   unsigned DiagID;
10040   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10041                      getPrintingPolicy());
10042 
10043   Declarator D(DS, Declarator::ForContext);
10044   D.SetIdentifier(Ident, IdentLoc);
10045   D.takeAttributes(Attrs, AttrEnd);
10046 
10047   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10048   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10049                 EmptyAttrs, IdentLoc);
10050   Decl *Var = ActOnDeclarator(S, D);
10051   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10052   FinalizeDeclaration(Var);
10053   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10054                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10055 }
10056 
10057 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10058   if (var->isInvalidDecl()) return;
10059 
10060   // In Objective-C, don't allow jumps past the implicit initialization of a
10061   // local retaining variable.
10062   if (getLangOpts().ObjC1 &&
10063       var->hasLocalStorage()) {
10064     switch (var->getType().getObjCLifetime()) {
10065     case Qualifiers::OCL_None:
10066     case Qualifiers::OCL_ExplicitNone:
10067     case Qualifiers::OCL_Autoreleasing:
10068       break;
10069 
10070     case Qualifiers::OCL_Weak:
10071     case Qualifiers::OCL_Strong:
10072       getCurFunction()->setHasBranchProtectedScope();
10073       break;
10074     }
10075   }
10076 
10077   // Warn about externally-visible variables being defined without a
10078   // prior declaration.  We only want to do this for global
10079   // declarations, but we also specifically need to avoid doing it for
10080   // class members because the linkage of an anonymous class can
10081   // change if it's later given a typedef name.
10082   if (var->isThisDeclarationADefinition() &&
10083       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10084       var->isExternallyVisible() && var->hasLinkage() &&
10085       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10086                                   var->getLocation())) {
10087     // Find a previous declaration that's not a definition.
10088     VarDecl *prev = var->getPreviousDecl();
10089     while (prev && prev->isThisDeclarationADefinition())
10090       prev = prev->getPreviousDecl();
10091 
10092     if (!prev)
10093       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10094   }
10095 
10096   if (var->getTLSKind() == VarDecl::TLS_Static) {
10097     const Expr *Culprit;
10098     if (var->getType().isDestructedType()) {
10099       // GNU C++98 edits for __thread, [basic.start.term]p3:
10100       //   The type of an object with thread storage duration shall not
10101       //   have a non-trivial destructor.
10102       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10103       if (getLangOpts().CPlusPlus11)
10104         Diag(var->getLocation(), diag::note_use_thread_local);
10105     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
10106                !var->getInit()->isConstantInitializer(
10107                    Context, var->getType()->isReferenceType(), &Culprit)) {
10108       // GNU C++98 edits for __thread, [basic.start.init]p4:
10109       //   An object of thread storage duration shall not require dynamic
10110       //   initialization.
10111       // FIXME: Need strict checking here.
10112       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
10113         << Culprit->getSourceRange();
10114       if (getLangOpts().CPlusPlus11)
10115         Diag(var->getLocation(), diag::note_use_thread_local);
10116     }
10117   }
10118 
10119   // Apply section attributes and pragmas to global variables.
10120   bool GlobalStorage = var->hasGlobalStorage();
10121   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10122       ActiveTemplateInstantiations.empty()) {
10123     PragmaStack<StringLiteral *> *Stack = nullptr;
10124     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10125     if (var->getType().isConstQualified())
10126       Stack = &ConstSegStack;
10127     else if (!var->getInit()) {
10128       Stack = &BSSSegStack;
10129       SectionFlags |= ASTContext::PSF_Write;
10130     } else {
10131       Stack = &DataSegStack;
10132       SectionFlags |= ASTContext::PSF_Write;
10133     }
10134     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10135       var->addAttr(SectionAttr::CreateImplicit(
10136           Context, SectionAttr::Declspec_allocate,
10137           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10138     }
10139     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10140       if (UnifySection(SA->getName(), SectionFlags, var))
10141         var->dropAttr<SectionAttr>();
10142 
10143     // Apply the init_seg attribute if this has an initializer.  If the
10144     // initializer turns out to not be dynamic, we'll end up ignoring this
10145     // attribute.
10146     if (CurInitSeg && var->getInit())
10147       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10148                                                CurInitSegLoc));
10149   }
10150 
10151   // All the following checks are C++ only.
10152   if (!getLangOpts().CPlusPlus) return;
10153 
10154   QualType type = var->getType();
10155   if (type->isDependentType()) return;
10156 
10157   // __block variables might require us to capture a copy-initializer.
10158   if (var->hasAttr<BlocksAttr>()) {
10159     // It's currently invalid to ever have a __block variable with an
10160     // array type; should we diagnose that here?
10161 
10162     // Regardless, we don't want to ignore array nesting when
10163     // constructing this copy.
10164     if (type->isStructureOrClassType()) {
10165       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10166       SourceLocation poi = var->getLocation();
10167       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10168       ExprResult result
10169         = PerformMoveOrCopyInitialization(
10170             InitializedEntity::InitializeBlock(poi, type, false),
10171             var, var->getType(), varRef, /*AllowNRVO=*/true);
10172       if (!result.isInvalid()) {
10173         result = MaybeCreateExprWithCleanups(result);
10174         Expr *init = result.getAs<Expr>();
10175         Context.setBlockVarCopyInits(var, init);
10176       }
10177     }
10178   }
10179 
10180   Expr *Init = var->getInit();
10181   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10182   QualType baseType = Context.getBaseElementType(type);
10183 
10184   if (!var->getDeclContext()->isDependentContext() &&
10185       Init && !Init->isValueDependent()) {
10186     if (IsGlobal && !var->isConstexpr() &&
10187         !getDiagnostics().isIgnored(diag::warn_global_constructor,
10188                                     var->getLocation())) {
10189       // Warn about globals which don't have a constant initializer.  Don't
10190       // warn about globals with a non-trivial destructor because we already
10191       // warned about them.
10192       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10193       if (!(RD && !RD->hasTrivialDestructor()) &&
10194           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10195         Diag(var->getLocation(), diag::warn_global_constructor)
10196           << Init->getSourceRange();
10197     }
10198 
10199     if (var->isConstexpr()) {
10200       SmallVector<PartialDiagnosticAt, 8> Notes;
10201       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10202         SourceLocation DiagLoc = var->getLocation();
10203         // If the note doesn't add any useful information other than a source
10204         // location, fold it into the primary diagnostic.
10205         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10206               diag::note_invalid_subexpr_in_const_expr) {
10207           DiagLoc = Notes[0].first;
10208           Notes.clear();
10209         }
10210         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10211           << var << Init->getSourceRange();
10212         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10213           Diag(Notes[I].first, Notes[I].second);
10214       }
10215     } else if (var->isUsableInConstantExpressions(Context)) {
10216       // Check whether the initializer of a const variable of integral or
10217       // enumeration type is an ICE now, since we can't tell whether it was
10218       // initialized by a constant expression if we check later.
10219       var->checkInitIsICE();
10220     }
10221   }
10222 
10223   // Require the destructor.
10224   if (const RecordType *recordType = baseType->getAs<RecordType>())
10225     FinalizeVarWithDestructor(var, recordType);
10226 }
10227 
10228 /// \brief Determines if a variable's alignment is dependent.
10229 static bool hasDependentAlignment(VarDecl *VD) {
10230   if (VD->getType()->isDependentType())
10231     return true;
10232   for (auto *I : VD->specific_attrs<AlignedAttr>())
10233     if (I->isAlignmentDependent())
10234       return true;
10235   return false;
10236 }
10237 
10238 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10239 /// any semantic actions necessary after any initializer has been attached.
10240 void
10241 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10242   // Note that we are no longer parsing the initializer for this declaration.
10243   ParsingInitForAutoVars.erase(ThisDecl);
10244 
10245   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10246   if (!VD)
10247     return;
10248 
10249   checkAttributesAfterMerging(*this, *VD);
10250 
10251   // Perform TLS alignment check here after attributes attached to the variable
10252   // which may affect the alignment have been processed. Only perform the check
10253   // if the target has a maximum TLS alignment (zero means no constraints).
10254   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10255     // Protect the check so that it's not performed on dependent types and
10256     // dependent alignments (we can't determine the alignment in that case).
10257     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10258       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10259       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10260         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10261           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10262           << (unsigned)MaxAlignChars.getQuantity();
10263       }
10264     }
10265   }
10266 
10267   // Static locals inherit dll attributes from their function.
10268   if (VD->isStaticLocal()) {
10269     if (FunctionDecl *FD =
10270             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10271       if (Attr *A = getDLLAttr(FD)) {
10272         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10273         NewAttr->setInherited(true);
10274         VD->addAttr(NewAttr);
10275       }
10276     }
10277   }
10278 
10279   // Perform check for initializers of device-side global variables.
10280   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10281   // 7.5). CUDA also allows constant initializers for __constant__ and
10282   // __device__ variables.
10283   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
10284     const Expr *Init = VD->getInit();
10285     const bool IsGlobal = VD->hasGlobalStorage() && !VD->isStaticLocal();
10286     if (Init && IsGlobal &&
10287         (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10288          VD->hasAttr<CUDASharedAttr>())) {
10289       bool AllowedInit = false;
10290       if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10291         AllowedInit =
10292             isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10293       // We'll allow constant initializers even if it's a non-empty
10294       // constructor according to CUDA rules. This deviates from NVCC,
10295       // but allows us to handle things like constexpr constructors.
10296       if (!AllowedInit &&
10297           (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10298         AllowedInit = VD->getInit()->isConstantInitializer(
10299             Context, VD->getType()->isReferenceType());
10300 
10301       if (!AllowedInit) {
10302         Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10303                                     ? diag::err_shared_var_init
10304                                     : diag::err_dynamic_var_init)
10305             << Init->getSourceRange();
10306         VD->setInvalidDecl();
10307       }
10308     }
10309   }
10310 
10311   // Grab the dllimport or dllexport attribute off of the VarDecl.
10312   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10313 
10314   // Imported static data members cannot be defined out-of-line.
10315   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10316     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10317         VD->isThisDeclarationADefinition()) {
10318       // We allow definitions of dllimport class template static data members
10319       // with a warning.
10320       CXXRecordDecl *Context =
10321         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10322       bool IsClassTemplateMember =
10323           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10324           Context->getDescribedClassTemplate();
10325 
10326       Diag(VD->getLocation(),
10327            IsClassTemplateMember
10328                ? diag::warn_attribute_dllimport_static_field_definition
10329                : diag::err_attribute_dllimport_static_field_definition);
10330       Diag(IA->getLocation(), diag::note_attribute);
10331       if (!IsClassTemplateMember)
10332         VD->setInvalidDecl();
10333     }
10334   }
10335 
10336   // dllimport/dllexport variables cannot be thread local, their TLS index
10337   // isn't exported with the variable.
10338   if (DLLAttr && VD->getTLSKind()) {
10339     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10340     if (F && getDLLAttr(F)) {
10341       assert(VD->isStaticLocal());
10342       // But if this is a static local in a dlimport/dllexport function, the
10343       // function will never be inlined, which means the var would never be
10344       // imported, so having it marked import/export is safe.
10345     } else {
10346       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10347                                                                     << DLLAttr;
10348       VD->setInvalidDecl();
10349     }
10350   }
10351 
10352   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10353     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10354       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10355       VD->dropAttr<UsedAttr>();
10356     }
10357   }
10358 
10359   const DeclContext *DC = VD->getDeclContext();
10360   // If there's a #pragma GCC visibility in scope, and this isn't a class
10361   // member, set the visibility of this variable.
10362   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10363     AddPushedVisibilityAttribute(VD);
10364 
10365   // FIXME: Warn on unused templates.
10366   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10367       !isa<VarTemplatePartialSpecializationDecl>(VD))
10368     MarkUnusedFileScopedDecl(VD);
10369 
10370   // Now we have parsed the initializer and can update the table of magic
10371   // tag values.
10372   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10373       !VD->getType()->isIntegralOrEnumerationType())
10374     return;
10375 
10376   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10377     const Expr *MagicValueExpr = VD->getInit();
10378     if (!MagicValueExpr) {
10379       continue;
10380     }
10381     llvm::APSInt MagicValueInt;
10382     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10383       Diag(I->getRange().getBegin(),
10384            diag::err_type_tag_for_datatype_not_ice)
10385         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10386       continue;
10387     }
10388     if (MagicValueInt.getActiveBits() > 64) {
10389       Diag(I->getRange().getBegin(),
10390            diag::err_type_tag_for_datatype_too_large)
10391         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10392       continue;
10393     }
10394     uint64_t MagicValue = MagicValueInt.getZExtValue();
10395     RegisterTypeTagForDatatype(I->getArgumentKind(),
10396                                MagicValue,
10397                                I->getMatchingCType(),
10398                                I->getLayoutCompatible(),
10399                                I->getMustBeNull());
10400   }
10401 }
10402 
10403 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10404                                                    ArrayRef<Decl *> Group) {
10405   SmallVector<Decl*, 8> Decls;
10406 
10407   if (DS.isTypeSpecOwned())
10408     Decls.push_back(DS.getRepAsDecl());
10409 
10410   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10411   for (unsigned i = 0, e = Group.size(); i != e; ++i)
10412     if (Decl *D = Group[i]) {
10413       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10414         if (!FirstDeclaratorInGroup)
10415           FirstDeclaratorInGroup = DD;
10416       Decls.push_back(D);
10417     }
10418 
10419   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10420     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10421       handleTagNumbering(Tag, S);
10422       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10423           getLangOpts().CPlusPlus)
10424         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10425     }
10426   }
10427 
10428   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10429 }
10430 
10431 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10432 /// group, performing any necessary semantic checking.
10433 Sema::DeclGroupPtrTy
10434 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10435                            bool TypeMayContainAuto) {
10436   // C++0x [dcl.spec.auto]p7:
10437   //   If the type deduced for the template parameter U is not the same in each
10438   //   deduction, the program is ill-formed.
10439   // FIXME: When initializer-list support is added, a distinction is needed
10440   // between the deduced type U and the deduced type which 'auto' stands for.
10441   //   auto a = 0, b = { 1, 2, 3 };
10442   // is legal because the deduced type U is 'int' in both cases.
10443   if (TypeMayContainAuto && Group.size() > 1) {
10444     QualType Deduced;
10445     CanQualType DeducedCanon;
10446     VarDecl *DeducedDecl = nullptr;
10447     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10448       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10449         AutoType *AT = D->getType()->getContainedAutoType();
10450         // Don't reissue diagnostics when instantiating a template.
10451         if (AT && D->isInvalidDecl())
10452           break;
10453         QualType U = AT ? AT->getDeducedType() : QualType();
10454         if (!U.isNull()) {
10455           CanQualType UCanon = Context.getCanonicalType(U);
10456           if (Deduced.isNull()) {
10457             Deduced = U;
10458             DeducedCanon = UCanon;
10459             DeducedDecl = D;
10460           } else if (DeducedCanon != UCanon) {
10461             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10462                  diag::err_auto_different_deductions)
10463               << (unsigned)AT->getKeyword()
10464               << Deduced << DeducedDecl->getDeclName()
10465               << U << D->getDeclName()
10466               << DeducedDecl->getInit()->getSourceRange()
10467               << D->getInit()->getSourceRange();
10468             D->setInvalidDecl();
10469             break;
10470           }
10471         }
10472       }
10473     }
10474   }
10475 
10476   ActOnDocumentableDecls(Group);
10477 
10478   return DeclGroupPtrTy::make(
10479       DeclGroupRef::Create(Context, Group.data(), Group.size()));
10480 }
10481 
10482 void Sema::ActOnDocumentableDecl(Decl *D) {
10483   ActOnDocumentableDecls(D);
10484 }
10485 
10486 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10487   // Don't parse the comment if Doxygen diagnostics are ignored.
10488   if (Group.empty() || !Group[0])
10489     return;
10490 
10491   if (Diags.isIgnored(diag::warn_doc_param_not_found,
10492                       Group[0]->getLocation()) &&
10493       Diags.isIgnored(diag::warn_unknown_comment_command_name,
10494                       Group[0]->getLocation()))
10495     return;
10496 
10497   if (Group.size() >= 2) {
10498     // This is a decl group.  Normally it will contain only declarations
10499     // produced from declarator list.  But in case we have any definitions or
10500     // additional declaration references:
10501     //   'typedef struct S {} S;'
10502     //   'typedef struct S *S;'
10503     //   'struct S *pS;'
10504     // FinalizeDeclaratorGroup adds these as separate declarations.
10505     Decl *MaybeTagDecl = Group[0];
10506     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10507       Group = Group.slice(1);
10508     }
10509   }
10510 
10511   // See if there are any new comments that are not attached to a decl.
10512   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10513   if (!Comments.empty() &&
10514       !Comments.back()->isAttached()) {
10515     // There is at least one comment that not attached to a decl.
10516     // Maybe it should be attached to one of these decls?
10517     //
10518     // Note that this way we pick up not only comments that precede the
10519     // declaration, but also comments that *follow* the declaration -- thanks to
10520     // the lookahead in the lexer: we've consumed the semicolon and looked
10521     // ahead through comments.
10522     for (unsigned i = 0, e = Group.size(); i != e; ++i)
10523       Context.getCommentForDecl(Group[i], &PP);
10524   }
10525 }
10526 
10527 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10528 /// to introduce parameters into function prototype scope.
10529 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10530   const DeclSpec &DS = D.getDeclSpec();
10531 
10532   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10533 
10534   // C++03 [dcl.stc]p2 also permits 'auto'.
10535   StorageClass SC = SC_None;
10536   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10537     SC = SC_Register;
10538   } else if (getLangOpts().CPlusPlus &&
10539              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10540     SC = SC_Auto;
10541   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10542     Diag(DS.getStorageClassSpecLoc(),
10543          diag::err_invalid_storage_class_in_func_decl);
10544     D.getMutableDeclSpec().ClearStorageClassSpecs();
10545   }
10546 
10547   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10548     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10549       << DeclSpec::getSpecifierName(TSCS);
10550   if (DS.isConstexprSpecified())
10551     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10552       << 0;
10553   if (DS.isConceptSpecified())
10554     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10555 
10556   DiagnoseFunctionSpecifiers(DS);
10557 
10558   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10559   QualType parmDeclType = TInfo->getType();
10560 
10561   if (getLangOpts().CPlusPlus) {
10562     // Check that there are no default arguments inside the type of this
10563     // parameter.
10564     CheckExtraCXXDefaultArguments(D);
10565 
10566     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10567     if (D.getCXXScopeSpec().isSet()) {
10568       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10569         << D.getCXXScopeSpec().getRange();
10570       D.getCXXScopeSpec().clear();
10571     }
10572   }
10573 
10574   // Ensure we have a valid name
10575   IdentifierInfo *II = nullptr;
10576   if (D.hasName()) {
10577     II = D.getIdentifier();
10578     if (!II) {
10579       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10580         << GetNameForDeclarator(D).getName();
10581       D.setInvalidType(true);
10582     }
10583   }
10584 
10585   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10586   if (II) {
10587     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10588                    ForRedeclaration);
10589     LookupName(R, S);
10590     if (R.isSingleResult()) {
10591       NamedDecl *PrevDecl = R.getFoundDecl();
10592       if (PrevDecl->isTemplateParameter()) {
10593         // Maybe we will complain about the shadowed template parameter.
10594         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10595         // Just pretend that we didn't see the previous declaration.
10596         PrevDecl = nullptr;
10597       } else if (S->isDeclScope(PrevDecl)) {
10598         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10599         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10600 
10601         // Recover by removing the name
10602         II = nullptr;
10603         D.SetIdentifier(nullptr, D.getIdentifierLoc());
10604         D.setInvalidType(true);
10605       }
10606     }
10607   }
10608 
10609   // Temporarily put parameter variables in the translation unit, not
10610   // the enclosing context.  This prevents them from accidentally
10611   // looking like class members in C++.
10612   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10613                                     D.getLocStart(),
10614                                     D.getIdentifierLoc(), II,
10615                                     parmDeclType, TInfo,
10616                                     SC);
10617 
10618   if (D.isInvalidType())
10619     New->setInvalidDecl();
10620 
10621   assert(S->isFunctionPrototypeScope());
10622   assert(S->getFunctionPrototypeDepth() >= 1);
10623   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10624                     S->getNextFunctionPrototypeIndex());
10625 
10626   // Add the parameter declaration into this scope.
10627   S->AddDecl(New);
10628   if (II)
10629     IdResolver.AddDecl(New);
10630 
10631   ProcessDeclAttributes(S, New, D);
10632 
10633   if (D.getDeclSpec().isModulePrivateSpecified())
10634     Diag(New->getLocation(), diag::err_module_private_local)
10635       << 1 << New->getDeclName()
10636       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10637       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10638 
10639   if (New->hasAttr<BlocksAttr>()) {
10640     Diag(New->getLocation(), diag::err_block_on_nonlocal);
10641   }
10642   return New;
10643 }
10644 
10645 /// \brief Synthesizes a variable for a parameter arising from a
10646 /// typedef.
10647 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10648                                               SourceLocation Loc,
10649                                               QualType T) {
10650   /* FIXME: setting StartLoc == Loc.
10651      Would it be worth to modify callers so as to provide proper source
10652      location for the unnamed parameters, embedding the parameter's type? */
10653   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10654                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
10655                                            SC_None, nullptr);
10656   Param->setImplicit();
10657   return Param;
10658 }
10659 
10660 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
10661                                     ParmVarDecl * const *ParamEnd) {
10662   // Don't diagnose unused-parameter errors in template instantiations; we
10663   // will already have done so in the template itself.
10664   if (!ActiveTemplateInstantiations.empty())
10665     return;
10666 
10667   for (; Param != ParamEnd; ++Param) {
10668     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10669         !(*Param)->hasAttr<UnusedAttr>()) {
10670       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10671         << (*Param)->getDeclName();
10672     }
10673   }
10674 }
10675 
10676 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
10677                                                   ParmVarDecl * const *ParamEnd,
10678                                                   QualType ReturnTy,
10679                                                   NamedDecl *D) {
10680   if (LangOpts.NumLargeByValueCopy == 0) // No check.
10681     return;
10682 
10683   // Warn if the return value is pass-by-value and larger than the specified
10684   // threshold.
10685   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10686     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10687     if (Size > LangOpts.NumLargeByValueCopy)
10688       Diag(D->getLocation(), diag::warn_return_value_size)
10689           << D->getDeclName() << Size;
10690   }
10691 
10692   // Warn if any parameter is pass-by-value and larger than the specified
10693   // threshold.
10694   for (; Param != ParamEnd; ++Param) {
10695     QualType T = (*Param)->getType();
10696     if (T->isDependentType() || !T.isPODType(Context))
10697       continue;
10698     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10699     if (Size > LangOpts.NumLargeByValueCopy)
10700       Diag((*Param)->getLocation(), diag::warn_parameter_size)
10701           << (*Param)->getDeclName() << Size;
10702   }
10703 }
10704 
10705 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10706                                   SourceLocation NameLoc, IdentifierInfo *Name,
10707                                   QualType T, TypeSourceInfo *TSInfo,
10708                                   StorageClass SC) {
10709   // In ARC, infer a lifetime qualifier for appropriate parameter types.
10710   if (getLangOpts().ObjCAutoRefCount &&
10711       T.getObjCLifetime() == Qualifiers::OCL_None &&
10712       T->isObjCLifetimeType()) {
10713 
10714     Qualifiers::ObjCLifetime lifetime;
10715 
10716     // Special cases for arrays:
10717     //   - if it's const, use __unsafe_unretained
10718     //   - otherwise, it's an error
10719     if (T->isArrayType()) {
10720       if (!T.isConstQualified()) {
10721         DelayedDiagnostics.add(
10722             sema::DelayedDiagnostic::makeForbiddenType(
10723             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10724       }
10725       lifetime = Qualifiers::OCL_ExplicitNone;
10726     } else {
10727       lifetime = T->getObjCARCImplicitLifetime();
10728     }
10729     T = Context.getLifetimeQualifiedType(T, lifetime);
10730   }
10731 
10732   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10733                                          Context.getAdjustedParameterType(T),
10734                                          TSInfo, SC, nullptr);
10735 
10736   // Parameters can not be abstract class types.
10737   // For record types, this is done by the AbstractClassUsageDiagnoser once
10738   // the class has been completely parsed.
10739   if (!CurContext->isRecord() &&
10740       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10741                              AbstractParamType))
10742     New->setInvalidDecl();
10743 
10744   // Parameter declarators cannot be interface types. All ObjC objects are
10745   // passed by reference.
10746   if (T->isObjCObjectType()) {
10747     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10748     Diag(NameLoc,
10749          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10750       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10751     T = Context.getObjCObjectPointerType(T);
10752     New->setType(T);
10753   }
10754 
10755   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10756   // duration shall not be qualified by an address-space qualifier."
10757   // Since all parameters have automatic store duration, they can not have
10758   // an address space.
10759   if (T.getAddressSpace() != 0) {
10760     // OpenCL allows function arguments declared to be an array of a type
10761     // to be qualified with an address space.
10762     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10763       Diag(NameLoc, diag::err_arg_with_address_space);
10764       New->setInvalidDecl();
10765     }
10766   }
10767 
10768   // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
10769   // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
10770   if (getLangOpts().OpenCL && T->isPointerType()) {
10771     const QualType PTy = T->getPointeeType();
10772     if (PTy->isImageType() || PTy->isSamplerT() || PTy->isPipeType()) {
10773       Diag(NameLoc, diag::err_opencl_pointer_to_type) << PTy;
10774       New->setInvalidDecl();
10775     }
10776   }
10777 
10778   return New;
10779 }
10780 
10781 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10782                                            SourceLocation LocAfterDecls) {
10783   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10784 
10785   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10786   // for a K&R function.
10787   if (!FTI.hasPrototype) {
10788     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10789       --i;
10790       if (FTI.Params[i].Param == nullptr) {
10791         SmallString<256> Code;
10792         llvm::raw_svector_ostream(Code)
10793             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10794         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10795             << FTI.Params[i].Ident
10796             << FixItHint::CreateInsertion(LocAfterDecls, Code);
10797 
10798         // Implicitly declare the argument as type 'int' for lack of a better
10799         // type.
10800         AttributeFactory attrs;
10801         DeclSpec DS(attrs);
10802         const char* PrevSpec; // unused
10803         unsigned DiagID; // unused
10804         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10805                            DiagID, Context.getPrintingPolicy());
10806         // Use the identifier location for the type source range.
10807         DS.SetRangeStart(FTI.Params[i].IdentLoc);
10808         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10809         Declarator ParamD(DS, Declarator::KNRTypeListContext);
10810         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10811         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10812       }
10813     }
10814   }
10815 }
10816 
10817 Decl *
10818 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
10819                               MultiTemplateParamsArg TemplateParameterLists,
10820                               SkipBodyInfo *SkipBody) {
10821   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10822   assert(D.isFunctionDeclarator() && "Not a function declarator!");
10823   Scope *ParentScope = FnBodyScope->getParent();
10824 
10825   D.setFunctionDefinitionKind(FDK_Definition);
10826   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
10827   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
10828 }
10829 
10830 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10831   Consumer.HandleInlineMethodDefinition(D);
10832 }
10833 
10834 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10835                              const FunctionDecl*& PossibleZeroParamPrototype) {
10836   // Don't warn about invalid declarations.
10837   if (FD->isInvalidDecl())
10838     return false;
10839 
10840   // Or declarations that aren't global.
10841   if (!FD->isGlobal())
10842     return false;
10843 
10844   // Don't warn about C++ member functions.
10845   if (isa<CXXMethodDecl>(FD))
10846     return false;
10847 
10848   // Don't warn about 'main'.
10849   if (FD->isMain())
10850     return false;
10851 
10852   // Don't warn about inline functions.
10853   if (FD->isInlined())
10854     return false;
10855 
10856   // Don't warn about function templates.
10857   if (FD->getDescribedFunctionTemplate())
10858     return false;
10859 
10860   // Don't warn about function template specializations.
10861   if (FD->isFunctionTemplateSpecialization())
10862     return false;
10863 
10864   // Don't warn for OpenCL kernels.
10865   if (FD->hasAttr<OpenCLKernelAttr>())
10866     return false;
10867 
10868   // Don't warn on explicitly deleted functions.
10869   if (FD->isDeleted())
10870     return false;
10871 
10872   bool MissingPrototype = true;
10873   for (const FunctionDecl *Prev = FD->getPreviousDecl();
10874        Prev; Prev = Prev->getPreviousDecl()) {
10875     // Ignore any declarations that occur in function or method
10876     // scope, because they aren't visible from the header.
10877     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10878       continue;
10879 
10880     MissingPrototype = !Prev->getType()->isFunctionProtoType();
10881     if (FD->getNumParams() == 0)
10882       PossibleZeroParamPrototype = Prev;
10883     break;
10884   }
10885 
10886   return MissingPrototype;
10887 }
10888 
10889 void
10890 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10891                                    const FunctionDecl *EffectiveDefinition,
10892                                    SkipBodyInfo *SkipBody) {
10893   // Don't complain if we're in GNU89 mode and the previous definition
10894   // was an extern inline function.
10895   const FunctionDecl *Definition = EffectiveDefinition;
10896   if (!Definition)
10897     if (!FD->isDefined(Definition))
10898       return;
10899 
10900   if (canRedefineFunction(Definition, getLangOpts()))
10901     return;
10902 
10903   // If we don't have a visible definition of the function, and it's inline or
10904   // a template, skip the new definition.
10905   if (SkipBody && !hasVisibleDefinition(Definition) &&
10906       (Definition->getFormalLinkage() == InternalLinkage ||
10907        Definition->isInlined() ||
10908        Definition->getDescribedFunctionTemplate() ||
10909        Definition->getNumTemplateParameterLists())) {
10910     SkipBody->ShouldSkip = true;
10911     if (auto *TD = Definition->getDescribedFunctionTemplate())
10912       makeMergedDefinitionVisible(TD, FD->getLocation());
10913     else
10914       makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
10915                                   FD->getLocation());
10916     return;
10917   }
10918 
10919   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10920       Definition->getStorageClass() == SC_Extern)
10921     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10922         << FD->getDeclName() << getLangOpts().CPlusPlus;
10923   else
10924     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10925 
10926   Diag(Definition->getLocation(), diag::note_previous_definition);
10927   FD->setInvalidDecl();
10928 }
10929 
10930 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10931                                    Sema &S) {
10932   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10933 
10934   LambdaScopeInfo *LSI = S.PushLambdaScope();
10935   LSI->CallOperator = CallOperator;
10936   LSI->Lambda = LambdaClass;
10937   LSI->ReturnType = CallOperator->getReturnType();
10938   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10939 
10940   if (LCD == LCD_None)
10941     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10942   else if (LCD == LCD_ByCopy)
10943     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10944   else if (LCD == LCD_ByRef)
10945     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10946   DeclarationNameInfo DNI = CallOperator->getNameInfo();
10947 
10948   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
10949   LSI->Mutable = !CallOperator->isConst();
10950 
10951   // Add the captures to the LSI so they can be noted as already
10952   // captured within tryCaptureVar.
10953   auto I = LambdaClass->field_begin();
10954   for (const auto &C : LambdaClass->captures()) {
10955     if (C.capturesVariable()) {
10956       VarDecl *VD = C.getCapturedVar();
10957       if (VD->isInitCapture())
10958         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10959       QualType CaptureType = VD->getType();
10960       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10961       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
10962           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
10963           /*EllipsisLoc*/C.isPackExpansion()
10964                          ? C.getEllipsisLoc() : SourceLocation(),
10965           CaptureType, /*Expr*/ nullptr);
10966 
10967     } else if (C.capturesThis()) {
10968       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
10969                               S.getCurrentThisType(), /*Expr*/ nullptr);
10970     } else {
10971       LSI->addVLATypeCapture(C.getLocation(), I->getType());
10972     }
10973     ++I;
10974   }
10975 }
10976 
10977 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
10978                                     SkipBodyInfo *SkipBody) {
10979   // Clear the last template instantiation error context.
10980   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10981 
10982   if (!D)
10983     return D;
10984   FunctionDecl *FD = nullptr;
10985 
10986   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10987     FD = FunTmpl->getTemplatedDecl();
10988   else
10989     FD = cast<FunctionDecl>(D);
10990 
10991   // See if this is a redefinition.
10992   if (!FD->isLateTemplateParsed()) {
10993     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
10994 
10995     // If we're skipping the body, we're done. Don't enter the scope.
10996     if (SkipBody && SkipBody->ShouldSkip)
10997       return D;
10998   }
10999 
11000   // If we are instantiating a generic lambda call operator, push
11001   // a LambdaScopeInfo onto the function stack.  But use the information
11002   // that's already been calculated (ActOnLambdaExpr) to prime the current
11003   // LambdaScopeInfo.
11004   // When the template operator is being specialized, the LambdaScopeInfo,
11005   // has to be properly restored so that tryCaptureVariable doesn't try
11006   // and capture any new variables. In addition when calculating potential
11007   // captures during transformation of nested lambdas, it is necessary to
11008   // have the LSI properly restored.
11009   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11010     assert(ActiveTemplateInstantiations.size() &&
11011       "There should be an active template instantiation on the stack "
11012       "when instantiating a generic lambda!");
11013     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11014   }
11015   else
11016     // Enter a new function scope
11017     PushFunctionScope();
11018 
11019   // Builtin functions cannot be defined.
11020   if (unsigned BuiltinID = FD->getBuiltinID()) {
11021     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11022         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11023       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11024       FD->setInvalidDecl();
11025     }
11026   }
11027 
11028   // The return type of a function definition must be complete
11029   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11030   QualType ResultType = FD->getReturnType();
11031   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11032       !FD->isInvalidDecl() &&
11033       RequireCompleteType(FD->getLocation(), ResultType,
11034                           diag::err_func_def_incomplete_result))
11035     FD->setInvalidDecl();
11036 
11037   if (FnBodyScope)
11038     PushDeclContext(FnBodyScope, FD);
11039 
11040   // Check the validity of our function parameters
11041   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
11042                            /*CheckParameterNames=*/true);
11043 
11044   // Introduce our parameters into the function scope
11045   for (auto Param : FD->params()) {
11046     Param->setOwningFunction(FD);
11047 
11048     // If this has an identifier, add it to the scope stack.
11049     if (Param->getIdentifier() && FnBodyScope) {
11050       CheckShadow(FnBodyScope, Param);
11051 
11052       PushOnScopeChains(Param, FnBodyScope);
11053     }
11054   }
11055 
11056   // If we had any tags defined in the function prototype,
11057   // introduce them into the function scope.
11058   if (FnBodyScope) {
11059     for (ArrayRef<NamedDecl *>::iterator
11060              I = FD->getDeclsInPrototypeScope().begin(),
11061              E = FD->getDeclsInPrototypeScope().end();
11062          I != E; ++I) {
11063       NamedDecl *D = *I;
11064 
11065       // Some of these decls (like enums) may have been pinned to the
11066       // translation unit for lack of a real context earlier. If so, remove
11067       // from the translation unit and reattach to the current context.
11068       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
11069         // Is the decl actually in the context?
11070         if (Context.getTranslationUnitDecl()->containsDecl(D))
11071           Context.getTranslationUnitDecl()->removeDecl(D);
11072         // Either way, reassign the lexical decl context to our FunctionDecl.
11073         D->setLexicalDeclContext(CurContext);
11074       }
11075 
11076       // If the decl has a non-null name, make accessible in the current scope.
11077       if (!D->getName().empty())
11078         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
11079 
11080       // Similarly, dive into enums and fish their constants out, making them
11081       // accessible in this scope.
11082       if (auto *ED = dyn_cast<EnumDecl>(D)) {
11083         for (auto *EI : ED->enumerators())
11084           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11085       }
11086     }
11087   }
11088 
11089   // Ensure that the function's exception specification is instantiated.
11090   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11091     ResolveExceptionSpec(D->getLocation(), FPT);
11092 
11093   // dllimport cannot be applied to non-inline function definitions.
11094   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11095       !FD->isTemplateInstantiation()) {
11096     assert(!FD->hasAttr<DLLExportAttr>());
11097     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11098     FD->setInvalidDecl();
11099     return D;
11100   }
11101   // We want to attach documentation to original Decl (which might be
11102   // a function template).
11103   ActOnDocumentableDecl(D);
11104   if (getCurLexicalContext()->isObjCContainer() &&
11105       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11106       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11107     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11108 
11109   return D;
11110 }
11111 
11112 /// \brief Given the set of return statements within a function body,
11113 /// compute the variables that are subject to the named return value
11114 /// optimization.
11115 ///
11116 /// Each of the variables that is subject to the named return value
11117 /// optimization will be marked as NRVO variables in the AST, and any
11118 /// return statement that has a marked NRVO variable as its NRVO candidate can
11119 /// use the named return value optimization.
11120 ///
11121 /// This function applies a very simplistic algorithm for NRVO: if every return
11122 /// statement in the scope of a variable has the same NRVO candidate, that
11123 /// candidate is an NRVO variable.
11124 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11125   ReturnStmt **Returns = Scope->Returns.data();
11126 
11127   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11128     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11129       if (!NRVOCandidate->isNRVOVariable())
11130         Returns[I]->setNRVOCandidate(nullptr);
11131     }
11132   }
11133 }
11134 
11135 bool Sema::canDelayFunctionBody(const Declarator &D) {
11136   // We can't delay parsing the body of a constexpr function template (yet).
11137   if (D.getDeclSpec().isConstexprSpecified())
11138     return false;
11139 
11140   // We can't delay parsing the body of a function template with a deduced
11141   // return type (yet).
11142   if (D.getDeclSpec().containsPlaceholderType()) {
11143     // If the placeholder introduces a non-deduced trailing return type,
11144     // we can still delay parsing it.
11145     if (D.getNumTypeObjects()) {
11146       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11147       if (Outer.Kind == DeclaratorChunk::Function &&
11148           Outer.Fun.hasTrailingReturnType()) {
11149         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11150         return Ty.isNull() || !Ty->isUndeducedType();
11151       }
11152     }
11153     return false;
11154   }
11155 
11156   return true;
11157 }
11158 
11159 bool Sema::canSkipFunctionBody(Decl *D) {
11160   // We cannot skip the body of a function (or function template) which is
11161   // constexpr, since we may need to evaluate its body in order to parse the
11162   // rest of the file.
11163   // We cannot skip the body of a function with an undeduced return type,
11164   // because any callers of that function need to know the type.
11165   if (const FunctionDecl *FD = D->getAsFunction())
11166     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11167       return false;
11168   return Consumer.shouldSkipFunctionBody(D);
11169 }
11170 
11171 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11172   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11173     FD->setHasSkippedBody();
11174   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11175     MD->setHasSkippedBody();
11176   return ActOnFinishFunctionBody(Decl, nullptr);
11177 }
11178 
11179 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11180   return ActOnFinishFunctionBody(D, BodyArg, false);
11181 }
11182 
11183 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11184                                     bool IsInstantiation) {
11185   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11186 
11187   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11188   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11189 
11190   if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
11191     CheckCompletedCoroutineBody(FD, Body);
11192 
11193   if (FD) {
11194     FD->setBody(Body);
11195 
11196     if (getLangOpts().CPlusPlus14) {
11197       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11198           FD->getReturnType()->isUndeducedType()) {
11199         // If the function has a deduced result type but contains no 'return'
11200         // statements, the result type as written must be exactly 'auto', and
11201         // the deduced result type is 'void'.
11202         if (!FD->getReturnType()->getAs<AutoType>()) {
11203           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11204               << FD->getReturnType();
11205           FD->setInvalidDecl();
11206         } else {
11207           // Substitute 'void' for the 'auto' in the type.
11208           TypeLoc ResultType = getReturnTypeLoc(FD);
11209           Context.adjustDeducedFunctionResultType(
11210               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11211         }
11212       }
11213     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11214       // In C++11, we don't use 'auto' deduction rules for lambda call
11215       // operators because we don't support return type deduction.
11216       auto *LSI = getCurLambda();
11217       if (LSI->HasImplicitReturnType) {
11218         deduceClosureReturnType(*LSI);
11219 
11220         // C++11 [expr.prim.lambda]p4:
11221         //   [...] if there are no return statements in the compound-statement
11222         //   [the deduced type is] the type void
11223         QualType RetType =
11224             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11225 
11226         // Update the return type to the deduced type.
11227         const FunctionProtoType *Proto =
11228             FD->getType()->getAs<FunctionProtoType>();
11229         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11230                                             Proto->getExtProtoInfo()));
11231       }
11232     }
11233 
11234     // The only way to be included in UndefinedButUsed is if there is an
11235     // ODR use before the definition. Avoid the expensive map lookup if this
11236     // is the first declaration.
11237     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11238       if (!FD->isExternallyVisible())
11239         UndefinedButUsed.erase(FD);
11240       else if (FD->isInlined() &&
11241                !LangOpts.GNUInline &&
11242                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11243         UndefinedButUsed.erase(FD);
11244     }
11245 
11246     // If the function implicitly returns zero (like 'main') or is naked,
11247     // don't complain about missing return statements.
11248     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11249       WP.disableCheckFallThrough();
11250 
11251     // MSVC permits the use of pure specifier (=0) on function definition,
11252     // defined at class scope, warn about this non-standard construct.
11253     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11254       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11255 
11256     if (!FD->isInvalidDecl()) {
11257       // Don't diagnose unused parameters of defaulted or deleted functions.
11258       if (!FD->isDeleted() && !FD->isDefaulted())
11259         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
11260       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
11261                                              FD->getReturnType(), FD);
11262 
11263       // If this is a structor, we need a vtable.
11264       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11265         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11266       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11267         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11268 
11269       // Try to apply the named return value optimization. We have to check
11270       // if we can do this here because lambdas keep return statements around
11271       // to deduce an implicit return type.
11272       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11273           !FD->isDependentContext())
11274         computeNRVO(Body, getCurFunction());
11275     }
11276 
11277     // GNU warning -Wmissing-prototypes:
11278     //   Warn if a global function is defined without a previous
11279     //   prototype declaration. This warning is issued even if the
11280     //   definition itself provides a prototype. The aim is to detect
11281     //   global functions that fail to be declared in header files.
11282     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11283     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11284       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11285 
11286       if (PossibleZeroParamPrototype) {
11287         // We found a declaration that is not a prototype,
11288         // but that could be a zero-parameter prototype
11289         if (TypeSourceInfo *TI =
11290                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11291           TypeLoc TL = TI->getTypeLoc();
11292           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11293             Diag(PossibleZeroParamPrototype->getLocation(),
11294                  diag::note_declaration_not_a_prototype)
11295                 << PossibleZeroParamPrototype
11296                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11297         }
11298       }
11299     }
11300 
11301     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11302       const CXXMethodDecl *KeyFunction;
11303       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11304           MD->isVirtual() &&
11305           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11306           MD == KeyFunction->getCanonicalDecl()) {
11307         // Update the key-function state if necessary for this ABI.
11308         if (FD->isInlined() &&
11309             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11310           Context.setNonKeyFunction(MD);
11311 
11312           // If the newly-chosen key function is already defined, then we
11313           // need to mark the vtable as used retroactively.
11314           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11315           const FunctionDecl *Definition;
11316           if (KeyFunction && KeyFunction->isDefined(Definition))
11317             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11318         } else {
11319           // We just defined they key function; mark the vtable as used.
11320           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11321         }
11322       }
11323     }
11324 
11325     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11326            "Function parsing confused");
11327   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11328     assert(MD == getCurMethodDecl() && "Method parsing confused");
11329     MD->setBody(Body);
11330     if (!MD->isInvalidDecl()) {
11331       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
11332       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
11333                                              MD->getReturnType(), MD);
11334 
11335       if (Body)
11336         computeNRVO(Body, getCurFunction());
11337     }
11338     if (getCurFunction()->ObjCShouldCallSuper) {
11339       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11340         << MD->getSelector().getAsString();
11341       getCurFunction()->ObjCShouldCallSuper = false;
11342     }
11343     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11344       const ObjCMethodDecl *InitMethod = nullptr;
11345       bool isDesignated =
11346           MD->isDesignatedInitializerForTheInterface(&InitMethod);
11347       assert(isDesignated && InitMethod);
11348       (void)isDesignated;
11349 
11350       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11351         auto IFace = MD->getClassInterface();
11352         if (!IFace)
11353           return false;
11354         auto SuperD = IFace->getSuperClass();
11355         if (!SuperD)
11356           return false;
11357         return SuperD->getIdentifier() ==
11358             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11359       };
11360       // Don't issue this warning for unavailable inits or direct subclasses
11361       // of NSObject.
11362       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11363         Diag(MD->getLocation(),
11364              diag::warn_objc_designated_init_missing_super_call);
11365         Diag(InitMethod->getLocation(),
11366              diag::note_objc_designated_init_marked_here);
11367       }
11368       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11369     }
11370     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11371       // Don't issue this warning for unavaialable inits.
11372       if (!MD->isUnavailable())
11373         Diag(MD->getLocation(),
11374              diag::warn_objc_secondary_init_missing_init_call);
11375       getCurFunction()->ObjCWarnForNoInitDelegation = false;
11376     }
11377   } else {
11378     return nullptr;
11379   }
11380 
11381   assert(!getCurFunction()->ObjCShouldCallSuper &&
11382          "This should only be set for ObjC methods, which should have been "
11383          "handled in the block above.");
11384 
11385   // Verify and clean out per-function state.
11386   if (Body && (!FD || !FD->isDefaulted())) {
11387     // C++ constructors that have function-try-blocks can't have return
11388     // statements in the handlers of that block. (C++ [except.handle]p14)
11389     // Verify this.
11390     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11391       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11392 
11393     // Verify that gotos and switch cases don't jump into scopes illegally.
11394     if (getCurFunction()->NeedsScopeChecking() &&
11395         !PP.isCodeCompletionEnabled())
11396       DiagnoseInvalidJumps(Body);
11397 
11398     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11399       if (!Destructor->getParent()->isDependentType())
11400         CheckDestructor(Destructor);
11401 
11402       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11403                                              Destructor->getParent());
11404     }
11405 
11406     // If any errors have occurred, clear out any temporaries that may have
11407     // been leftover. This ensures that these temporaries won't be picked up for
11408     // deletion in some later function.
11409     if (getDiagnostics().hasErrorOccurred() ||
11410         getDiagnostics().getSuppressAllDiagnostics()) {
11411       DiscardCleanupsInEvaluationContext();
11412     }
11413     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11414         !isa<FunctionTemplateDecl>(dcl)) {
11415       // Since the body is valid, issue any analysis-based warnings that are
11416       // enabled.
11417       ActivePolicy = &WP;
11418     }
11419 
11420     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11421         (!CheckConstexprFunctionDecl(FD) ||
11422          !CheckConstexprFunctionBody(FD, Body)))
11423       FD->setInvalidDecl();
11424 
11425     if (FD && FD->hasAttr<NakedAttr>()) {
11426       for (const Stmt *S : Body->children()) {
11427         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11428           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11429           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11430           FD->setInvalidDecl();
11431           break;
11432         }
11433       }
11434     }
11435 
11436     assert(ExprCleanupObjects.size() ==
11437                ExprEvalContexts.back().NumCleanupObjects &&
11438            "Leftover temporaries in function");
11439     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
11440     assert(MaybeODRUseExprs.empty() &&
11441            "Leftover expressions for odr-use checking");
11442   }
11443 
11444   if (!IsInstantiation)
11445     PopDeclContext();
11446 
11447   PopFunctionScopeInfo(ActivePolicy, dcl);
11448   // If any errors have occurred, clear out any temporaries that may have
11449   // been leftover. This ensures that these temporaries won't be picked up for
11450   // deletion in some later function.
11451   if (getDiagnostics().hasErrorOccurred()) {
11452     DiscardCleanupsInEvaluationContext();
11453   }
11454 
11455   return dcl;
11456 }
11457 
11458 /// When we finish delayed parsing of an attribute, we must attach it to the
11459 /// relevant Decl.
11460 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11461                                        ParsedAttributes &Attrs) {
11462   // Always attach attributes to the underlying decl.
11463   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11464     D = TD->getTemplatedDecl();
11465   ProcessDeclAttributeList(S, D, Attrs.getList());
11466 
11467   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11468     if (Method->isStatic())
11469       checkThisInStaticMemberFunctionAttributes(Method);
11470 }
11471 
11472 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11473 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11474 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11475                                           IdentifierInfo &II, Scope *S) {
11476   // Before we produce a declaration for an implicitly defined
11477   // function, see whether there was a locally-scoped declaration of
11478   // this name as a function or variable. If so, use that
11479   // (non-visible) declaration, and complain about it.
11480   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11481     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11482     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11483     return ExternCPrev;
11484   }
11485 
11486   // Extension in C99.  Legal in C90, but warn about it.
11487   unsigned diag_id;
11488   if (II.getName().startswith("__builtin_"))
11489     diag_id = diag::warn_builtin_unknown;
11490   else if (getLangOpts().C99)
11491     diag_id = diag::ext_implicit_function_decl;
11492   else
11493     diag_id = diag::warn_implicit_function_decl;
11494   Diag(Loc, diag_id) << &II;
11495 
11496   // Because typo correction is expensive, only do it if the implicit
11497   // function declaration is going to be treated as an error.
11498   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11499     TypoCorrection Corrected;
11500     if (S &&
11501         (Corrected = CorrectTypo(
11502              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11503              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11504       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11505                    /*ErrorRecovery*/false);
11506   }
11507 
11508   // Set a Declarator for the implicit definition: int foo();
11509   const char *Dummy;
11510   AttributeFactory attrFactory;
11511   DeclSpec DS(attrFactory);
11512   unsigned DiagID;
11513   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11514                                   Context.getPrintingPolicy());
11515   (void)Error; // Silence warning.
11516   assert(!Error && "Error setting up implicit decl!");
11517   SourceLocation NoLoc;
11518   Declarator D(DS, Declarator::BlockContext);
11519   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11520                                              /*IsAmbiguous=*/false,
11521                                              /*LParenLoc=*/NoLoc,
11522                                              /*Params=*/nullptr,
11523                                              /*NumParams=*/0,
11524                                              /*EllipsisLoc=*/NoLoc,
11525                                              /*RParenLoc=*/NoLoc,
11526                                              /*TypeQuals=*/0,
11527                                              /*RefQualifierIsLvalueRef=*/true,
11528                                              /*RefQualifierLoc=*/NoLoc,
11529                                              /*ConstQualifierLoc=*/NoLoc,
11530                                              /*VolatileQualifierLoc=*/NoLoc,
11531                                              /*RestrictQualifierLoc=*/NoLoc,
11532                                              /*MutableLoc=*/NoLoc,
11533                                              EST_None,
11534                                              /*ESpecRange=*/SourceRange(),
11535                                              /*Exceptions=*/nullptr,
11536                                              /*ExceptionRanges=*/nullptr,
11537                                              /*NumExceptions=*/0,
11538                                              /*NoexceptExpr=*/nullptr,
11539                                              /*ExceptionSpecTokens=*/nullptr,
11540                                              Loc, Loc, D),
11541                 DS.getAttributes(),
11542                 SourceLocation());
11543   D.SetIdentifier(&II, Loc);
11544 
11545   // Insert this function into translation-unit scope.
11546 
11547   DeclContext *PrevDC = CurContext;
11548   CurContext = Context.getTranslationUnitDecl();
11549 
11550   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11551   FD->setImplicit();
11552 
11553   CurContext = PrevDC;
11554 
11555   AddKnownFunctionAttributes(FD);
11556 
11557   return FD;
11558 }
11559 
11560 /// \brief Adds any function attributes that we know a priori based on
11561 /// the declaration of this function.
11562 ///
11563 /// These attributes can apply both to implicitly-declared builtins
11564 /// (like __builtin___printf_chk) or to library-declared functions
11565 /// like NSLog or printf.
11566 ///
11567 /// We need to check for duplicate attributes both here and where user-written
11568 /// attributes are applied to declarations.
11569 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11570   if (FD->isInvalidDecl())
11571     return;
11572 
11573   // If this is a built-in function, map its builtin attributes to
11574   // actual attributes.
11575   if (unsigned BuiltinID = FD->getBuiltinID()) {
11576     // Handle printf-formatting attributes.
11577     unsigned FormatIdx;
11578     bool HasVAListArg;
11579     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11580       if (!FD->hasAttr<FormatAttr>()) {
11581         const char *fmt = "printf";
11582         unsigned int NumParams = FD->getNumParams();
11583         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11584             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11585           fmt = "NSString";
11586         FD->addAttr(FormatAttr::CreateImplicit(Context,
11587                                                &Context.Idents.get(fmt),
11588                                                FormatIdx+1,
11589                                                HasVAListArg ? 0 : FormatIdx+2,
11590                                                FD->getLocation()));
11591       }
11592     }
11593     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11594                                              HasVAListArg)) {
11595      if (!FD->hasAttr<FormatAttr>())
11596        FD->addAttr(FormatAttr::CreateImplicit(Context,
11597                                               &Context.Idents.get("scanf"),
11598                                               FormatIdx+1,
11599                                               HasVAListArg ? 0 : FormatIdx+2,
11600                                               FD->getLocation()));
11601     }
11602 
11603     // Mark const if we don't care about errno and that is the only
11604     // thing preventing the function from being const. This allows
11605     // IRgen to use LLVM intrinsics for such functions.
11606     if (!getLangOpts().MathErrno &&
11607         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11608       if (!FD->hasAttr<ConstAttr>())
11609         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11610     }
11611 
11612     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11613         !FD->hasAttr<ReturnsTwiceAttr>())
11614       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11615                                          FD->getLocation()));
11616     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11617       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11618     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11619       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11620     if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads &&
11621         Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11622         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11623       // Assign appropriate attribute depending on CUDA compilation
11624       // mode and the target builtin belongs to. E.g. during host
11625       // compilation, aux builtins are __device__, the rest are __host__.
11626       if (getLangOpts().CUDAIsDevice !=
11627           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11628         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11629       else
11630         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11631     }
11632   }
11633 
11634   // If C++ exceptions are enabled but we are told extern "C" functions cannot
11635   // throw, add an implicit nothrow attribute to any extern "C" function we come
11636   // across.
11637   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
11638       FD->isExternC() && !FD->hasAttr<NoThrowAttr>())
11639     FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11640 
11641   IdentifierInfo *Name = FD->getIdentifier();
11642   if (!Name)
11643     return;
11644   if ((!getLangOpts().CPlusPlus &&
11645        FD->getDeclContext()->isTranslationUnit()) ||
11646       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11647        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11648        LinkageSpecDecl::lang_c)) {
11649     // Okay: this could be a libc/libm/Objective-C function we know
11650     // about.
11651   } else
11652     return;
11653 
11654   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11655     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11656     // target-specific builtins, perhaps?
11657     if (!FD->hasAttr<FormatAttr>())
11658       FD->addAttr(FormatAttr::CreateImplicit(Context,
11659                                              &Context.Idents.get("printf"), 2,
11660                                              Name->isStr("vasprintf") ? 0 : 3,
11661                                              FD->getLocation()));
11662   }
11663 
11664   if (Name->isStr("__CFStringMakeConstantString")) {
11665     // We already have a __builtin___CFStringMakeConstantString,
11666     // but builds that use -fno-constant-cfstrings don't go through that.
11667     if (!FD->hasAttr<FormatArgAttr>())
11668       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11669                                                 FD->getLocation()));
11670   }
11671 }
11672 
11673 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11674                                     TypeSourceInfo *TInfo) {
11675   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11676   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11677 
11678   if (!TInfo) {
11679     assert(D.isInvalidType() && "no declarator info for valid type");
11680     TInfo = Context.getTrivialTypeSourceInfo(T);
11681   }
11682 
11683   // Scope manipulation handled by caller.
11684   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11685                                            D.getLocStart(),
11686                                            D.getIdentifierLoc(),
11687                                            D.getIdentifier(),
11688                                            TInfo);
11689 
11690   // Bail out immediately if we have an invalid declaration.
11691   if (D.isInvalidType()) {
11692     NewTD->setInvalidDecl();
11693     return NewTD;
11694   }
11695 
11696   if (D.getDeclSpec().isModulePrivateSpecified()) {
11697     if (CurContext->isFunctionOrMethod())
11698       Diag(NewTD->getLocation(), diag::err_module_private_local)
11699         << 2 << NewTD->getDeclName()
11700         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11701         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11702     else
11703       NewTD->setModulePrivate();
11704   }
11705 
11706   // C++ [dcl.typedef]p8:
11707   //   If the typedef declaration defines an unnamed class (or
11708   //   enum), the first typedef-name declared by the declaration
11709   //   to be that class type (or enum type) is used to denote the
11710   //   class type (or enum type) for linkage purposes only.
11711   // We need to check whether the type was declared in the declaration.
11712   switch (D.getDeclSpec().getTypeSpecType()) {
11713   case TST_enum:
11714   case TST_struct:
11715   case TST_interface:
11716   case TST_union:
11717   case TST_class: {
11718     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11719     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11720     break;
11721   }
11722 
11723   default:
11724     break;
11725   }
11726 
11727   return NewTD;
11728 }
11729 
11730 /// \brief Check that this is a valid underlying type for an enum declaration.
11731 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11732   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11733   QualType T = TI->getType();
11734 
11735   if (T->isDependentType())
11736     return false;
11737 
11738   if (const BuiltinType *BT = T->getAs<BuiltinType>())
11739     if (BT->isInteger())
11740       return false;
11741 
11742   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11743   return true;
11744 }
11745 
11746 /// Check whether this is a valid redeclaration of a previous enumeration.
11747 /// \return true if the redeclaration was invalid.
11748 bool Sema::CheckEnumRedeclaration(
11749     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
11750     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
11751   bool IsFixed = !EnumUnderlyingTy.isNull();
11752 
11753   if (IsScoped != Prev->isScoped()) {
11754     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11755       << Prev->isScoped();
11756     Diag(Prev->getLocation(), diag::note_previous_declaration);
11757     return true;
11758   }
11759 
11760   if (IsFixed && Prev->isFixed()) {
11761     if (!EnumUnderlyingTy->isDependentType() &&
11762         !Prev->getIntegerType()->isDependentType() &&
11763         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11764                                         Prev->getIntegerType())) {
11765       // TODO: Highlight the underlying type of the redeclaration.
11766       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11767         << EnumUnderlyingTy << Prev->getIntegerType();
11768       Diag(Prev->getLocation(), diag::note_previous_declaration)
11769           << Prev->getIntegerTypeRange();
11770       return true;
11771     }
11772   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
11773     ;
11774   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
11775     ;
11776   } else if (IsFixed != Prev->isFixed()) {
11777     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11778       << Prev->isFixed();
11779     Diag(Prev->getLocation(), diag::note_previous_declaration);
11780     return true;
11781   }
11782 
11783   return false;
11784 }
11785 
11786 /// \brief Get diagnostic %select index for tag kind for
11787 /// redeclaration diagnostic message.
11788 /// WARNING: Indexes apply to particular diagnostics only!
11789 ///
11790 /// \returns diagnostic %select index.
11791 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
11792   switch (Tag) {
11793   case TTK_Struct: return 0;
11794   case TTK_Interface: return 1;
11795   case TTK_Class:  return 2;
11796   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11797   }
11798 }
11799 
11800 /// \brief Determine if tag kind is a class-key compatible with
11801 /// class for redeclaration (class, struct, or __interface).
11802 ///
11803 /// \returns true iff the tag kind is compatible.
11804 static bool isClassCompatTagKind(TagTypeKind Tag)
11805 {
11806   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11807 }
11808 
11809 /// \brief Determine whether a tag with a given kind is acceptable
11810 /// as a redeclaration of the given tag declaration.
11811 ///
11812 /// \returns true if the new tag kind is acceptable, false otherwise.
11813 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11814                                         TagTypeKind NewTag, bool isDefinition,
11815                                         SourceLocation NewTagLoc,
11816                                         const IdentifierInfo *Name) {
11817   // C++ [dcl.type.elab]p3:
11818   //   The class-key or enum keyword present in the
11819   //   elaborated-type-specifier shall agree in kind with the
11820   //   declaration to which the name in the elaborated-type-specifier
11821   //   refers. This rule also applies to the form of
11822   //   elaborated-type-specifier that declares a class-name or
11823   //   friend class since it can be construed as referring to the
11824   //   definition of the class. Thus, in any
11825   //   elaborated-type-specifier, the enum keyword shall be used to
11826   //   refer to an enumeration (7.2), the union class-key shall be
11827   //   used to refer to a union (clause 9), and either the class or
11828   //   struct class-key shall be used to refer to a class (clause 9)
11829   //   declared using the class or struct class-key.
11830   TagTypeKind OldTag = Previous->getTagKind();
11831   if (!isDefinition || !isClassCompatTagKind(NewTag))
11832     if (OldTag == NewTag)
11833       return true;
11834 
11835   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11836     // Warn about the struct/class tag mismatch.
11837     bool isTemplate = false;
11838     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11839       isTemplate = Record->getDescribedClassTemplate();
11840 
11841     if (!ActiveTemplateInstantiations.empty()) {
11842       // In a template instantiation, do not offer fix-its for tag mismatches
11843       // since they usually mess up the template instead of fixing the problem.
11844       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11845         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11846         << getRedeclDiagFromTagKind(OldTag);
11847       return true;
11848     }
11849 
11850     if (isDefinition) {
11851       // On definitions, check previous tags and issue a fix-it for each
11852       // one that doesn't match the current tag.
11853       if (Previous->getDefinition()) {
11854         // Don't suggest fix-its for redefinitions.
11855         return true;
11856       }
11857 
11858       bool previousMismatch = false;
11859       for (auto I : Previous->redecls()) {
11860         if (I->getTagKind() != NewTag) {
11861           if (!previousMismatch) {
11862             previousMismatch = true;
11863             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11864               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11865               << getRedeclDiagFromTagKind(I->getTagKind());
11866           }
11867           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11868             << getRedeclDiagFromTagKind(NewTag)
11869             << FixItHint::CreateReplacement(I->getInnerLocStart(),
11870                  TypeWithKeyword::getTagTypeKindName(NewTag));
11871         }
11872       }
11873       return true;
11874     }
11875 
11876     // Check for a previous definition.  If current tag and definition
11877     // are same type, do nothing.  If no definition, but disagree with
11878     // with previous tag type, give a warning, but no fix-it.
11879     const TagDecl *Redecl = Previous->getDefinition() ?
11880                             Previous->getDefinition() : Previous;
11881     if (Redecl->getTagKind() == NewTag) {
11882       return true;
11883     }
11884 
11885     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11886       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11887       << getRedeclDiagFromTagKind(OldTag);
11888     Diag(Redecl->getLocation(), diag::note_previous_use);
11889 
11890     // If there is a previous definition, suggest a fix-it.
11891     if (Previous->getDefinition()) {
11892         Diag(NewTagLoc, diag::note_struct_class_suggestion)
11893           << getRedeclDiagFromTagKind(Redecl->getTagKind())
11894           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11895                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11896     }
11897 
11898     return true;
11899   }
11900   return false;
11901 }
11902 
11903 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11904 /// from an outer enclosing namespace or file scope inside a friend declaration.
11905 /// This should provide the commented out code in the following snippet:
11906 ///   namespace N {
11907 ///     struct X;
11908 ///     namespace M {
11909 ///       struct Y { friend struct /*N::*/ X; };
11910 ///     }
11911 ///   }
11912 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11913                                          SourceLocation NameLoc) {
11914   // While the decl is in a namespace, do repeated lookup of that name and see
11915   // if we get the same namespace back.  If we do not, continue until
11916   // translation unit scope, at which point we have a fully qualified NNS.
11917   SmallVector<IdentifierInfo *, 4> Namespaces;
11918   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11919   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11920     // This tag should be declared in a namespace, which can only be enclosed by
11921     // other namespaces.  Bail if there's an anonymous namespace in the chain.
11922     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11923     if (!Namespace || Namespace->isAnonymousNamespace())
11924       return FixItHint();
11925     IdentifierInfo *II = Namespace->getIdentifier();
11926     Namespaces.push_back(II);
11927     NamedDecl *Lookup = SemaRef.LookupSingleName(
11928         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11929     if (Lookup == Namespace)
11930       break;
11931   }
11932 
11933   // Once we have all the namespaces, reverse them to go outermost first, and
11934   // build an NNS.
11935   SmallString<64> Insertion;
11936   llvm::raw_svector_ostream OS(Insertion);
11937   if (DC->isTranslationUnit())
11938     OS << "::";
11939   std::reverse(Namespaces.begin(), Namespaces.end());
11940   for (auto *II : Namespaces)
11941     OS << II->getName() << "::";
11942   return FixItHint::CreateInsertion(NameLoc, Insertion);
11943 }
11944 
11945 /// \brief Determine whether a tag originally declared in context \p OldDC can
11946 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
11947 /// found a declaration in \p OldDC as a previous decl, perhaps through a
11948 /// using-declaration).
11949 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
11950                                          DeclContext *NewDC) {
11951   OldDC = OldDC->getRedeclContext();
11952   NewDC = NewDC->getRedeclContext();
11953 
11954   if (OldDC->Equals(NewDC))
11955     return true;
11956 
11957   // In MSVC mode, we allow a redeclaration if the contexts are related (either
11958   // encloses the other).
11959   if (S.getLangOpts().MSVCCompat &&
11960       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
11961     return true;
11962 
11963   return false;
11964 }
11965 
11966 /// Find the DeclContext in which a tag is implicitly declared if we see an
11967 /// elaborated type specifier in the specified context, and lookup finds
11968 /// nothing.
11969 static DeclContext *getTagInjectionContext(DeclContext *DC) {
11970   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
11971     DC = DC->getParent();
11972   return DC;
11973 }
11974 
11975 /// Find the Scope in which a tag is implicitly declared if we see an
11976 /// elaborated type specifier in the specified context, and lookup finds
11977 /// nothing.
11978 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
11979   while (S->isClassScope() ||
11980          (LangOpts.CPlusPlus &&
11981           S->isFunctionPrototypeScope()) ||
11982          ((S->getFlags() & Scope::DeclScope) == 0) ||
11983          (S->getEntity() && S->getEntity()->isTransparentContext()))
11984     S = S->getParent();
11985   return S;
11986 }
11987 
11988 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
11989 /// former case, Name will be non-null.  In the later case, Name will be null.
11990 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
11991 /// reference/declaration/definition of a tag.
11992 ///
11993 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
11994 /// trailing-type-specifier) other than one in an alias-declaration.
11995 ///
11996 /// \param SkipBody If non-null, will be set to indicate if the caller should
11997 /// skip the definition of this tag and treat it as if it were a declaration.
11998 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11999                      SourceLocation KWLoc, CXXScopeSpec &SS,
12000                      IdentifierInfo *Name, SourceLocation NameLoc,
12001                      AttributeList *Attr, AccessSpecifier AS,
12002                      SourceLocation ModulePrivateLoc,
12003                      MultiTemplateParamsArg TemplateParameterLists,
12004                      bool &OwnedDecl, bool &IsDependent,
12005                      SourceLocation ScopedEnumKWLoc,
12006                      bool ScopedEnumUsesClassTag,
12007                      TypeResult UnderlyingType,
12008                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12009   // If this is not a definition, it must have a name.
12010   IdentifierInfo *OrigName = Name;
12011   assert((Name != nullptr || TUK == TUK_Definition) &&
12012          "Nameless record must be a definition!");
12013   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12014 
12015   OwnedDecl = false;
12016   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12017   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12018 
12019   // FIXME: Check explicit specializations more carefully.
12020   bool isExplicitSpecialization = false;
12021   bool Invalid = false;
12022 
12023   // We only need to do this matching if we have template parameters
12024   // or a scope specifier, which also conveniently avoids this work
12025   // for non-C++ cases.
12026   if (TemplateParameterLists.size() > 0 ||
12027       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12028     if (TemplateParameterList *TemplateParams =
12029             MatchTemplateParametersToScopeSpecifier(
12030                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12031                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12032       if (Kind == TTK_Enum) {
12033         Diag(KWLoc, diag::err_enum_template);
12034         return nullptr;
12035       }
12036 
12037       if (TemplateParams->size() > 0) {
12038         // This is a declaration or definition of a class template (which may
12039         // be a member of another template).
12040 
12041         if (Invalid)
12042           return nullptr;
12043 
12044         OwnedDecl = false;
12045         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12046                                                SS, Name, NameLoc, Attr,
12047                                                TemplateParams, AS,
12048                                                ModulePrivateLoc,
12049                                                /*FriendLoc*/SourceLocation(),
12050                                                TemplateParameterLists.size()-1,
12051                                                TemplateParameterLists.data(),
12052                                                SkipBody);
12053         return Result.get();
12054       } else {
12055         // The "template<>" header is extraneous.
12056         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12057           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12058         isExplicitSpecialization = true;
12059       }
12060     }
12061   }
12062 
12063   // Figure out the underlying type if this a enum declaration. We need to do
12064   // this early, because it's needed to detect if this is an incompatible
12065   // redeclaration.
12066   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12067   bool EnumUnderlyingIsImplicit = false;
12068 
12069   if (Kind == TTK_Enum) {
12070     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12071       // No underlying type explicitly specified, or we failed to parse the
12072       // type, default to int.
12073       EnumUnderlying = Context.IntTy.getTypePtr();
12074     else if (UnderlyingType.get()) {
12075       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12076       // integral type; any cv-qualification is ignored.
12077       TypeSourceInfo *TI = nullptr;
12078       GetTypeFromParser(UnderlyingType.get(), &TI);
12079       EnumUnderlying = TI;
12080 
12081       if (CheckEnumUnderlyingType(TI))
12082         // Recover by falling back to int.
12083         EnumUnderlying = Context.IntTy.getTypePtr();
12084 
12085       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12086                                           UPPC_FixedUnderlyingType))
12087         EnumUnderlying = Context.IntTy.getTypePtr();
12088 
12089     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12090       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12091         // Microsoft enums are always of int type.
12092         EnumUnderlying = Context.IntTy.getTypePtr();
12093         EnumUnderlyingIsImplicit = true;
12094       }
12095     }
12096   }
12097 
12098   DeclContext *SearchDC = CurContext;
12099   DeclContext *DC = CurContext;
12100   bool isStdBadAlloc = false;
12101 
12102   RedeclarationKind Redecl = ForRedeclaration;
12103   if (TUK == TUK_Friend || TUK == TUK_Reference)
12104     Redecl = NotForRedeclaration;
12105 
12106   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12107   if (Name && SS.isNotEmpty()) {
12108     // We have a nested-name tag ('struct foo::bar').
12109 
12110     // Check for invalid 'foo::'.
12111     if (SS.isInvalid()) {
12112       Name = nullptr;
12113       goto CreateNewDecl;
12114     }
12115 
12116     // If this is a friend or a reference to a class in a dependent
12117     // context, don't try to make a decl for it.
12118     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12119       DC = computeDeclContext(SS, false);
12120       if (!DC) {
12121         IsDependent = true;
12122         return nullptr;
12123       }
12124     } else {
12125       DC = computeDeclContext(SS, true);
12126       if (!DC) {
12127         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12128           << SS.getRange();
12129         return nullptr;
12130       }
12131     }
12132 
12133     if (RequireCompleteDeclContext(SS, DC))
12134       return nullptr;
12135 
12136     SearchDC = DC;
12137     // Look-up name inside 'foo::'.
12138     LookupQualifiedName(Previous, DC);
12139 
12140     if (Previous.isAmbiguous())
12141       return nullptr;
12142 
12143     if (Previous.empty()) {
12144       // Name lookup did not find anything. However, if the
12145       // nested-name-specifier refers to the current instantiation,
12146       // and that current instantiation has any dependent base
12147       // classes, we might find something at instantiation time: treat
12148       // this as a dependent elaborated-type-specifier.
12149       // But this only makes any sense for reference-like lookups.
12150       if (Previous.wasNotFoundInCurrentInstantiation() &&
12151           (TUK == TUK_Reference || TUK == TUK_Friend)) {
12152         IsDependent = true;
12153         return nullptr;
12154       }
12155 
12156       // A tag 'foo::bar' must already exist.
12157       Diag(NameLoc, diag::err_not_tag_in_scope)
12158         << Kind << Name << DC << SS.getRange();
12159       Name = nullptr;
12160       Invalid = true;
12161       goto CreateNewDecl;
12162     }
12163   } else if (Name) {
12164     // C++14 [class.mem]p14:
12165     //   If T is the name of a class, then each of the following shall have a
12166     //   name different from T:
12167     //    -- every member of class T that is itself a type
12168     if (TUK != TUK_Reference && TUK != TUK_Friend &&
12169         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12170       return nullptr;
12171 
12172     // If this is a named struct, check to see if there was a previous forward
12173     // declaration or definition.
12174     // FIXME: We're looking into outer scopes here, even when we
12175     // shouldn't be. Doing so can result in ambiguities that we
12176     // shouldn't be diagnosing.
12177     LookupName(Previous, S);
12178 
12179     // When declaring or defining a tag, ignore ambiguities introduced
12180     // by types using'ed into this scope.
12181     if (Previous.isAmbiguous() &&
12182         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12183       LookupResult::Filter F = Previous.makeFilter();
12184       while (F.hasNext()) {
12185         NamedDecl *ND = F.next();
12186         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
12187           F.erase();
12188       }
12189       F.done();
12190     }
12191 
12192     // C++11 [namespace.memdef]p3:
12193     //   If the name in a friend declaration is neither qualified nor
12194     //   a template-id and the declaration is a function or an
12195     //   elaborated-type-specifier, the lookup to determine whether
12196     //   the entity has been previously declared shall not consider
12197     //   any scopes outside the innermost enclosing namespace.
12198     //
12199     // MSVC doesn't implement the above rule for types, so a friend tag
12200     // declaration may be a redeclaration of a type declared in an enclosing
12201     // scope.  They do implement this rule for friend functions.
12202     //
12203     // Does it matter that this should be by scope instead of by
12204     // semantic context?
12205     if (!Previous.empty() && TUK == TUK_Friend) {
12206       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12207       LookupResult::Filter F = Previous.makeFilter();
12208       bool FriendSawTagOutsideEnclosingNamespace = false;
12209       while (F.hasNext()) {
12210         NamedDecl *ND = F.next();
12211         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12212         if (DC->isFileContext() &&
12213             !EnclosingNS->Encloses(ND->getDeclContext())) {
12214           if (getLangOpts().MSVCCompat)
12215             FriendSawTagOutsideEnclosingNamespace = true;
12216           else
12217             F.erase();
12218         }
12219       }
12220       F.done();
12221 
12222       // Diagnose this MSVC extension in the easy case where lookup would have
12223       // unambiguously found something outside the enclosing namespace.
12224       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12225         NamedDecl *ND = Previous.getFoundDecl();
12226         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12227             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12228       }
12229     }
12230 
12231     // Note:  there used to be some attempt at recovery here.
12232     if (Previous.isAmbiguous())
12233       return nullptr;
12234 
12235     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12236       // FIXME: This makes sure that we ignore the contexts associated
12237       // with C structs, unions, and enums when looking for a matching
12238       // tag declaration or definition. See the similar lookup tweak
12239       // in Sema::LookupName; is there a better way to deal with this?
12240       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12241         SearchDC = SearchDC->getParent();
12242     }
12243   }
12244 
12245   if (Previous.isSingleResult() &&
12246       Previous.getFoundDecl()->isTemplateParameter()) {
12247     // Maybe we will complain about the shadowed template parameter.
12248     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12249     // Just pretend that we didn't see the previous declaration.
12250     Previous.clear();
12251   }
12252 
12253   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12254       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12255     // This is a declaration of or a reference to "std::bad_alloc".
12256     isStdBadAlloc = true;
12257 
12258     if (Previous.empty() && StdBadAlloc) {
12259       // std::bad_alloc has been implicitly declared (but made invisible to
12260       // name lookup). Fill in this implicit declaration as the previous
12261       // declaration, so that the declarations get chained appropriately.
12262       Previous.addDecl(getStdBadAlloc());
12263     }
12264   }
12265 
12266   // If we didn't find a previous declaration, and this is a reference
12267   // (or friend reference), move to the correct scope.  In C++, we
12268   // also need to do a redeclaration lookup there, just in case
12269   // there's a shadow friend decl.
12270   if (Name && Previous.empty() &&
12271       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12272     if (Invalid) goto CreateNewDecl;
12273     assert(SS.isEmpty());
12274 
12275     if (TUK == TUK_Reference) {
12276       // C++ [basic.scope.pdecl]p5:
12277       //   -- for an elaborated-type-specifier of the form
12278       //
12279       //          class-key identifier
12280       //
12281       //      if the elaborated-type-specifier is used in the
12282       //      decl-specifier-seq or parameter-declaration-clause of a
12283       //      function defined in namespace scope, the identifier is
12284       //      declared as a class-name in the namespace that contains
12285       //      the declaration; otherwise, except as a friend
12286       //      declaration, the identifier is declared in the smallest
12287       //      non-class, non-function-prototype scope that contains the
12288       //      declaration.
12289       //
12290       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12291       // C structs and unions.
12292       //
12293       // It is an error in C++ to declare (rather than define) an enum
12294       // type, including via an elaborated type specifier.  We'll
12295       // diagnose that later; for now, declare the enum in the same
12296       // scope as we would have picked for any other tag type.
12297       //
12298       // GNU C also supports this behavior as part of its incomplete
12299       // enum types extension, while GNU C++ does not.
12300       //
12301       // Find the context where we'll be declaring the tag.
12302       // FIXME: We would like to maintain the current DeclContext as the
12303       // lexical context,
12304       SearchDC = getTagInjectionContext(SearchDC);
12305 
12306       // Find the scope where we'll be declaring the tag.
12307       S = getTagInjectionScope(S, getLangOpts());
12308     } else {
12309       assert(TUK == TUK_Friend);
12310       // C++ [namespace.memdef]p3:
12311       //   If a friend declaration in a non-local class first declares a
12312       //   class or function, the friend class or function is a member of
12313       //   the innermost enclosing namespace.
12314       SearchDC = SearchDC->getEnclosingNamespaceContext();
12315     }
12316 
12317     // In C++, we need to do a redeclaration lookup to properly
12318     // diagnose some problems.
12319     // FIXME: redeclaration lookup is also used (with and without C++) to find a
12320     // hidden declaration so that we don't get ambiguity errors when using a
12321     // type declared by an elaborated-type-specifier.  In C that is not correct
12322     // and we should instead merge compatible types found by lookup.
12323     if (getLangOpts().CPlusPlus) {
12324       Previous.setRedeclarationKind(ForRedeclaration);
12325       LookupQualifiedName(Previous, SearchDC);
12326     } else {
12327       Previous.setRedeclarationKind(ForRedeclaration);
12328       LookupName(Previous, S);
12329     }
12330   }
12331 
12332   // If we have a known previous declaration to use, then use it.
12333   if (Previous.empty() && SkipBody && SkipBody->Previous)
12334     Previous.addDecl(SkipBody->Previous);
12335 
12336   if (!Previous.empty()) {
12337     NamedDecl *PrevDecl = Previous.getFoundDecl();
12338     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12339 
12340     // It's okay to have a tag decl in the same scope as a typedef
12341     // which hides a tag decl in the same scope.  Finding this
12342     // insanity with a redeclaration lookup can only actually happen
12343     // in C++.
12344     //
12345     // This is also okay for elaborated-type-specifiers, which is
12346     // technically forbidden by the current standard but which is
12347     // okay according to the likely resolution of an open issue;
12348     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12349     if (getLangOpts().CPlusPlus) {
12350       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12351         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12352           TagDecl *Tag = TT->getDecl();
12353           if (Tag->getDeclName() == Name &&
12354               Tag->getDeclContext()->getRedeclContext()
12355                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
12356             PrevDecl = Tag;
12357             Previous.clear();
12358             Previous.addDecl(Tag);
12359             Previous.resolveKind();
12360           }
12361         }
12362       }
12363     }
12364 
12365     // If this is a redeclaration of a using shadow declaration, it must
12366     // declare a tag in the same context. In MSVC mode, we allow a
12367     // redefinition if either context is within the other.
12368     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12369       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12370       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12371           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12372           !(OldTag && isAcceptableTagRedeclContext(
12373                           *this, OldTag->getDeclContext(), SearchDC))) {
12374         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12375         Diag(Shadow->getTargetDecl()->getLocation(),
12376              diag::note_using_decl_target);
12377         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12378             << 0;
12379         // Recover by ignoring the old declaration.
12380         Previous.clear();
12381         goto CreateNewDecl;
12382       }
12383     }
12384 
12385     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12386       // If this is a use of a previous tag, or if the tag is already declared
12387       // in the same scope (so that the definition/declaration completes or
12388       // rementions the tag), reuse the decl.
12389       if (TUK == TUK_Reference || TUK == TUK_Friend ||
12390           isDeclInScope(DirectPrevDecl, SearchDC, S,
12391                         SS.isNotEmpty() || isExplicitSpecialization)) {
12392         // Make sure that this wasn't declared as an enum and now used as a
12393         // struct or something similar.
12394         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12395                                           TUK == TUK_Definition, KWLoc,
12396                                           Name)) {
12397           bool SafeToContinue
12398             = (PrevTagDecl->getTagKind() != TTK_Enum &&
12399                Kind != TTK_Enum);
12400           if (SafeToContinue)
12401             Diag(KWLoc, diag::err_use_with_wrong_tag)
12402               << Name
12403               << FixItHint::CreateReplacement(SourceRange(KWLoc),
12404                                               PrevTagDecl->getKindName());
12405           else
12406             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12407           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12408 
12409           if (SafeToContinue)
12410             Kind = PrevTagDecl->getTagKind();
12411           else {
12412             // Recover by making this an anonymous redefinition.
12413             Name = nullptr;
12414             Previous.clear();
12415             Invalid = true;
12416           }
12417         }
12418 
12419         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12420           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12421 
12422           // If this is an elaborated-type-specifier for a scoped enumeration,
12423           // the 'class' keyword is not necessary and not permitted.
12424           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12425             if (ScopedEnum)
12426               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12427                 << PrevEnum->isScoped()
12428                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12429             return PrevTagDecl;
12430           }
12431 
12432           QualType EnumUnderlyingTy;
12433           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12434             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12435           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12436             EnumUnderlyingTy = QualType(T, 0);
12437 
12438           // All conflicts with previous declarations are recovered by
12439           // returning the previous declaration, unless this is a definition,
12440           // in which case we want the caller to bail out.
12441           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12442                                      ScopedEnum, EnumUnderlyingTy,
12443                                      EnumUnderlyingIsImplicit, PrevEnum))
12444             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12445         }
12446 
12447         // C++11 [class.mem]p1:
12448         //   A member shall not be declared twice in the member-specification,
12449         //   except that a nested class or member class template can be declared
12450         //   and then later defined.
12451         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12452             S->isDeclScope(PrevDecl)) {
12453           Diag(NameLoc, diag::ext_member_redeclared);
12454           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12455         }
12456 
12457         if (!Invalid) {
12458           // If this is a use, just return the declaration we found, unless
12459           // we have attributes.
12460           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12461             if (Attr) {
12462               // FIXME: Diagnose these attributes. For now, we create a new
12463               // declaration to hold them.
12464             } else if (TUK == TUK_Reference &&
12465                        (PrevTagDecl->getFriendObjectKind() ==
12466                             Decl::FOK_Undeclared ||
12467                         PP.getModuleContainingLocation(
12468                             PrevDecl->getLocation()) !=
12469                             PP.getModuleContainingLocation(KWLoc)) &&
12470                        SS.isEmpty()) {
12471               // This declaration is a reference to an existing entity, but
12472               // has different visibility from that entity: it either makes
12473               // a friend visible or it makes a type visible in a new module.
12474               // In either case, create a new declaration. We only do this if
12475               // the declaration would have meant the same thing if no prior
12476               // declaration were found, that is, if it was found in the same
12477               // scope where we would have injected a declaration.
12478               if (!getTagInjectionContext(CurContext)->getRedeclContext()
12479                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
12480                 return PrevTagDecl;
12481               // This is in the injected scope, create a new declaration in
12482               // that scope.
12483               S = getTagInjectionScope(S, getLangOpts());
12484             } else {
12485               return PrevTagDecl;
12486             }
12487           }
12488 
12489           // Diagnose attempts to redefine a tag.
12490           if (TUK == TUK_Definition) {
12491             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12492               // If we're defining a specialization and the previous definition
12493               // is from an implicit instantiation, don't emit an error
12494               // here; we'll catch this in the general case below.
12495               bool IsExplicitSpecializationAfterInstantiation = false;
12496               if (isExplicitSpecialization) {
12497                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12498                   IsExplicitSpecializationAfterInstantiation =
12499                     RD->getTemplateSpecializationKind() !=
12500                     TSK_ExplicitSpecialization;
12501                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12502                   IsExplicitSpecializationAfterInstantiation =
12503                     ED->getTemplateSpecializationKind() !=
12504                     TSK_ExplicitSpecialization;
12505               }
12506 
12507               NamedDecl *Hidden = nullptr;
12508               if (SkipBody && getLangOpts().CPlusPlus &&
12509                   !hasVisibleDefinition(Def, &Hidden)) {
12510                 // There is a definition of this tag, but it is not visible. We
12511                 // explicitly make use of C++'s one definition rule here, and
12512                 // assume that this definition is identical to the hidden one
12513                 // we already have. Make the existing definition visible and
12514                 // use it in place of this one.
12515                 SkipBody->ShouldSkip = true;
12516                 makeMergedDefinitionVisible(Hidden, KWLoc);
12517                 return Def;
12518               } else if (!IsExplicitSpecializationAfterInstantiation) {
12519                 // A redeclaration in function prototype scope in C isn't
12520                 // visible elsewhere, so merely issue a warning.
12521                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12522                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12523                 else
12524                   Diag(NameLoc, diag::err_redefinition) << Name;
12525                 Diag(Def->getLocation(), diag::note_previous_definition);
12526                 // If this is a redefinition, recover by making this
12527                 // struct be anonymous, which will make any later
12528                 // references get the previous definition.
12529                 Name = nullptr;
12530                 Previous.clear();
12531                 Invalid = true;
12532               }
12533             } else {
12534               // If the type is currently being defined, complain
12535               // about a nested redefinition.
12536               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12537               if (TD->isBeingDefined()) {
12538                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12539                 Diag(PrevTagDecl->getLocation(),
12540                      diag::note_previous_definition);
12541                 Name = nullptr;
12542                 Previous.clear();
12543                 Invalid = true;
12544               }
12545             }
12546 
12547             // Okay, this is definition of a previously declared or referenced
12548             // tag. We're going to create a new Decl for it.
12549           }
12550 
12551           // Okay, we're going to make a redeclaration.  If this is some kind
12552           // of reference, make sure we build the redeclaration in the same DC
12553           // as the original, and ignore the current access specifier.
12554           if (TUK == TUK_Friend || TUK == TUK_Reference) {
12555             SearchDC = PrevTagDecl->getDeclContext();
12556             AS = AS_none;
12557           }
12558         }
12559         // If we get here we have (another) forward declaration or we
12560         // have a definition.  Just create a new decl.
12561 
12562       } else {
12563         // If we get here, this is a definition of a new tag type in a nested
12564         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12565         // new decl/type.  We set PrevDecl to NULL so that the entities
12566         // have distinct types.
12567         Previous.clear();
12568       }
12569       // If we get here, we're going to create a new Decl. If PrevDecl
12570       // is non-NULL, it's a definition of the tag declared by
12571       // PrevDecl. If it's NULL, we have a new definition.
12572 
12573     // Otherwise, PrevDecl is not a tag, but was found with tag
12574     // lookup.  This is only actually possible in C++, where a few
12575     // things like templates still live in the tag namespace.
12576     } else {
12577       // Use a better diagnostic if an elaborated-type-specifier
12578       // found the wrong kind of type on the first
12579       // (non-redeclaration) lookup.
12580       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12581           !Previous.isForRedeclaration()) {
12582         unsigned Kind = 0;
12583         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12584         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12585         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12586         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12587         Diag(PrevDecl->getLocation(), diag::note_declared_at);
12588         Invalid = true;
12589 
12590       // Otherwise, only diagnose if the declaration is in scope.
12591       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12592                                 SS.isNotEmpty() || isExplicitSpecialization)) {
12593         // do nothing
12594 
12595       // Diagnose implicit declarations introduced by elaborated types.
12596       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12597         unsigned Kind = 0;
12598         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12599         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12600         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12601         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12602         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12603         Invalid = true;
12604 
12605       // Otherwise it's a declaration.  Call out a particularly common
12606       // case here.
12607       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12608         unsigned Kind = 0;
12609         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12610         Diag(NameLoc, diag::err_tag_definition_of_typedef)
12611           << Name << Kind << TND->getUnderlyingType();
12612         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12613         Invalid = true;
12614 
12615       // Otherwise, diagnose.
12616       } else {
12617         // The tag name clashes with something else in the target scope,
12618         // issue an error and recover by making this tag be anonymous.
12619         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12620         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12621         Name = nullptr;
12622         Invalid = true;
12623       }
12624 
12625       // The existing declaration isn't relevant to us; we're in a
12626       // new scope, so clear out the previous declaration.
12627       Previous.clear();
12628     }
12629   }
12630 
12631 CreateNewDecl:
12632 
12633   TagDecl *PrevDecl = nullptr;
12634   if (Previous.isSingleResult())
12635     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12636 
12637   // If there is an identifier, use the location of the identifier as the
12638   // location of the decl, otherwise use the location of the struct/union
12639   // keyword.
12640   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12641 
12642   // Otherwise, create a new declaration. If there is a previous
12643   // declaration of the same entity, the two will be linked via
12644   // PrevDecl.
12645   TagDecl *New;
12646 
12647   bool IsForwardReference = false;
12648   if (Kind == TTK_Enum) {
12649     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12650     // enum X { A, B, C } D;    D should chain to X.
12651     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12652                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12653                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12654     // If this is an undefined enum, warn.
12655     if (TUK != TUK_Definition && !Invalid) {
12656       TagDecl *Def;
12657       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12658           cast<EnumDecl>(New)->isFixed()) {
12659         // C++0x: 7.2p2: opaque-enum-declaration.
12660         // Conflicts are diagnosed above. Do nothing.
12661       }
12662       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12663         Diag(Loc, diag::ext_forward_ref_enum_def)
12664           << New;
12665         Diag(Def->getLocation(), diag::note_previous_definition);
12666       } else {
12667         unsigned DiagID = diag::ext_forward_ref_enum;
12668         if (getLangOpts().MSVCCompat)
12669           DiagID = diag::ext_ms_forward_ref_enum;
12670         else if (getLangOpts().CPlusPlus)
12671           DiagID = diag::err_forward_ref_enum;
12672         Diag(Loc, DiagID);
12673 
12674         // If this is a forward-declared reference to an enumeration, make a
12675         // note of it; we won't actually be introducing the declaration into
12676         // the declaration context.
12677         if (TUK == TUK_Reference)
12678           IsForwardReference = true;
12679       }
12680     }
12681 
12682     if (EnumUnderlying) {
12683       EnumDecl *ED = cast<EnumDecl>(New);
12684       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12685         ED->setIntegerTypeSourceInfo(TI);
12686       else
12687         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12688       ED->setPromotionType(ED->getIntegerType());
12689     }
12690   } else {
12691     // struct/union/class
12692 
12693     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12694     // struct X { int A; } D;    D should chain to X.
12695     if (getLangOpts().CPlusPlus) {
12696       // FIXME: Look for a way to use RecordDecl for simple structs.
12697       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12698                                   cast_or_null<CXXRecordDecl>(PrevDecl));
12699 
12700       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12701         StdBadAlloc = cast<CXXRecordDecl>(New);
12702     } else
12703       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12704                                cast_or_null<RecordDecl>(PrevDecl));
12705   }
12706 
12707   // C++11 [dcl.type]p3:
12708   //   A type-specifier-seq shall not define a class or enumeration [...].
12709   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12710     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12711       << Context.getTagDeclType(New);
12712     Invalid = true;
12713   }
12714 
12715   // Maybe add qualifier info.
12716   if (SS.isNotEmpty()) {
12717     if (SS.isSet()) {
12718       // If this is either a declaration or a definition, check the
12719       // nested-name-specifier against the current context. We don't do this
12720       // for explicit specializations, because they have similar checking
12721       // (with more specific diagnostics) in the call to
12722       // CheckMemberSpecialization, below.
12723       if (!isExplicitSpecialization &&
12724           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12725           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12726         Invalid = true;
12727 
12728       New->setQualifierInfo(SS.getWithLocInContext(Context));
12729       if (TemplateParameterLists.size() > 0) {
12730         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12731       }
12732     }
12733     else
12734       Invalid = true;
12735   }
12736 
12737   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12738     // Add alignment attributes if necessary; these attributes are checked when
12739     // the ASTContext lays out the structure.
12740     //
12741     // It is important for implementing the correct semantics that this
12742     // happen here (in act on tag decl). The #pragma pack stack is
12743     // maintained as a result of parser callbacks which can occur at
12744     // many points during the parsing of a struct declaration (because
12745     // the #pragma tokens are effectively skipped over during the
12746     // parsing of the struct).
12747     if (TUK == TUK_Definition) {
12748       AddAlignmentAttributesForRecord(RD);
12749       AddMsStructLayoutForRecord(RD);
12750     }
12751   }
12752 
12753   if (ModulePrivateLoc.isValid()) {
12754     if (isExplicitSpecialization)
12755       Diag(New->getLocation(), diag::err_module_private_specialization)
12756         << 2
12757         << FixItHint::CreateRemoval(ModulePrivateLoc);
12758     // __module_private__ does not apply to local classes. However, we only
12759     // diagnose this as an error when the declaration specifiers are
12760     // freestanding. Here, we just ignore the __module_private__.
12761     else if (!SearchDC->isFunctionOrMethod())
12762       New->setModulePrivate();
12763   }
12764 
12765   // If this is a specialization of a member class (of a class template),
12766   // check the specialization.
12767   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12768     Invalid = true;
12769 
12770   // If we're declaring or defining a tag in function prototype scope in C,
12771   // note that this type can only be used within the function and add it to
12772   // the list of decls to inject into the function definition scope.
12773   if ((Name || Kind == TTK_Enum) &&
12774       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12775     if (getLangOpts().CPlusPlus) {
12776       // C++ [dcl.fct]p6:
12777       //   Types shall not be defined in return or parameter types.
12778       if (TUK == TUK_Definition && !IsTypeSpecifier) {
12779         Diag(Loc, diag::err_type_defined_in_param_type)
12780             << Name;
12781         Invalid = true;
12782       }
12783     } else if (!PrevDecl) {
12784       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
12785     }
12786     DeclsInPrototypeScope.push_back(New);
12787   }
12788 
12789   if (Invalid)
12790     New->setInvalidDecl();
12791 
12792   if (Attr)
12793     ProcessDeclAttributeList(S, New, Attr);
12794 
12795   // Set the lexical context. If the tag has a C++ scope specifier, the
12796   // lexical context will be different from the semantic context.
12797   New->setLexicalDeclContext(CurContext);
12798 
12799   // Mark this as a friend decl if applicable.
12800   // In Microsoft mode, a friend declaration also acts as a forward
12801   // declaration so we always pass true to setObjectOfFriendDecl to make
12802   // the tag name visible.
12803   if (TUK == TUK_Friend)
12804     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
12805 
12806   // Set the access specifier.
12807   if (!Invalid && SearchDC->isRecord())
12808     SetMemberAccessSpecifier(New, PrevDecl, AS);
12809 
12810   if (TUK == TUK_Definition)
12811     New->startDefinition();
12812 
12813   // If this has an identifier, add it to the scope stack.
12814   if (TUK == TUK_Friend) {
12815     // We might be replacing an existing declaration in the lookup tables;
12816     // if so, borrow its access specifier.
12817     if (PrevDecl)
12818       New->setAccess(PrevDecl->getAccess());
12819 
12820     DeclContext *DC = New->getDeclContext()->getRedeclContext();
12821     DC->makeDeclVisibleInContext(New);
12822     if (Name) // can be null along some error paths
12823       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12824         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
12825   } else if (Name) {
12826     S = getNonFieldDeclScope(S);
12827     PushOnScopeChains(New, S, !IsForwardReference);
12828     if (IsForwardReference)
12829       SearchDC->makeDeclVisibleInContext(New);
12830   } else {
12831     CurContext->addDecl(New);
12832   }
12833 
12834   // If this is the C FILE type, notify the AST context.
12835   if (IdentifierInfo *II = New->getIdentifier())
12836     if (!New->isInvalidDecl() &&
12837         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
12838         II->isStr("FILE"))
12839       Context.setFILEDecl(New);
12840 
12841   if (PrevDecl)
12842     mergeDeclAttributes(New, PrevDecl);
12843 
12844   // If there's a #pragma GCC visibility in scope, set the visibility of this
12845   // record.
12846   AddPushedVisibilityAttribute(New);
12847 
12848   OwnedDecl = true;
12849   // In C++, don't return an invalid declaration. We can't recover well from
12850   // the cases where we make the type anonymous.
12851   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
12852 }
12853 
12854 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
12855   AdjustDeclIfTemplate(TagD);
12856   TagDecl *Tag = cast<TagDecl>(TagD);
12857 
12858   // Enter the tag context.
12859   PushDeclContext(S, Tag);
12860 
12861   ActOnDocumentableDecl(TagD);
12862 
12863   // If there's a #pragma GCC visibility in scope, set the visibility of this
12864   // record.
12865   AddPushedVisibilityAttribute(Tag);
12866 }
12867 
12868 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
12869   assert(isa<ObjCContainerDecl>(IDecl) &&
12870          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
12871   DeclContext *OCD = cast<DeclContext>(IDecl);
12872   assert(getContainingDC(OCD) == CurContext &&
12873       "The next DeclContext should be lexically contained in the current one.");
12874   CurContext = OCD;
12875   return IDecl;
12876 }
12877 
12878 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
12879                                            SourceLocation FinalLoc,
12880                                            bool IsFinalSpelledSealed,
12881                                            SourceLocation LBraceLoc) {
12882   AdjustDeclIfTemplate(TagD);
12883   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
12884 
12885   FieldCollector->StartClass();
12886 
12887   if (!Record->getIdentifier())
12888     return;
12889 
12890   if (FinalLoc.isValid())
12891     Record->addAttr(new (Context)
12892                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
12893 
12894   // C++ [class]p2:
12895   //   [...] The class-name is also inserted into the scope of the
12896   //   class itself; this is known as the injected-class-name. For
12897   //   purposes of access checking, the injected-class-name is treated
12898   //   as if it were a public member name.
12899   CXXRecordDecl *InjectedClassName
12900     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
12901                             Record->getLocStart(), Record->getLocation(),
12902                             Record->getIdentifier(),
12903                             /*PrevDecl=*/nullptr,
12904                             /*DelayTypeCreation=*/true);
12905   Context.getTypeDeclType(InjectedClassName, Record);
12906   InjectedClassName->setImplicit();
12907   InjectedClassName->setAccess(AS_public);
12908   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
12909       InjectedClassName->setDescribedClassTemplate(Template);
12910   PushOnScopeChains(InjectedClassName, S);
12911   assert(InjectedClassName->isInjectedClassName() &&
12912          "Broken injected-class-name");
12913 }
12914 
12915 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
12916                                     SourceLocation RBraceLoc) {
12917   AdjustDeclIfTemplate(TagD);
12918   TagDecl *Tag = cast<TagDecl>(TagD);
12919   Tag->setRBraceLoc(RBraceLoc);
12920 
12921   // Make sure we "complete" the definition even it is invalid.
12922   if (Tag->isBeingDefined()) {
12923     assert(Tag->isInvalidDecl() && "We should already have completed it");
12924     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12925       RD->completeDefinition();
12926   }
12927 
12928   if (isa<CXXRecordDecl>(Tag))
12929     FieldCollector->FinishClass();
12930 
12931   // Exit this scope of this tag's definition.
12932   PopDeclContext();
12933 
12934   if (getCurLexicalContext()->isObjCContainer() &&
12935       Tag->getDeclContext()->isFileContext())
12936     Tag->setTopLevelDeclInObjCContainer();
12937 
12938   // Notify the consumer that we've defined a tag.
12939   if (!Tag->isInvalidDecl())
12940     Consumer.HandleTagDeclDefinition(Tag);
12941 }
12942 
12943 void Sema::ActOnObjCContainerFinishDefinition() {
12944   // Exit this scope of this interface definition.
12945   PopDeclContext();
12946 }
12947 
12948 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
12949   assert(DC == CurContext && "Mismatch of container contexts");
12950   OriginalLexicalContext = DC;
12951   ActOnObjCContainerFinishDefinition();
12952 }
12953 
12954 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
12955   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
12956   OriginalLexicalContext = nullptr;
12957 }
12958 
12959 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
12960   AdjustDeclIfTemplate(TagD);
12961   TagDecl *Tag = cast<TagDecl>(TagD);
12962   Tag->setInvalidDecl();
12963 
12964   // Make sure we "complete" the definition even it is invalid.
12965   if (Tag->isBeingDefined()) {
12966     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12967       RD->completeDefinition();
12968   }
12969 
12970   // We're undoing ActOnTagStartDefinition here, not
12971   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
12972   // the FieldCollector.
12973 
12974   PopDeclContext();
12975 }
12976 
12977 // Note that FieldName may be null for anonymous bitfields.
12978 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
12979                                 IdentifierInfo *FieldName,
12980                                 QualType FieldTy, bool IsMsStruct,
12981                                 Expr *BitWidth, bool *ZeroWidth) {
12982   // Default to true; that shouldn't confuse checks for emptiness
12983   if (ZeroWidth)
12984     *ZeroWidth = true;
12985 
12986   // C99 6.7.2.1p4 - verify the field type.
12987   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
12988   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
12989     // Handle incomplete types with specific error.
12990     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
12991       return ExprError();
12992     if (FieldName)
12993       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12994         << FieldName << FieldTy << BitWidth->getSourceRange();
12995     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12996       << FieldTy << BitWidth->getSourceRange();
12997   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12998                                              UPPC_BitFieldWidth))
12999     return ExprError();
13000 
13001   // If the bit-width is type- or value-dependent, don't try to check
13002   // it now.
13003   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13004     return BitWidth;
13005 
13006   llvm::APSInt Value;
13007   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13008   if (ICE.isInvalid())
13009     return ICE;
13010   BitWidth = ICE.get();
13011 
13012   if (Value != 0 && ZeroWidth)
13013     *ZeroWidth = false;
13014 
13015   // Zero-width bitfield is ok for anonymous field.
13016   if (Value == 0 && FieldName)
13017     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13018 
13019   if (Value.isSigned() && Value.isNegative()) {
13020     if (FieldName)
13021       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13022                << FieldName << Value.toString(10);
13023     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13024       << Value.toString(10);
13025   }
13026 
13027   if (!FieldTy->isDependentType()) {
13028     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13029     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13030     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13031 
13032     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13033     // ABI.
13034     bool CStdConstraintViolation =
13035         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13036     bool MSBitfieldViolation =
13037         Value.ugt(TypeStorageSize) &&
13038         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13039     if (CStdConstraintViolation || MSBitfieldViolation) {
13040       unsigned DiagWidth =
13041           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13042       if (FieldName)
13043         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13044                << FieldName << (unsigned)Value.getZExtValue()
13045                << !CStdConstraintViolation << DiagWidth;
13046 
13047       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13048              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13049              << DiagWidth;
13050     }
13051 
13052     // Warn on types where the user might conceivably expect to get all
13053     // specified bits as value bits: that's all integral types other than
13054     // 'bool'.
13055     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13056       if (FieldName)
13057         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13058             << FieldName << (unsigned)Value.getZExtValue()
13059             << (unsigned)TypeWidth;
13060       else
13061         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13062             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13063     }
13064   }
13065 
13066   return BitWidth;
13067 }
13068 
13069 /// ActOnField - Each field of a C struct/union is passed into this in order
13070 /// to create a FieldDecl object for it.
13071 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13072                        Declarator &D, Expr *BitfieldWidth) {
13073   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13074                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13075                                /*InitStyle=*/ICIS_NoInit, AS_public);
13076   return Res;
13077 }
13078 
13079 /// HandleField - Analyze a field of a C struct or a C++ data member.
13080 ///
13081 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13082                              SourceLocation DeclStart,
13083                              Declarator &D, Expr *BitWidth,
13084                              InClassInitStyle InitStyle,
13085                              AccessSpecifier AS) {
13086   IdentifierInfo *II = D.getIdentifier();
13087   SourceLocation Loc = DeclStart;
13088   if (II) Loc = D.getIdentifierLoc();
13089 
13090   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13091   QualType T = TInfo->getType();
13092   if (getLangOpts().CPlusPlus) {
13093     CheckExtraCXXDefaultArguments(D);
13094 
13095     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13096                                         UPPC_DataMemberType)) {
13097       D.setInvalidType();
13098       T = Context.IntTy;
13099       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13100     }
13101   }
13102 
13103   // TR 18037 does not allow fields to be declared with address spaces.
13104   if (T.getQualifiers().hasAddressSpace()) {
13105     Diag(Loc, diag::err_field_with_address_space);
13106     D.setInvalidType();
13107   }
13108 
13109   // OpenCL 1.2 spec, s6.9 r:
13110   // The event type cannot be used to declare a structure or union field.
13111   if (LangOpts.OpenCL && T->isEventT()) {
13112     Diag(Loc, diag::err_event_t_struct_field);
13113     D.setInvalidType();
13114   }
13115 
13116   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13117 
13118   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13119     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13120          diag::err_invalid_thread)
13121       << DeclSpec::getSpecifierName(TSCS);
13122 
13123   // Check to see if this name was declared as a member previously
13124   NamedDecl *PrevDecl = nullptr;
13125   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13126   LookupName(Previous, S);
13127   switch (Previous.getResultKind()) {
13128     case LookupResult::Found:
13129     case LookupResult::FoundUnresolvedValue:
13130       PrevDecl = Previous.getAsSingle<NamedDecl>();
13131       break;
13132 
13133     case LookupResult::FoundOverloaded:
13134       PrevDecl = Previous.getRepresentativeDecl();
13135       break;
13136 
13137     case LookupResult::NotFound:
13138     case LookupResult::NotFoundInCurrentInstantiation:
13139     case LookupResult::Ambiguous:
13140       break;
13141   }
13142   Previous.suppressDiagnostics();
13143 
13144   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13145     // Maybe we will complain about the shadowed template parameter.
13146     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13147     // Just pretend that we didn't see the previous declaration.
13148     PrevDecl = nullptr;
13149   }
13150 
13151   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13152     PrevDecl = nullptr;
13153 
13154   bool Mutable
13155     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13156   SourceLocation TSSL = D.getLocStart();
13157   FieldDecl *NewFD
13158     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13159                      TSSL, AS, PrevDecl, &D);
13160 
13161   if (NewFD->isInvalidDecl())
13162     Record->setInvalidDecl();
13163 
13164   if (D.getDeclSpec().isModulePrivateSpecified())
13165     NewFD->setModulePrivate();
13166 
13167   if (NewFD->isInvalidDecl() && PrevDecl) {
13168     // Don't introduce NewFD into scope; there's already something
13169     // with the same name in the same scope.
13170   } else if (II) {
13171     PushOnScopeChains(NewFD, S);
13172   } else
13173     Record->addDecl(NewFD);
13174 
13175   return NewFD;
13176 }
13177 
13178 /// \brief Build a new FieldDecl and check its well-formedness.
13179 ///
13180 /// This routine builds a new FieldDecl given the fields name, type,
13181 /// record, etc. \p PrevDecl should refer to any previous declaration
13182 /// with the same name and in the same scope as the field to be
13183 /// created.
13184 ///
13185 /// \returns a new FieldDecl.
13186 ///
13187 /// \todo The Declarator argument is a hack. It will be removed once
13188 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13189                                 TypeSourceInfo *TInfo,
13190                                 RecordDecl *Record, SourceLocation Loc,
13191                                 bool Mutable, Expr *BitWidth,
13192                                 InClassInitStyle InitStyle,
13193                                 SourceLocation TSSL,
13194                                 AccessSpecifier AS, NamedDecl *PrevDecl,
13195                                 Declarator *D) {
13196   IdentifierInfo *II = Name.getAsIdentifierInfo();
13197   bool InvalidDecl = false;
13198   if (D) InvalidDecl = D->isInvalidType();
13199 
13200   // If we receive a broken type, recover by assuming 'int' and
13201   // marking this declaration as invalid.
13202   if (T.isNull()) {
13203     InvalidDecl = true;
13204     T = Context.IntTy;
13205   }
13206 
13207   QualType EltTy = Context.getBaseElementType(T);
13208   if (!EltTy->isDependentType()) {
13209     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13210       // Fields of incomplete type force their record to be invalid.
13211       Record->setInvalidDecl();
13212       InvalidDecl = true;
13213     } else {
13214       NamedDecl *Def;
13215       EltTy->isIncompleteType(&Def);
13216       if (Def && Def->isInvalidDecl()) {
13217         Record->setInvalidDecl();
13218         InvalidDecl = true;
13219       }
13220     }
13221   }
13222 
13223   // OpenCL v1.2 s6.9.c: bitfields are not supported.
13224   if (BitWidth && getLangOpts().OpenCL) {
13225     Diag(Loc, diag::err_opencl_bitfields);
13226     InvalidDecl = true;
13227   }
13228 
13229   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13230   // than a variably modified type.
13231   if (!InvalidDecl && T->isVariablyModifiedType()) {
13232     bool SizeIsNegative;
13233     llvm::APSInt Oversized;
13234 
13235     TypeSourceInfo *FixedTInfo =
13236       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13237                                                     SizeIsNegative,
13238                                                     Oversized);
13239     if (FixedTInfo) {
13240       Diag(Loc, diag::warn_illegal_constant_array_size);
13241       TInfo = FixedTInfo;
13242       T = FixedTInfo->getType();
13243     } else {
13244       if (SizeIsNegative)
13245         Diag(Loc, diag::err_typecheck_negative_array_size);
13246       else if (Oversized.getBoolValue())
13247         Diag(Loc, diag::err_array_too_large)
13248           << Oversized.toString(10);
13249       else
13250         Diag(Loc, diag::err_typecheck_field_variable_size);
13251       InvalidDecl = true;
13252     }
13253   }
13254 
13255   // Fields can not have abstract class types
13256   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13257                                              diag::err_abstract_type_in_decl,
13258                                              AbstractFieldType))
13259     InvalidDecl = true;
13260 
13261   bool ZeroWidth = false;
13262   if (InvalidDecl)
13263     BitWidth = nullptr;
13264   // If this is declared as a bit-field, check the bit-field.
13265   if (BitWidth) {
13266     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13267                               &ZeroWidth).get();
13268     if (!BitWidth) {
13269       InvalidDecl = true;
13270       BitWidth = nullptr;
13271       ZeroWidth = false;
13272     }
13273   }
13274 
13275   // Check that 'mutable' is consistent with the type of the declaration.
13276   if (!InvalidDecl && Mutable) {
13277     unsigned DiagID = 0;
13278     if (T->isReferenceType())
13279       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13280                                         : diag::err_mutable_reference;
13281     else if (T.isConstQualified())
13282       DiagID = diag::err_mutable_const;
13283 
13284     if (DiagID) {
13285       SourceLocation ErrLoc = Loc;
13286       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13287         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13288       Diag(ErrLoc, DiagID);
13289       if (DiagID != diag::ext_mutable_reference) {
13290         Mutable = false;
13291         InvalidDecl = true;
13292       }
13293     }
13294   }
13295 
13296   // C++11 [class.union]p8 (DR1460):
13297   //   At most one variant member of a union may have a
13298   //   brace-or-equal-initializer.
13299   if (InitStyle != ICIS_NoInit)
13300     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13301 
13302   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13303                                        BitWidth, Mutable, InitStyle);
13304   if (InvalidDecl)
13305     NewFD->setInvalidDecl();
13306 
13307   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13308     Diag(Loc, diag::err_duplicate_member) << II;
13309     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13310     NewFD->setInvalidDecl();
13311   }
13312 
13313   if (!InvalidDecl && getLangOpts().CPlusPlus) {
13314     if (Record->isUnion()) {
13315       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13316         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13317         if (RDecl->getDefinition()) {
13318           // C++ [class.union]p1: An object of a class with a non-trivial
13319           // constructor, a non-trivial copy constructor, a non-trivial
13320           // destructor, or a non-trivial copy assignment operator
13321           // cannot be a member of a union, nor can an array of such
13322           // objects.
13323           if (CheckNontrivialField(NewFD))
13324             NewFD->setInvalidDecl();
13325         }
13326       }
13327 
13328       // C++ [class.union]p1: If a union contains a member of reference type,
13329       // the program is ill-formed, except when compiling with MSVC extensions
13330       // enabled.
13331       if (EltTy->isReferenceType()) {
13332         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13333                                     diag::ext_union_member_of_reference_type :
13334                                     diag::err_union_member_of_reference_type)
13335           << NewFD->getDeclName() << EltTy;
13336         if (!getLangOpts().MicrosoftExt)
13337           NewFD->setInvalidDecl();
13338       }
13339     }
13340   }
13341 
13342   // FIXME: We need to pass in the attributes given an AST
13343   // representation, not a parser representation.
13344   if (D) {
13345     // FIXME: The current scope is almost... but not entirely... correct here.
13346     ProcessDeclAttributes(getCurScope(), NewFD, *D);
13347 
13348     if (NewFD->hasAttrs())
13349       CheckAlignasUnderalignment(NewFD);
13350   }
13351 
13352   // In auto-retain/release, infer strong retension for fields of
13353   // retainable type.
13354   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13355     NewFD->setInvalidDecl();
13356 
13357   if (T.isObjCGCWeak())
13358     Diag(Loc, diag::warn_attribute_weak_on_field);
13359 
13360   NewFD->setAccess(AS);
13361   return NewFD;
13362 }
13363 
13364 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13365   assert(FD);
13366   assert(getLangOpts().CPlusPlus && "valid check only for C++");
13367 
13368   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13369     return false;
13370 
13371   QualType EltTy = Context.getBaseElementType(FD->getType());
13372   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13373     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13374     if (RDecl->getDefinition()) {
13375       // We check for copy constructors before constructors
13376       // because otherwise we'll never get complaints about
13377       // copy constructors.
13378 
13379       CXXSpecialMember member = CXXInvalid;
13380       // We're required to check for any non-trivial constructors. Since the
13381       // implicit default constructor is suppressed if there are any
13382       // user-declared constructors, we just need to check that there is a
13383       // trivial default constructor and a trivial copy constructor. (We don't
13384       // worry about move constructors here, since this is a C++98 check.)
13385       if (RDecl->hasNonTrivialCopyConstructor())
13386         member = CXXCopyConstructor;
13387       else if (!RDecl->hasTrivialDefaultConstructor())
13388         member = CXXDefaultConstructor;
13389       else if (RDecl->hasNonTrivialCopyAssignment())
13390         member = CXXCopyAssignment;
13391       else if (RDecl->hasNonTrivialDestructor())
13392         member = CXXDestructor;
13393 
13394       if (member != CXXInvalid) {
13395         if (!getLangOpts().CPlusPlus11 &&
13396             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13397           // Objective-C++ ARC: it is an error to have a non-trivial field of
13398           // a union. However, system headers in Objective-C programs
13399           // occasionally have Objective-C lifetime objects within unions,
13400           // and rather than cause the program to fail, we make those
13401           // members unavailable.
13402           SourceLocation Loc = FD->getLocation();
13403           if (getSourceManager().isInSystemHeader(Loc)) {
13404             if (!FD->hasAttr<UnavailableAttr>())
13405               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13406                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13407             return false;
13408           }
13409         }
13410 
13411         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13412                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13413                diag::err_illegal_union_or_anon_struct_member)
13414           << FD->getParent()->isUnion() << FD->getDeclName() << member;
13415         DiagnoseNontrivial(RDecl, member);
13416         return !getLangOpts().CPlusPlus11;
13417       }
13418     }
13419   }
13420 
13421   return false;
13422 }
13423 
13424 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13425 ///  AST enum value.
13426 static ObjCIvarDecl::AccessControl
13427 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13428   switch (ivarVisibility) {
13429   default: llvm_unreachable("Unknown visitibility kind");
13430   case tok::objc_private: return ObjCIvarDecl::Private;
13431   case tok::objc_public: return ObjCIvarDecl::Public;
13432   case tok::objc_protected: return ObjCIvarDecl::Protected;
13433   case tok::objc_package: return ObjCIvarDecl::Package;
13434   }
13435 }
13436 
13437 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13438 /// in order to create an IvarDecl object for it.
13439 Decl *Sema::ActOnIvar(Scope *S,
13440                                 SourceLocation DeclStart,
13441                                 Declarator &D, Expr *BitfieldWidth,
13442                                 tok::ObjCKeywordKind Visibility) {
13443 
13444   IdentifierInfo *II = D.getIdentifier();
13445   Expr *BitWidth = (Expr*)BitfieldWidth;
13446   SourceLocation Loc = DeclStart;
13447   if (II) Loc = D.getIdentifierLoc();
13448 
13449   // FIXME: Unnamed fields can be handled in various different ways, for
13450   // example, unnamed unions inject all members into the struct namespace!
13451 
13452   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13453   QualType T = TInfo->getType();
13454 
13455   if (BitWidth) {
13456     // 6.7.2.1p3, 6.7.2.1p4
13457     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13458     if (!BitWidth)
13459       D.setInvalidType();
13460   } else {
13461     // Not a bitfield.
13462 
13463     // validate II.
13464 
13465   }
13466   if (T->isReferenceType()) {
13467     Diag(Loc, diag::err_ivar_reference_type);
13468     D.setInvalidType();
13469   }
13470   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13471   // than a variably modified type.
13472   else if (T->isVariablyModifiedType()) {
13473     Diag(Loc, diag::err_typecheck_ivar_variable_size);
13474     D.setInvalidType();
13475   }
13476 
13477   // Get the visibility (access control) for this ivar.
13478   ObjCIvarDecl::AccessControl ac =
13479     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13480                                         : ObjCIvarDecl::None;
13481   // Must set ivar's DeclContext to its enclosing interface.
13482   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13483   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13484     return nullptr;
13485   ObjCContainerDecl *EnclosingContext;
13486   if (ObjCImplementationDecl *IMPDecl =
13487       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13488     if (LangOpts.ObjCRuntime.isFragile()) {
13489     // Case of ivar declared in an implementation. Context is that of its class.
13490       EnclosingContext = IMPDecl->getClassInterface();
13491       assert(EnclosingContext && "Implementation has no class interface!");
13492     }
13493     else
13494       EnclosingContext = EnclosingDecl;
13495   } else {
13496     if (ObjCCategoryDecl *CDecl =
13497         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13498       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13499         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13500         return nullptr;
13501       }
13502     }
13503     EnclosingContext = EnclosingDecl;
13504   }
13505 
13506   // Construct the decl.
13507   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13508                                              DeclStart, Loc, II, T,
13509                                              TInfo, ac, (Expr *)BitfieldWidth);
13510 
13511   if (II) {
13512     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13513                                            ForRedeclaration);
13514     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13515         && !isa<TagDecl>(PrevDecl)) {
13516       Diag(Loc, diag::err_duplicate_member) << II;
13517       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13518       NewID->setInvalidDecl();
13519     }
13520   }
13521 
13522   // Process attributes attached to the ivar.
13523   ProcessDeclAttributes(S, NewID, D);
13524 
13525   if (D.isInvalidType())
13526     NewID->setInvalidDecl();
13527 
13528   // In ARC, infer 'retaining' for ivars of retainable type.
13529   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13530     NewID->setInvalidDecl();
13531 
13532   if (D.getDeclSpec().isModulePrivateSpecified())
13533     NewID->setModulePrivate();
13534 
13535   if (II) {
13536     // FIXME: When interfaces are DeclContexts, we'll need to add
13537     // these to the interface.
13538     S->AddDecl(NewID);
13539     IdResolver.AddDecl(NewID);
13540   }
13541 
13542   if (LangOpts.ObjCRuntime.isNonFragile() &&
13543       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13544     Diag(Loc, diag::warn_ivars_in_interface);
13545 
13546   return NewID;
13547 }
13548 
13549 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13550 /// class and class extensions. For every class \@interface and class
13551 /// extension \@interface, if the last ivar is a bitfield of any type,
13552 /// then add an implicit `char :0` ivar to the end of that interface.
13553 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13554                              SmallVectorImpl<Decl *> &AllIvarDecls) {
13555   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13556     return;
13557 
13558   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13559   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13560 
13561   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13562     return;
13563   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13564   if (!ID) {
13565     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13566       if (!CD->IsClassExtension())
13567         return;
13568     }
13569     // No need to add this to end of @implementation.
13570     else
13571       return;
13572   }
13573   // All conditions are met. Add a new bitfield to the tail end of ivars.
13574   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13575   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13576 
13577   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13578                               DeclLoc, DeclLoc, nullptr,
13579                               Context.CharTy,
13580                               Context.getTrivialTypeSourceInfo(Context.CharTy,
13581                                                                DeclLoc),
13582                               ObjCIvarDecl::Private, BW,
13583                               true);
13584   AllIvarDecls.push_back(Ivar);
13585 }
13586 
13587 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13588                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
13589                        SourceLocation RBrac, AttributeList *Attr) {
13590   assert(EnclosingDecl && "missing record or interface decl");
13591 
13592   // If this is an Objective-C @implementation or category and we have
13593   // new fields here we should reset the layout of the interface since
13594   // it will now change.
13595   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13596     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13597     switch (DC->getKind()) {
13598     default: break;
13599     case Decl::ObjCCategory:
13600       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13601       break;
13602     case Decl::ObjCImplementation:
13603       Context.
13604         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13605       break;
13606     }
13607   }
13608 
13609   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13610 
13611   // Start counting up the number of named members; make sure to include
13612   // members of anonymous structs and unions in the total.
13613   unsigned NumNamedMembers = 0;
13614   if (Record) {
13615     for (const auto *I : Record->decls()) {
13616       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13617         if (IFD->getDeclName())
13618           ++NumNamedMembers;
13619     }
13620   }
13621 
13622   // Verify that all the fields are okay.
13623   SmallVector<FieldDecl*, 32> RecFields;
13624 
13625   bool ARCErrReported = false;
13626   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13627        i != end; ++i) {
13628     FieldDecl *FD = cast<FieldDecl>(*i);
13629 
13630     // Get the type for the field.
13631     const Type *FDTy = FD->getType().getTypePtr();
13632 
13633     if (!FD->isAnonymousStructOrUnion()) {
13634       // Remember all fields written by the user.
13635       RecFields.push_back(FD);
13636     }
13637 
13638     // If the field is already invalid for some reason, don't emit more
13639     // diagnostics about it.
13640     if (FD->isInvalidDecl()) {
13641       EnclosingDecl->setInvalidDecl();
13642       continue;
13643     }
13644 
13645     // C99 6.7.2.1p2:
13646     //   A structure or union shall not contain a member with
13647     //   incomplete or function type (hence, a structure shall not
13648     //   contain an instance of itself, but may contain a pointer to
13649     //   an instance of itself), except that the last member of a
13650     //   structure with more than one named member may have incomplete
13651     //   array type; such a structure (and any union containing,
13652     //   possibly recursively, a member that is such a structure)
13653     //   shall not be a member of a structure or an element of an
13654     //   array.
13655     if (FDTy->isFunctionType()) {
13656       // Field declared as a function.
13657       Diag(FD->getLocation(), diag::err_field_declared_as_function)
13658         << FD->getDeclName();
13659       FD->setInvalidDecl();
13660       EnclosingDecl->setInvalidDecl();
13661       continue;
13662     } else if (FDTy->isIncompleteArrayType() && Record &&
13663                ((i + 1 == Fields.end() && !Record->isUnion()) ||
13664                 ((getLangOpts().MicrosoftExt ||
13665                   getLangOpts().CPlusPlus) &&
13666                  (i + 1 == Fields.end() || Record->isUnion())))) {
13667       // Flexible array member.
13668       // Microsoft and g++ is more permissive regarding flexible array.
13669       // It will accept flexible array in union and also
13670       // as the sole element of a struct/class.
13671       unsigned DiagID = 0;
13672       if (Record->isUnion())
13673         DiagID = getLangOpts().MicrosoftExt
13674                      ? diag::ext_flexible_array_union_ms
13675                      : getLangOpts().CPlusPlus
13676                            ? diag::ext_flexible_array_union_gnu
13677                            : diag::err_flexible_array_union;
13678       else if (Fields.size() == 1)
13679         DiagID = getLangOpts().MicrosoftExt
13680                      ? diag::ext_flexible_array_empty_aggregate_ms
13681                      : getLangOpts().CPlusPlus
13682                            ? diag::ext_flexible_array_empty_aggregate_gnu
13683                            : NumNamedMembers < 1
13684                                  ? diag::err_flexible_array_empty_aggregate
13685                                  : 0;
13686 
13687       if (DiagID)
13688         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13689                                         << Record->getTagKind();
13690       // While the layout of types that contain virtual bases is not specified
13691       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13692       // virtual bases after the derived members.  This would make a flexible
13693       // array member declared at the end of an object not adjacent to the end
13694       // of the type.
13695       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13696         if (RD->getNumVBases() != 0)
13697           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13698             << FD->getDeclName() << Record->getTagKind();
13699       if (!getLangOpts().C99)
13700         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13701           << FD->getDeclName() << Record->getTagKind();
13702 
13703       // If the element type has a non-trivial destructor, we would not
13704       // implicitly destroy the elements, so disallow it for now.
13705       //
13706       // FIXME: GCC allows this. We should probably either implicitly delete
13707       // the destructor of the containing class, or just allow this.
13708       QualType BaseElem = Context.getBaseElementType(FD->getType());
13709       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13710         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13711           << FD->getDeclName() << FD->getType();
13712         FD->setInvalidDecl();
13713         EnclosingDecl->setInvalidDecl();
13714         continue;
13715       }
13716       // Okay, we have a legal flexible array member at the end of the struct.
13717       Record->setHasFlexibleArrayMember(true);
13718     } else if (!FDTy->isDependentType() &&
13719                RequireCompleteType(FD->getLocation(), FD->getType(),
13720                                    diag::err_field_incomplete)) {
13721       // Incomplete type
13722       FD->setInvalidDecl();
13723       EnclosingDecl->setInvalidDecl();
13724       continue;
13725     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13726       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13727         // A type which contains a flexible array member is considered to be a
13728         // flexible array member.
13729         Record->setHasFlexibleArrayMember(true);
13730         if (!Record->isUnion()) {
13731           // If this is a struct/class and this is not the last element, reject
13732           // it.  Note that GCC supports variable sized arrays in the middle of
13733           // structures.
13734           if (i + 1 != Fields.end())
13735             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13736               << FD->getDeclName() << FD->getType();
13737           else {
13738             // We support flexible arrays at the end of structs in
13739             // other structs as an extension.
13740             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13741               << FD->getDeclName();
13742           }
13743         }
13744       }
13745       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13746           RequireNonAbstractType(FD->getLocation(), FD->getType(),
13747                                  diag::err_abstract_type_in_decl,
13748                                  AbstractIvarType)) {
13749         // Ivars can not have abstract class types
13750         FD->setInvalidDecl();
13751       }
13752       if (Record && FDTTy->getDecl()->hasObjectMember())
13753         Record->setHasObjectMember(true);
13754       if (Record && FDTTy->getDecl()->hasVolatileMember())
13755         Record->setHasVolatileMember(true);
13756     } else if (FDTy->isObjCObjectType()) {
13757       /// A field cannot be an Objective-c object
13758       Diag(FD->getLocation(), diag::err_statically_allocated_object)
13759         << FixItHint::CreateInsertion(FD->getLocation(), "*");
13760       QualType T = Context.getObjCObjectPointerType(FD->getType());
13761       FD->setType(T);
13762     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13763                (!getLangOpts().CPlusPlus || Record->isUnion())) {
13764       // It's an error in ARC if a field has lifetime.
13765       // We don't want to report this in a system header, though,
13766       // so we just make the field unavailable.
13767       // FIXME: that's really not sufficient; we need to make the type
13768       // itself invalid to, say, initialize or copy.
13769       QualType T = FD->getType();
13770       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
13771       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13772         SourceLocation loc = FD->getLocation();
13773         if (getSourceManager().isInSystemHeader(loc)) {
13774           if (!FD->hasAttr<UnavailableAttr>()) {
13775             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13776                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
13777           }
13778         } else {
13779           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
13780             << T->isBlockPointerType() << Record->getTagKind();
13781         }
13782         ARCErrReported = true;
13783       }
13784     } else if (getLangOpts().ObjC1 &&
13785                getLangOpts().getGC() != LangOptions::NonGC &&
13786                Record && !Record->hasObjectMember()) {
13787       if (FD->getType()->isObjCObjectPointerType() ||
13788           FD->getType().isObjCGCStrong())
13789         Record->setHasObjectMember(true);
13790       else if (Context.getAsArrayType(FD->getType())) {
13791         QualType BaseType = Context.getBaseElementType(FD->getType());
13792         if (BaseType->isRecordType() &&
13793             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
13794           Record->setHasObjectMember(true);
13795         else if (BaseType->isObjCObjectPointerType() ||
13796                  BaseType.isObjCGCStrong())
13797                Record->setHasObjectMember(true);
13798       }
13799     }
13800     if (Record && FD->getType().isVolatileQualified())
13801       Record->setHasVolatileMember(true);
13802     // Keep track of the number of named members.
13803     if (FD->getIdentifier())
13804       ++NumNamedMembers;
13805   }
13806 
13807   // Okay, we successfully defined 'Record'.
13808   if (Record) {
13809     bool Completed = false;
13810     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
13811       if (!CXXRecord->isInvalidDecl()) {
13812         // Set access bits correctly on the directly-declared conversions.
13813         for (CXXRecordDecl::conversion_iterator
13814                I = CXXRecord->conversion_begin(),
13815                E = CXXRecord->conversion_end(); I != E; ++I)
13816           I.setAccess((*I)->getAccess());
13817 
13818         if (!CXXRecord->isDependentType()) {
13819           if (CXXRecord->hasUserDeclaredDestructor()) {
13820             // Adjust user-defined destructor exception spec.
13821             if (getLangOpts().CPlusPlus11)
13822               AdjustDestructorExceptionSpec(CXXRecord,
13823                                             CXXRecord->getDestructor());
13824           }
13825 
13826           // Add any implicitly-declared members to this class.
13827           AddImplicitlyDeclaredMembersToClass(CXXRecord);
13828 
13829           // If we have virtual base classes, we may end up finding multiple
13830           // final overriders for a given virtual function. Check for this
13831           // problem now.
13832           if (CXXRecord->getNumVBases()) {
13833             CXXFinalOverriderMap FinalOverriders;
13834             CXXRecord->getFinalOverriders(FinalOverriders);
13835 
13836             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
13837                                              MEnd = FinalOverriders.end();
13838                  M != MEnd; ++M) {
13839               for (OverridingMethods::iterator SO = M->second.begin(),
13840                                             SOEnd = M->second.end();
13841                    SO != SOEnd; ++SO) {
13842                 assert(SO->second.size() > 0 &&
13843                        "Virtual function without overridding functions?");
13844                 if (SO->second.size() == 1)
13845                   continue;
13846 
13847                 // C++ [class.virtual]p2:
13848                 //   In a derived class, if a virtual member function of a base
13849                 //   class subobject has more than one final overrider the
13850                 //   program is ill-formed.
13851                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
13852                   << (const NamedDecl *)M->first << Record;
13853                 Diag(M->first->getLocation(),
13854                      diag::note_overridden_virtual_function);
13855                 for (OverridingMethods::overriding_iterator
13856                           OM = SO->second.begin(),
13857                        OMEnd = SO->second.end();
13858                      OM != OMEnd; ++OM)
13859                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
13860                     << (const NamedDecl *)M->first << OM->Method->getParent();
13861 
13862                 Record->setInvalidDecl();
13863               }
13864             }
13865             CXXRecord->completeDefinition(&FinalOverriders);
13866             Completed = true;
13867           }
13868         }
13869       }
13870     }
13871 
13872     if (!Completed)
13873       Record->completeDefinition();
13874 
13875     if (Record->hasAttrs()) {
13876       CheckAlignasUnderalignment(Record);
13877 
13878       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
13879         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
13880                                            IA->getRange(), IA->getBestCase(),
13881                                            IA->getSemanticSpelling());
13882     }
13883 
13884     // Check if the structure/union declaration is a type that can have zero
13885     // size in C. For C this is a language extension, for C++ it may cause
13886     // compatibility problems.
13887     bool CheckForZeroSize;
13888     if (!getLangOpts().CPlusPlus) {
13889       CheckForZeroSize = true;
13890     } else {
13891       // For C++ filter out types that cannot be referenced in C code.
13892       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
13893       CheckForZeroSize =
13894           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
13895           !CXXRecord->isDependentType() &&
13896           CXXRecord->isCLike();
13897     }
13898     if (CheckForZeroSize) {
13899       bool ZeroSize = true;
13900       bool IsEmpty = true;
13901       unsigned NonBitFields = 0;
13902       for (RecordDecl::field_iterator I = Record->field_begin(),
13903                                       E = Record->field_end();
13904            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
13905         IsEmpty = false;
13906         if (I->isUnnamedBitfield()) {
13907           if (I->getBitWidthValue(Context) > 0)
13908             ZeroSize = false;
13909         } else {
13910           ++NonBitFields;
13911           QualType FieldType = I->getType();
13912           if (FieldType->isIncompleteType() ||
13913               !Context.getTypeSizeInChars(FieldType).isZero())
13914             ZeroSize = false;
13915         }
13916       }
13917 
13918       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
13919       // allowed in C++, but warn if its declaration is inside
13920       // extern "C" block.
13921       if (ZeroSize) {
13922         Diag(RecLoc, getLangOpts().CPlusPlus ?
13923                          diag::warn_zero_size_struct_union_in_extern_c :
13924                          diag::warn_zero_size_struct_union_compat)
13925           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
13926       }
13927 
13928       // Structs without named members are extension in C (C99 6.7.2.1p7),
13929       // but are accepted by GCC.
13930       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
13931         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
13932                                diag::ext_no_named_members_in_struct_union)
13933           << Record->isUnion();
13934       }
13935     }
13936   } else {
13937     ObjCIvarDecl **ClsFields =
13938       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
13939     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
13940       ID->setEndOfDefinitionLoc(RBrac);
13941       // Add ivar's to class's DeclContext.
13942       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13943         ClsFields[i]->setLexicalDeclContext(ID);
13944         ID->addDecl(ClsFields[i]);
13945       }
13946       // Must enforce the rule that ivars in the base classes may not be
13947       // duplicates.
13948       if (ID->getSuperClass())
13949         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
13950     } else if (ObjCImplementationDecl *IMPDecl =
13951                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13952       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
13953       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
13954         // Ivar declared in @implementation never belongs to the implementation.
13955         // Only it is in implementation's lexical context.
13956         ClsFields[I]->setLexicalDeclContext(IMPDecl);
13957       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
13958       IMPDecl->setIvarLBraceLoc(LBrac);
13959       IMPDecl->setIvarRBraceLoc(RBrac);
13960     } else if (ObjCCategoryDecl *CDecl =
13961                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13962       // case of ivars in class extension; all other cases have been
13963       // reported as errors elsewhere.
13964       // FIXME. Class extension does not have a LocEnd field.
13965       // CDecl->setLocEnd(RBrac);
13966       // Add ivar's to class extension's DeclContext.
13967       // Diagnose redeclaration of private ivars.
13968       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
13969       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13970         if (IDecl) {
13971           if (const ObjCIvarDecl *ClsIvar =
13972               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
13973             Diag(ClsFields[i]->getLocation(),
13974                  diag::err_duplicate_ivar_declaration);
13975             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
13976             continue;
13977           }
13978           for (const auto *Ext : IDecl->known_extensions()) {
13979             if (const ObjCIvarDecl *ClsExtIvar
13980                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
13981               Diag(ClsFields[i]->getLocation(),
13982                    diag::err_duplicate_ivar_declaration);
13983               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
13984               continue;
13985             }
13986           }
13987         }
13988         ClsFields[i]->setLexicalDeclContext(CDecl);
13989         CDecl->addDecl(ClsFields[i]);
13990       }
13991       CDecl->setIvarLBraceLoc(LBrac);
13992       CDecl->setIvarRBraceLoc(RBrac);
13993     }
13994   }
13995 
13996   if (Attr)
13997     ProcessDeclAttributeList(S, Record, Attr);
13998 }
13999 
14000 /// \brief Determine whether the given integral value is representable within
14001 /// the given type T.
14002 static bool isRepresentableIntegerValue(ASTContext &Context,
14003                                         llvm::APSInt &Value,
14004                                         QualType T) {
14005   assert(T->isIntegralType(Context) && "Integral type required!");
14006   unsigned BitWidth = Context.getIntWidth(T);
14007 
14008   if (Value.isUnsigned() || Value.isNonNegative()) {
14009     if (T->isSignedIntegerOrEnumerationType())
14010       --BitWidth;
14011     return Value.getActiveBits() <= BitWidth;
14012   }
14013   return Value.getMinSignedBits() <= BitWidth;
14014 }
14015 
14016 // \brief Given an integral type, return the next larger integral type
14017 // (or a NULL type of no such type exists).
14018 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14019   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14020   // enum checking below.
14021   assert(T->isIntegralType(Context) && "Integral type required!");
14022   const unsigned NumTypes = 4;
14023   QualType SignedIntegralTypes[NumTypes] = {
14024     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14025   };
14026   QualType UnsignedIntegralTypes[NumTypes] = {
14027     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14028     Context.UnsignedLongLongTy
14029   };
14030 
14031   unsigned BitWidth = Context.getTypeSize(T);
14032   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14033                                                         : UnsignedIntegralTypes;
14034   for (unsigned I = 0; I != NumTypes; ++I)
14035     if (Context.getTypeSize(Types[I]) > BitWidth)
14036       return Types[I];
14037 
14038   return QualType();
14039 }
14040 
14041 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14042                                           EnumConstantDecl *LastEnumConst,
14043                                           SourceLocation IdLoc,
14044                                           IdentifierInfo *Id,
14045                                           Expr *Val) {
14046   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14047   llvm::APSInt EnumVal(IntWidth);
14048   QualType EltTy;
14049 
14050   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14051     Val = nullptr;
14052 
14053   if (Val)
14054     Val = DefaultLvalueConversion(Val).get();
14055 
14056   if (Val) {
14057     if (Enum->isDependentType() || Val->isTypeDependent())
14058       EltTy = Context.DependentTy;
14059     else {
14060       SourceLocation ExpLoc;
14061       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14062           !getLangOpts().MSVCCompat) {
14063         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14064         // constant-expression in the enumerator-definition shall be a converted
14065         // constant expression of the underlying type.
14066         EltTy = Enum->getIntegerType();
14067         ExprResult Converted =
14068           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14069                                            CCEK_Enumerator);
14070         if (Converted.isInvalid())
14071           Val = nullptr;
14072         else
14073           Val = Converted.get();
14074       } else if (!Val->isValueDependent() &&
14075                  !(Val = VerifyIntegerConstantExpression(Val,
14076                                                          &EnumVal).get())) {
14077         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14078       } else {
14079         if (Enum->isFixed()) {
14080           EltTy = Enum->getIntegerType();
14081 
14082           // In Obj-C and Microsoft mode, require the enumeration value to be
14083           // representable in the underlying type of the enumeration. In C++11,
14084           // we perform a non-narrowing conversion as part of converted constant
14085           // expression checking.
14086           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14087             if (getLangOpts().MSVCCompat) {
14088               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14089               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14090             } else
14091               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14092           } else
14093             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14094         } else if (getLangOpts().CPlusPlus) {
14095           // C++11 [dcl.enum]p5:
14096           //   If the underlying type is not fixed, the type of each enumerator
14097           //   is the type of its initializing value:
14098           //     - If an initializer is specified for an enumerator, the
14099           //       initializing value has the same type as the expression.
14100           EltTy = Val->getType();
14101         } else {
14102           // C99 6.7.2.2p2:
14103           //   The expression that defines the value of an enumeration constant
14104           //   shall be an integer constant expression that has a value
14105           //   representable as an int.
14106 
14107           // Complain if the value is not representable in an int.
14108           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14109             Diag(IdLoc, diag::ext_enum_value_not_int)
14110               << EnumVal.toString(10) << Val->getSourceRange()
14111               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14112           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14113             // Force the type of the expression to 'int'.
14114             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14115           }
14116           EltTy = Val->getType();
14117         }
14118       }
14119     }
14120   }
14121 
14122   if (!Val) {
14123     if (Enum->isDependentType())
14124       EltTy = Context.DependentTy;
14125     else if (!LastEnumConst) {
14126       // C++0x [dcl.enum]p5:
14127       //   If the underlying type is not fixed, the type of each enumerator
14128       //   is the type of its initializing value:
14129       //     - If no initializer is specified for the first enumerator, the
14130       //       initializing value has an unspecified integral type.
14131       //
14132       // GCC uses 'int' for its unspecified integral type, as does
14133       // C99 6.7.2.2p3.
14134       if (Enum->isFixed()) {
14135         EltTy = Enum->getIntegerType();
14136       }
14137       else {
14138         EltTy = Context.IntTy;
14139       }
14140     } else {
14141       // Assign the last value + 1.
14142       EnumVal = LastEnumConst->getInitVal();
14143       ++EnumVal;
14144       EltTy = LastEnumConst->getType();
14145 
14146       // Check for overflow on increment.
14147       if (EnumVal < LastEnumConst->getInitVal()) {
14148         // C++0x [dcl.enum]p5:
14149         //   If the underlying type is not fixed, the type of each enumerator
14150         //   is the type of its initializing value:
14151         //
14152         //     - Otherwise the type of the initializing value is the same as
14153         //       the type of the initializing value of the preceding enumerator
14154         //       unless the incremented value is not representable in that type,
14155         //       in which case the type is an unspecified integral type
14156         //       sufficient to contain the incremented value. If no such type
14157         //       exists, the program is ill-formed.
14158         QualType T = getNextLargerIntegralType(Context, EltTy);
14159         if (T.isNull() || Enum->isFixed()) {
14160           // There is no integral type larger enough to represent this
14161           // value. Complain, then allow the value to wrap around.
14162           EnumVal = LastEnumConst->getInitVal();
14163           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14164           ++EnumVal;
14165           if (Enum->isFixed())
14166             // When the underlying type is fixed, this is ill-formed.
14167             Diag(IdLoc, diag::err_enumerator_wrapped)
14168               << EnumVal.toString(10)
14169               << EltTy;
14170           else
14171             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14172               << EnumVal.toString(10);
14173         } else {
14174           EltTy = T;
14175         }
14176 
14177         // Retrieve the last enumerator's value, extent that type to the
14178         // type that is supposed to be large enough to represent the incremented
14179         // value, then increment.
14180         EnumVal = LastEnumConst->getInitVal();
14181         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14182         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14183         ++EnumVal;
14184 
14185         // If we're not in C++, diagnose the overflow of enumerator values,
14186         // which in C99 means that the enumerator value is not representable in
14187         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14188         // permits enumerator values that are representable in some larger
14189         // integral type.
14190         if (!getLangOpts().CPlusPlus && !T.isNull())
14191           Diag(IdLoc, diag::warn_enum_value_overflow);
14192       } else if (!getLangOpts().CPlusPlus &&
14193                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14194         // Enforce C99 6.7.2.2p2 even when we compute the next value.
14195         Diag(IdLoc, diag::ext_enum_value_not_int)
14196           << EnumVal.toString(10) << 1;
14197       }
14198     }
14199   }
14200 
14201   if (!EltTy->isDependentType()) {
14202     // Make the enumerator value match the signedness and size of the
14203     // enumerator's type.
14204     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14205     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14206   }
14207 
14208   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14209                                   Val, EnumVal);
14210 }
14211 
14212 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14213                                                 SourceLocation IILoc) {
14214   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14215       !getLangOpts().CPlusPlus)
14216     return SkipBodyInfo();
14217 
14218   // We have an anonymous enum definition. Look up the first enumerator to
14219   // determine if we should merge the definition with an existing one and
14220   // skip the body.
14221   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14222                                          ForRedeclaration);
14223   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14224   if (!PrevECD)
14225     return SkipBodyInfo();
14226 
14227   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14228   NamedDecl *Hidden;
14229   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14230     SkipBodyInfo Skip;
14231     Skip.Previous = Hidden;
14232     return Skip;
14233   }
14234 
14235   return SkipBodyInfo();
14236 }
14237 
14238 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14239                               SourceLocation IdLoc, IdentifierInfo *Id,
14240                               AttributeList *Attr,
14241                               SourceLocation EqualLoc, Expr *Val) {
14242   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14243   EnumConstantDecl *LastEnumConst =
14244     cast_or_null<EnumConstantDecl>(lastEnumConst);
14245 
14246   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14247   // we find one that is.
14248   S = getNonFieldDeclScope(S);
14249 
14250   // Verify that there isn't already something declared with this name in this
14251   // scope.
14252   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14253                                          ForRedeclaration);
14254   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14255     // Maybe we will complain about the shadowed template parameter.
14256     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14257     // Just pretend that we didn't see the previous declaration.
14258     PrevDecl = nullptr;
14259   }
14260 
14261   // C++ [class.mem]p15:
14262   // If T is the name of a class, then each of the following shall have a name
14263   // different from T:
14264   // - every enumerator of every member of class T that is an unscoped
14265   // enumerated type
14266   if (!TheEnumDecl->isScoped())
14267     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14268                             DeclarationNameInfo(Id, IdLoc));
14269 
14270   EnumConstantDecl *New =
14271     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14272   if (!New)
14273     return nullptr;
14274 
14275   if (PrevDecl) {
14276     // When in C++, we may get a TagDecl with the same name; in this case the
14277     // enum constant will 'hide' the tag.
14278     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14279            "Received TagDecl when not in C++!");
14280     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14281         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14282       if (isa<EnumConstantDecl>(PrevDecl))
14283         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14284       else
14285         Diag(IdLoc, diag::err_redefinition) << Id;
14286       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14287       return nullptr;
14288     }
14289   }
14290 
14291   // Process attributes.
14292   if (Attr) ProcessDeclAttributeList(S, New, Attr);
14293 
14294   // Register this decl in the current scope stack.
14295   New->setAccess(TheEnumDecl->getAccess());
14296   PushOnScopeChains(New, S);
14297 
14298   ActOnDocumentableDecl(New);
14299 
14300   return New;
14301 }
14302 
14303 // Returns true when the enum initial expression does not trigger the
14304 // duplicate enum warning.  A few common cases are exempted as follows:
14305 // Element2 = Element1
14306 // Element2 = Element1 + 1
14307 // Element2 = Element1 - 1
14308 // Where Element2 and Element1 are from the same enum.
14309 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14310   Expr *InitExpr = ECD->getInitExpr();
14311   if (!InitExpr)
14312     return true;
14313   InitExpr = InitExpr->IgnoreImpCasts();
14314 
14315   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14316     if (!BO->isAdditiveOp())
14317       return true;
14318     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14319     if (!IL)
14320       return true;
14321     if (IL->getValue() != 1)
14322       return true;
14323 
14324     InitExpr = BO->getLHS();
14325   }
14326 
14327   // This checks if the elements are from the same enum.
14328   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14329   if (!DRE)
14330     return true;
14331 
14332   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14333   if (!EnumConstant)
14334     return true;
14335 
14336   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14337       Enum)
14338     return true;
14339 
14340   return false;
14341 }
14342 
14343 namespace {
14344 struct DupKey {
14345   int64_t val;
14346   bool isTombstoneOrEmptyKey;
14347   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14348     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14349 };
14350 
14351 static DupKey GetDupKey(const llvm::APSInt& Val) {
14352   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14353                 false);
14354 }
14355 
14356 struct DenseMapInfoDupKey {
14357   static DupKey getEmptyKey() { return DupKey(0, true); }
14358   static DupKey getTombstoneKey() { return DupKey(1, true); }
14359   static unsigned getHashValue(const DupKey Key) {
14360     return (unsigned)(Key.val * 37);
14361   }
14362   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14363     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14364            LHS.val == RHS.val;
14365   }
14366 };
14367 } // end anonymous namespace
14368 
14369 // Emits a warning when an element is implicitly set a value that
14370 // a previous element has already been set to.
14371 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14372                                         EnumDecl *Enum,
14373                                         QualType EnumType) {
14374   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14375     return;
14376   // Avoid anonymous enums
14377   if (!Enum->getIdentifier())
14378     return;
14379 
14380   // Only check for small enums.
14381   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14382     return;
14383 
14384   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14385   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14386 
14387   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14388   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14389           ValueToVectorMap;
14390 
14391   DuplicatesVector DupVector;
14392   ValueToVectorMap EnumMap;
14393 
14394   // Populate the EnumMap with all values represented by enum constants without
14395   // an initialier.
14396   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14397     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14398 
14399     // Null EnumConstantDecl means a previous diagnostic has been emitted for
14400     // this constant.  Skip this enum since it may be ill-formed.
14401     if (!ECD) {
14402       return;
14403     }
14404 
14405     if (ECD->getInitExpr())
14406       continue;
14407 
14408     DupKey Key = GetDupKey(ECD->getInitVal());
14409     DeclOrVector &Entry = EnumMap[Key];
14410 
14411     // First time encountering this value.
14412     if (Entry.isNull())
14413       Entry = ECD;
14414   }
14415 
14416   // Create vectors for any values that has duplicates.
14417   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14418     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14419     if (!ValidDuplicateEnum(ECD, Enum))
14420       continue;
14421 
14422     DupKey Key = GetDupKey(ECD->getInitVal());
14423 
14424     DeclOrVector& Entry = EnumMap[Key];
14425     if (Entry.isNull())
14426       continue;
14427 
14428     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14429       // Ensure constants are different.
14430       if (D == ECD)
14431         continue;
14432 
14433       // Create new vector and push values onto it.
14434       ECDVector *Vec = new ECDVector();
14435       Vec->push_back(D);
14436       Vec->push_back(ECD);
14437 
14438       // Update entry to point to the duplicates vector.
14439       Entry = Vec;
14440 
14441       // Store the vector somewhere we can consult later for quick emission of
14442       // diagnostics.
14443       DupVector.push_back(Vec);
14444       continue;
14445     }
14446 
14447     ECDVector *Vec = Entry.get<ECDVector*>();
14448     // Make sure constants are not added more than once.
14449     if (*Vec->begin() == ECD)
14450       continue;
14451 
14452     Vec->push_back(ECD);
14453   }
14454 
14455   // Emit diagnostics.
14456   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14457                                   DupVectorEnd = DupVector.end();
14458        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14459     ECDVector *Vec = *DupVectorIter;
14460     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14461 
14462     // Emit warning for one enum constant.
14463     ECDVector::iterator I = Vec->begin();
14464     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14465       << (*I)->getName() << (*I)->getInitVal().toString(10)
14466       << (*I)->getSourceRange();
14467     ++I;
14468 
14469     // Emit one note for each of the remaining enum constants with
14470     // the same value.
14471     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14472       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14473         << (*I)->getName() << (*I)->getInitVal().toString(10)
14474         << (*I)->getSourceRange();
14475     delete Vec;
14476   }
14477 }
14478 
14479 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14480                              bool AllowMask) const {
14481   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14482   assert(ED->isCompleteDefinition() && "expected enum definition");
14483 
14484   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14485   llvm::APInt &FlagBits = R.first->second;
14486 
14487   if (R.second) {
14488     for (auto *E : ED->enumerators()) {
14489       const auto &EVal = E->getInitVal();
14490       // Only single-bit enumerators introduce new flag values.
14491       if (EVal.isPowerOf2())
14492         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14493     }
14494   }
14495 
14496   // A value is in a flag enum if either its bits are a subset of the enum's
14497   // flag bits (the first condition) or we are allowing masks and the same is
14498   // true of its complement (the second condition). When masks are allowed, we
14499   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14500   //
14501   // While it's true that any value could be used as a mask, the assumption is
14502   // that a mask will have all of the insignificant bits set. Anything else is
14503   // likely a logic error.
14504   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14505   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14506 }
14507 
14508 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14509                          SourceLocation RBraceLoc, Decl *EnumDeclX,
14510                          ArrayRef<Decl *> Elements,
14511                          Scope *S, AttributeList *Attr) {
14512   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14513   QualType EnumType = Context.getTypeDeclType(Enum);
14514 
14515   if (Attr)
14516     ProcessDeclAttributeList(S, Enum, Attr);
14517 
14518   if (Enum->isDependentType()) {
14519     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14520       EnumConstantDecl *ECD =
14521         cast_or_null<EnumConstantDecl>(Elements[i]);
14522       if (!ECD) continue;
14523 
14524       ECD->setType(EnumType);
14525     }
14526 
14527     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14528     return;
14529   }
14530 
14531   // TODO: If the result value doesn't fit in an int, it must be a long or long
14532   // long value.  ISO C does not support this, but GCC does as an extension,
14533   // emit a warning.
14534   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14535   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14536   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14537 
14538   // Verify that all the values are okay, compute the size of the values, and
14539   // reverse the list.
14540   unsigned NumNegativeBits = 0;
14541   unsigned NumPositiveBits = 0;
14542 
14543   // Keep track of whether all elements have type int.
14544   bool AllElementsInt = true;
14545 
14546   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14547     EnumConstantDecl *ECD =
14548       cast_or_null<EnumConstantDecl>(Elements[i]);
14549     if (!ECD) continue;  // Already issued a diagnostic.
14550 
14551     const llvm::APSInt &InitVal = ECD->getInitVal();
14552 
14553     // Keep track of the size of positive and negative values.
14554     if (InitVal.isUnsigned() || InitVal.isNonNegative())
14555       NumPositiveBits = std::max(NumPositiveBits,
14556                                  (unsigned)InitVal.getActiveBits());
14557     else
14558       NumNegativeBits = std::max(NumNegativeBits,
14559                                  (unsigned)InitVal.getMinSignedBits());
14560 
14561     // Keep track of whether every enum element has type int (very commmon).
14562     if (AllElementsInt)
14563       AllElementsInt = ECD->getType() == Context.IntTy;
14564   }
14565 
14566   // Figure out the type that should be used for this enum.
14567   QualType BestType;
14568   unsigned BestWidth;
14569 
14570   // C++0x N3000 [conv.prom]p3:
14571   //   An rvalue of an unscoped enumeration type whose underlying
14572   //   type is not fixed can be converted to an rvalue of the first
14573   //   of the following types that can represent all the values of
14574   //   the enumeration: int, unsigned int, long int, unsigned long
14575   //   int, long long int, or unsigned long long int.
14576   // C99 6.4.4.3p2:
14577   //   An identifier declared as an enumeration constant has type int.
14578   // The C99 rule is modified by a gcc extension
14579   QualType BestPromotionType;
14580 
14581   bool Packed = Enum->hasAttr<PackedAttr>();
14582   // -fshort-enums is the equivalent to specifying the packed attribute on all
14583   // enum definitions.
14584   if (LangOpts.ShortEnums)
14585     Packed = true;
14586 
14587   if (Enum->isFixed()) {
14588     BestType = Enum->getIntegerType();
14589     if (BestType->isPromotableIntegerType())
14590       BestPromotionType = Context.getPromotedIntegerType(BestType);
14591     else
14592       BestPromotionType = BestType;
14593 
14594     BestWidth = Context.getIntWidth(BestType);
14595   }
14596   else if (NumNegativeBits) {
14597     // If there is a negative value, figure out the smallest integer type (of
14598     // int/long/longlong) that fits.
14599     // If it's packed, check also if it fits a char or a short.
14600     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14601       BestType = Context.SignedCharTy;
14602       BestWidth = CharWidth;
14603     } else if (Packed && NumNegativeBits <= ShortWidth &&
14604                NumPositiveBits < ShortWidth) {
14605       BestType = Context.ShortTy;
14606       BestWidth = ShortWidth;
14607     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14608       BestType = Context.IntTy;
14609       BestWidth = IntWidth;
14610     } else {
14611       BestWidth = Context.getTargetInfo().getLongWidth();
14612 
14613       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14614         BestType = Context.LongTy;
14615       } else {
14616         BestWidth = Context.getTargetInfo().getLongLongWidth();
14617 
14618         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14619           Diag(Enum->getLocation(), diag::ext_enum_too_large);
14620         BestType = Context.LongLongTy;
14621       }
14622     }
14623     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14624   } else {
14625     // If there is no negative value, figure out the smallest type that fits
14626     // all of the enumerator values.
14627     // If it's packed, check also if it fits a char or a short.
14628     if (Packed && NumPositiveBits <= CharWidth) {
14629       BestType = Context.UnsignedCharTy;
14630       BestPromotionType = Context.IntTy;
14631       BestWidth = CharWidth;
14632     } else if (Packed && NumPositiveBits <= ShortWidth) {
14633       BestType = Context.UnsignedShortTy;
14634       BestPromotionType = Context.IntTy;
14635       BestWidth = ShortWidth;
14636     } else if (NumPositiveBits <= IntWidth) {
14637       BestType = Context.UnsignedIntTy;
14638       BestWidth = IntWidth;
14639       BestPromotionType
14640         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14641                            ? Context.UnsignedIntTy : Context.IntTy;
14642     } else if (NumPositiveBits <=
14643                (BestWidth = Context.getTargetInfo().getLongWidth())) {
14644       BestType = Context.UnsignedLongTy;
14645       BestPromotionType
14646         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14647                            ? Context.UnsignedLongTy : Context.LongTy;
14648     } else {
14649       BestWidth = Context.getTargetInfo().getLongLongWidth();
14650       assert(NumPositiveBits <= BestWidth &&
14651              "How could an initializer get larger than ULL?");
14652       BestType = Context.UnsignedLongLongTy;
14653       BestPromotionType
14654         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14655                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
14656     }
14657   }
14658 
14659   // Loop over all of the enumerator constants, changing their types to match
14660   // the type of the enum if needed.
14661   for (auto *D : Elements) {
14662     auto *ECD = cast_or_null<EnumConstantDecl>(D);
14663     if (!ECD) continue;  // Already issued a diagnostic.
14664 
14665     // Standard C says the enumerators have int type, but we allow, as an
14666     // extension, the enumerators to be larger than int size.  If each
14667     // enumerator value fits in an int, type it as an int, otherwise type it the
14668     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
14669     // that X has type 'int', not 'unsigned'.
14670 
14671     // Determine whether the value fits into an int.
14672     llvm::APSInt InitVal = ECD->getInitVal();
14673 
14674     // If it fits into an integer type, force it.  Otherwise force it to match
14675     // the enum decl type.
14676     QualType NewTy;
14677     unsigned NewWidth;
14678     bool NewSign;
14679     if (!getLangOpts().CPlusPlus &&
14680         !Enum->isFixed() &&
14681         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14682       NewTy = Context.IntTy;
14683       NewWidth = IntWidth;
14684       NewSign = true;
14685     } else if (ECD->getType() == BestType) {
14686       // Already the right type!
14687       if (getLangOpts().CPlusPlus)
14688         // C++ [dcl.enum]p4: Following the closing brace of an
14689         // enum-specifier, each enumerator has the type of its
14690         // enumeration.
14691         ECD->setType(EnumType);
14692       continue;
14693     } else {
14694       NewTy = BestType;
14695       NewWidth = BestWidth;
14696       NewSign = BestType->isSignedIntegerOrEnumerationType();
14697     }
14698 
14699     // Adjust the APSInt value.
14700     InitVal = InitVal.extOrTrunc(NewWidth);
14701     InitVal.setIsSigned(NewSign);
14702     ECD->setInitVal(InitVal);
14703 
14704     // Adjust the Expr initializer and type.
14705     if (ECD->getInitExpr() &&
14706         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14707       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14708                                                 CK_IntegralCast,
14709                                                 ECD->getInitExpr(),
14710                                                 /*base paths*/ nullptr,
14711                                                 VK_RValue));
14712     if (getLangOpts().CPlusPlus)
14713       // C++ [dcl.enum]p4: Following the closing brace of an
14714       // enum-specifier, each enumerator has the type of its
14715       // enumeration.
14716       ECD->setType(EnumType);
14717     else
14718       ECD->setType(NewTy);
14719   }
14720 
14721   Enum->completeDefinition(BestType, BestPromotionType,
14722                            NumPositiveBits, NumNegativeBits);
14723 
14724   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14725 
14726   if (Enum->hasAttr<FlagEnumAttr>()) {
14727     for (Decl *D : Elements) {
14728       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14729       if (!ECD) continue;  // Already issued a diagnostic.
14730 
14731       llvm::APSInt InitVal = ECD->getInitVal();
14732       if (InitVal != 0 && !InitVal.isPowerOf2() &&
14733           !IsValueInFlagEnum(Enum, InitVal, true))
14734         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14735           << ECD << Enum;
14736     }
14737   }
14738 
14739   // Now that the enum type is defined, ensure it's not been underaligned.
14740   if (Enum->hasAttrs())
14741     CheckAlignasUnderalignment(Enum);
14742 }
14743 
14744 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
14745                                   SourceLocation StartLoc,
14746                                   SourceLocation EndLoc) {
14747   StringLiteral *AsmString = cast<StringLiteral>(expr);
14748 
14749   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
14750                                                    AsmString, StartLoc,
14751                                                    EndLoc);
14752   CurContext->addDecl(New);
14753   return New;
14754 }
14755 
14756 static void checkModuleImportContext(Sema &S, Module *M,
14757                                      SourceLocation ImportLoc, DeclContext *DC,
14758                                      bool FromInclude = false) {
14759   SourceLocation ExternCLoc;
14760 
14761   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14762     switch (LSD->getLanguage()) {
14763     case LinkageSpecDecl::lang_c:
14764       if (ExternCLoc.isInvalid())
14765         ExternCLoc = LSD->getLocStart();
14766       break;
14767     case LinkageSpecDecl::lang_cxx:
14768       break;
14769     }
14770     DC = LSD->getParent();
14771   }
14772 
14773   while (isa<LinkageSpecDecl>(DC))
14774     DC = DC->getParent();
14775 
14776   if (!isa<TranslationUnitDecl>(DC)) {
14777     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
14778                           ? diag::ext_module_import_not_at_top_level_noop
14779                           : diag::err_module_import_not_at_top_level_fatal)
14780         << M->getFullModuleName() << DC;
14781     S.Diag(cast<Decl>(DC)->getLocStart(),
14782            diag::note_module_import_not_at_top_level) << DC;
14783   } else if (!M->IsExternC && ExternCLoc.isValid()) {
14784     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
14785       << M->getFullModuleName();
14786     S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
14787   }
14788 }
14789 
14790 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
14791   return checkModuleImportContext(*this, M, ImportLoc, CurContext);
14792 }
14793 
14794 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
14795                                    SourceLocation ImportLoc,
14796                                    ModuleIdPath Path) {
14797   Module *Mod =
14798       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
14799                                    /*IsIncludeDirective=*/false);
14800   if (!Mod)
14801     return true;
14802 
14803   VisibleModules.setVisible(Mod, ImportLoc);
14804 
14805   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
14806 
14807   // FIXME: we should support importing a submodule within a different submodule
14808   // of the same top-level module. Until we do, make it an error rather than
14809   // silently ignoring the import.
14810   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
14811     Diag(ImportLoc, getLangOpts().CompilingModule
14812                         ? diag::err_module_self_import
14813                         : diag::err_module_import_in_implementation)
14814         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
14815 
14816   SmallVector<SourceLocation, 2> IdentifierLocs;
14817   Module *ModCheck = Mod;
14818   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
14819     // If we've run out of module parents, just drop the remaining identifiers.
14820     // We need the length to be consistent.
14821     if (!ModCheck)
14822       break;
14823     ModCheck = ModCheck->Parent;
14824 
14825     IdentifierLocs.push_back(Path[I].second);
14826   }
14827 
14828   ImportDecl *Import = ImportDecl::Create(Context,
14829                                           Context.getTranslationUnitDecl(),
14830                                           AtLoc.isValid()? AtLoc : ImportLoc,
14831                                           Mod, IdentifierLocs);
14832   Context.getTranslationUnitDecl()->addDecl(Import);
14833   return Import;
14834 }
14835 
14836 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
14837   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
14838 
14839   // Determine whether we're in the #include buffer for a module. The #includes
14840   // in that buffer do not qualify as module imports; they're just an
14841   // implementation detail of us building the module.
14842   //
14843   // FIXME: Should we even get ActOnModuleInclude calls for those?
14844   bool IsInModuleIncludes =
14845       TUKind == TU_Module &&
14846       getSourceManager().isWrittenInMainFile(DirectiveLoc);
14847 
14848   // Similarly, if we're in the implementation of a module, don't
14849   // synthesize an illegal module import. FIXME: Why not?
14850   bool ShouldAddImport =
14851       !IsInModuleIncludes &&
14852       (getLangOpts().CompilingModule ||
14853        getLangOpts().CurrentModule.empty() ||
14854        getLangOpts().CurrentModule != Mod->getTopLevelModuleName());
14855 
14856   // If this module import was due to an inclusion directive, create an
14857   // implicit import declaration to capture it in the AST.
14858   if (ShouldAddImport) {
14859     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14860     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14861                                                      DirectiveLoc, Mod,
14862                                                      DirectiveLoc);
14863     TU->addDecl(ImportD);
14864     Consumer.HandleImplicitImportDecl(ImportD);
14865   }
14866 
14867   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
14868   VisibleModules.setVisible(Mod, DirectiveLoc);
14869 }
14870 
14871 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
14872   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14873 
14874   if (getLangOpts().ModulesLocalVisibility)
14875     VisibleModulesStack.push_back(std::move(VisibleModules));
14876   VisibleModules.setVisible(Mod, DirectiveLoc);
14877 }
14878 
14879 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
14880   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14881 
14882   if (getLangOpts().ModulesLocalVisibility) {
14883     VisibleModules = std::move(VisibleModulesStack.back());
14884     VisibleModulesStack.pop_back();
14885     VisibleModules.setVisible(Mod, DirectiveLoc);
14886     // Leaving a module hides namespace names, so our visible namespace cache
14887     // is now out of date.
14888     VisibleNamespaceCache.clear();
14889   }
14890 }
14891 
14892 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
14893                                                       Module *Mod) {
14894   // Bail if we're not allowed to implicitly import a module here.
14895   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
14896     return;
14897 
14898   // Create the implicit import declaration.
14899   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14900   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14901                                                    Loc, Mod, Loc);
14902   TU->addDecl(ImportD);
14903   Consumer.HandleImplicitImportDecl(ImportD);
14904 
14905   // Make the module visible.
14906   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
14907   VisibleModules.setVisible(Mod, Loc);
14908 }
14909 
14910 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
14911                                       IdentifierInfo* AliasName,
14912                                       SourceLocation PragmaLoc,
14913                                       SourceLocation NameLoc,
14914                                       SourceLocation AliasNameLoc) {
14915   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
14916                                          LookupOrdinaryName);
14917   AsmLabelAttr *Attr =
14918       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
14919 
14920   // If a declaration that:
14921   // 1) declares a function or a variable
14922   // 2) has external linkage
14923   // already exists, add a label attribute to it.
14924   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
14925     if (isDeclExternC(PrevDecl))
14926       PrevDecl->addAttr(Attr);
14927     else
14928       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
14929           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
14930   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
14931   } else
14932     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
14933 }
14934 
14935 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
14936                              SourceLocation PragmaLoc,
14937                              SourceLocation NameLoc) {
14938   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
14939 
14940   if (PrevDecl) {
14941     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
14942   } else {
14943     (void)WeakUndeclaredIdentifiers.insert(
14944       std::pair<IdentifierInfo*,WeakInfo>
14945         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
14946   }
14947 }
14948 
14949 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
14950                                 IdentifierInfo* AliasName,
14951                                 SourceLocation PragmaLoc,
14952                                 SourceLocation NameLoc,
14953                                 SourceLocation AliasNameLoc) {
14954   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
14955                                     LookupOrdinaryName);
14956   WeakInfo W = WeakInfo(Name, NameLoc);
14957 
14958   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
14959     if (!PrevDecl->hasAttr<AliasAttr>())
14960       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
14961         DeclApplyPragmaWeak(TUScope, ND, W);
14962   } else {
14963     (void)WeakUndeclaredIdentifiers.insert(
14964       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
14965   }
14966 }
14967 
14968 Decl *Sema::getObjCDeclContext() const {
14969   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
14970 }
14971 
14972 AvailabilityResult Sema::getCurContextAvailability() const {
14973   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
14974   if (!D)
14975     return AR_Available;
14976 
14977   // If we are within an Objective-C method, we should consult
14978   // both the availability of the method as well as the
14979   // enclosing class.  If the class is (say) deprecated,
14980   // the entire method is considered deprecated from the
14981   // purpose of checking if the current context is deprecated.
14982   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
14983     AvailabilityResult R = MD->getAvailability();
14984     if (R != AR_Available)
14985       return R;
14986     D = MD->getClassInterface();
14987   }
14988   // If we are within an Objective-c @implementation, it
14989   // gets the same availability context as the @interface.
14990   else if (const ObjCImplementationDecl *ID =
14991             dyn_cast<ObjCImplementationDecl>(D)) {
14992     D = ID->getClassInterface();
14993   }
14994   // Recover from user error.
14995   return D ? D->getAvailability() : AR_Available;
14996 }
14997