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, and warn on it if we haven't
1614     // already.
1615     IdResolver.RemoveDecl(D);
1616     auto ShadowI = ShadowingDecls.find(D);
1617     if (ShadowI != ShadowingDecls.end()) {
1618       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1619         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1620             << D << FD << FD->getParent();
1621         Diag(FD->getLocation(), diag::note_previous_declaration);
1622       }
1623       ShadowingDecls.erase(ShadowI);
1624     }
1625   }
1626 }
1627 
1628 /// \brief Look for an Objective-C class in the translation unit.
1629 ///
1630 /// \param Id The name of the Objective-C class we're looking for. If
1631 /// typo-correction fixes this name, the Id will be updated
1632 /// to the fixed name.
1633 ///
1634 /// \param IdLoc The location of the name in the translation unit.
1635 ///
1636 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1637 /// if there is no class with the given name.
1638 ///
1639 /// \returns The declaration of the named Objective-C class, or NULL if the
1640 /// class could not be found.
1641 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1642                                               SourceLocation IdLoc,
1643                                               bool DoTypoCorrection) {
1644   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1645   // creation from this context.
1646   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1647 
1648   if (!IDecl && DoTypoCorrection) {
1649     // Perform typo correction at the given location, but only if we
1650     // find an Objective-C class name.
1651     if (TypoCorrection C = CorrectTypo(
1652             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1653             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1654             CTK_ErrorRecovery)) {
1655       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1656       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1657       Id = IDecl->getIdentifier();
1658     }
1659   }
1660   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1661   // This routine must always return a class definition, if any.
1662   if (Def && Def->getDefinition())
1663       Def = Def->getDefinition();
1664   return Def;
1665 }
1666 
1667 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1668 /// from S, where a non-field would be declared. This routine copes
1669 /// with the difference between C and C++ scoping rules in structs and
1670 /// unions. For example, the following code is well-formed in C but
1671 /// ill-formed in C++:
1672 /// @code
1673 /// struct S6 {
1674 ///   enum { BAR } e;
1675 /// };
1676 ///
1677 /// void test_S6() {
1678 ///   struct S6 a;
1679 ///   a.e = BAR;
1680 /// }
1681 /// @endcode
1682 /// For the declaration of BAR, this routine will return a different
1683 /// scope. The scope S will be the scope of the unnamed enumeration
1684 /// within S6. In C++, this routine will return the scope associated
1685 /// with S6, because the enumeration's scope is a transparent
1686 /// context but structures can contain non-field names. In C, this
1687 /// routine will return the translation unit scope, since the
1688 /// enumeration's scope is a transparent context and structures cannot
1689 /// contain non-field names.
1690 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1691   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1692          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1693          (S->isClassScope() && !getLangOpts().CPlusPlus))
1694     S = S->getParent();
1695   return S;
1696 }
1697 
1698 /// \brief Looks up the declaration of "struct objc_super" and
1699 /// saves it for later use in building builtin declaration of
1700 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1701 /// pre-existing declaration exists no action takes place.
1702 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1703                                         IdentifierInfo *II) {
1704   if (!II->isStr("objc_msgSendSuper"))
1705     return;
1706   ASTContext &Context = ThisSema.Context;
1707 
1708   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1709                       SourceLocation(), Sema::LookupTagName);
1710   ThisSema.LookupName(Result, S);
1711   if (Result.getResultKind() == LookupResult::Found)
1712     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1713       Context.setObjCSuperType(Context.getTagDeclType(TD));
1714 }
1715 
1716 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1717   switch (Error) {
1718   case ASTContext::GE_None:
1719     return "";
1720   case ASTContext::GE_Missing_stdio:
1721     return "stdio.h";
1722   case ASTContext::GE_Missing_setjmp:
1723     return "setjmp.h";
1724   case ASTContext::GE_Missing_ucontext:
1725     return "ucontext.h";
1726   }
1727   llvm_unreachable("unhandled error kind");
1728 }
1729 
1730 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1731 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1732 /// if we're creating this built-in in anticipation of redeclaring the
1733 /// built-in.
1734 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1735                                      Scope *S, bool ForRedeclaration,
1736                                      SourceLocation Loc) {
1737   LookupPredefedObjCSuperType(*this, S, II);
1738 
1739   ASTContext::GetBuiltinTypeError Error;
1740   QualType R = Context.GetBuiltinType(ID, Error);
1741   if (Error) {
1742     if (ForRedeclaration)
1743       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1744           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1745     return nullptr;
1746   }
1747 
1748   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1749     Diag(Loc, diag::ext_implicit_lib_function_decl)
1750         << Context.BuiltinInfo.getName(ID) << R;
1751     if (Context.BuiltinInfo.getHeaderName(ID) &&
1752         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1753       Diag(Loc, diag::note_include_header_or_declare)
1754           << Context.BuiltinInfo.getHeaderName(ID)
1755           << Context.BuiltinInfo.getName(ID);
1756   }
1757 
1758   if (R.isNull())
1759     return nullptr;
1760 
1761   DeclContext *Parent = Context.getTranslationUnitDecl();
1762   if (getLangOpts().CPlusPlus) {
1763     LinkageSpecDecl *CLinkageDecl =
1764         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1765                                 LinkageSpecDecl::lang_c, false);
1766     CLinkageDecl->setImplicit();
1767     Parent->addDecl(CLinkageDecl);
1768     Parent = CLinkageDecl;
1769   }
1770 
1771   FunctionDecl *New = FunctionDecl::Create(Context,
1772                                            Parent,
1773                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1774                                            SC_Extern,
1775                                            false,
1776                                            R->isFunctionProtoType());
1777   New->setImplicit();
1778 
1779   // Create Decl objects for each parameter, adding them to the
1780   // FunctionDecl.
1781   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1782     SmallVector<ParmVarDecl*, 16> Params;
1783     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1784       ParmVarDecl *parm =
1785           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1786                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1787                               SC_None, nullptr);
1788       parm->setScopeInfo(0, i);
1789       Params.push_back(parm);
1790     }
1791     New->setParams(Params);
1792   }
1793 
1794   AddKnownFunctionAttributes(New);
1795   RegisterLocallyScopedExternCDecl(New, S);
1796 
1797   // TUScope is the translation-unit scope to insert this function into.
1798   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1799   // relate Scopes to DeclContexts, and probably eliminate CurContext
1800   // entirely, but we're not there yet.
1801   DeclContext *SavedContext = CurContext;
1802   CurContext = Parent;
1803   PushOnScopeChains(New, TUScope);
1804   CurContext = SavedContext;
1805   return New;
1806 }
1807 
1808 /// Typedef declarations don't have linkage, but they still denote the same
1809 /// entity if their types are the same.
1810 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1811 /// isSameEntity.
1812 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1813                                                      TypedefNameDecl *Decl,
1814                                                      LookupResult &Previous) {
1815   // This is only interesting when modules are enabled.
1816   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1817     return;
1818 
1819   // Empty sets are uninteresting.
1820   if (Previous.empty())
1821     return;
1822 
1823   LookupResult::Filter Filter = Previous.makeFilter();
1824   while (Filter.hasNext()) {
1825     NamedDecl *Old = Filter.next();
1826 
1827     // Non-hidden declarations are never ignored.
1828     if (S.isVisible(Old))
1829       continue;
1830 
1831     // Declarations of the same entity are not ignored, even if they have
1832     // different linkages.
1833     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1834       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1835                                 Decl->getUnderlyingType()))
1836         continue;
1837 
1838       // If both declarations give a tag declaration a typedef name for linkage
1839       // purposes, then they declare the same entity.
1840       if (S.getLangOpts().CPlusPlus &&
1841           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1842           Decl->getAnonDeclWithTypedefName())
1843         continue;
1844     }
1845 
1846     Filter.erase();
1847   }
1848 
1849   Filter.done();
1850 }
1851 
1852 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1853   QualType OldType;
1854   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1855     OldType = OldTypedef->getUnderlyingType();
1856   else
1857     OldType = Context.getTypeDeclType(Old);
1858   QualType NewType = New->getUnderlyingType();
1859 
1860   if (NewType->isVariablyModifiedType()) {
1861     // Must not redefine a typedef with a variably-modified type.
1862     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1863     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1864       << Kind << NewType;
1865     if (Old->getLocation().isValid())
1866       Diag(Old->getLocation(), diag::note_previous_definition);
1867     New->setInvalidDecl();
1868     return true;
1869   }
1870 
1871   if (OldType != NewType &&
1872       !OldType->isDependentType() &&
1873       !NewType->isDependentType() &&
1874       !Context.hasSameType(OldType, NewType)) {
1875     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1876     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1877       << Kind << NewType << OldType;
1878     if (Old->getLocation().isValid())
1879       Diag(Old->getLocation(), diag::note_previous_definition);
1880     New->setInvalidDecl();
1881     return true;
1882   }
1883   return false;
1884 }
1885 
1886 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1887 /// same name and scope as a previous declaration 'Old'.  Figure out
1888 /// how to resolve this situation, merging decls or emitting
1889 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1890 ///
1891 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1892                                 LookupResult &OldDecls) {
1893   // If the new decl is known invalid already, don't bother doing any
1894   // merging checks.
1895   if (New->isInvalidDecl()) return;
1896 
1897   // Allow multiple definitions for ObjC built-in typedefs.
1898   // FIXME: Verify the underlying types are equivalent!
1899   if (getLangOpts().ObjC1) {
1900     const IdentifierInfo *TypeID = New->getIdentifier();
1901     switch (TypeID->getLength()) {
1902     default: break;
1903     case 2:
1904       {
1905         if (!TypeID->isStr("id"))
1906           break;
1907         QualType T = New->getUnderlyingType();
1908         if (!T->isPointerType())
1909           break;
1910         if (!T->isVoidPointerType()) {
1911           QualType PT = T->getAs<PointerType>()->getPointeeType();
1912           if (!PT->isStructureType())
1913             break;
1914         }
1915         Context.setObjCIdRedefinitionType(T);
1916         // Install the built-in type for 'id', ignoring the current definition.
1917         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1918         return;
1919       }
1920     case 5:
1921       if (!TypeID->isStr("Class"))
1922         break;
1923       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1924       // Install the built-in type for 'Class', ignoring the current definition.
1925       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1926       return;
1927     case 3:
1928       if (!TypeID->isStr("SEL"))
1929         break;
1930       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1931       // Install the built-in type for 'SEL', ignoring the current definition.
1932       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1933       return;
1934     }
1935     // Fall through - the typedef name was not a builtin type.
1936   }
1937 
1938   // Verify the old decl was also a type.
1939   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1940   if (!Old) {
1941     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1942       << New->getDeclName();
1943 
1944     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1945     if (OldD->getLocation().isValid())
1946       Diag(OldD->getLocation(), diag::note_previous_definition);
1947 
1948     return New->setInvalidDecl();
1949   }
1950 
1951   // If the old declaration is invalid, just give up here.
1952   if (Old->isInvalidDecl())
1953     return New->setInvalidDecl();
1954 
1955   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1956     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
1957     auto *NewTag = New->getAnonDeclWithTypedefName();
1958     NamedDecl *Hidden = nullptr;
1959     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
1960         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
1961         !hasVisibleDefinition(OldTag, &Hidden)) {
1962       // There is a definition of this tag, but it is not visible. Use it
1963       // instead of our tag.
1964       New->setTypeForDecl(OldTD->getTypeForDecl());
1965       if (OldTD->isModed())
1966         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
1967                                     OldTD->getUnderlyingType());
1968       else
1969         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
1970 
1971       // Make the old tag definition visible.
1972       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
1973 
1974       // If this was an unscoped enumeration, yank all of its enumerators
1975       // out of the scope.
1976       if (isa<EnumDecl>(NewTag)) {
1977         Scope *EnumScope = getNonFieldDeclScope(S);
1978         for (auto *D : NewTag->decls()) {
1979           auto *ED = cast<EnumConstantDecl>(D);
1980           assert(EnumScope->isDeclScope(ED));
1981           EnumScope->RemoveDecl(ED);
1982           IdResolver.RemoveDecl(ED);
1983           ED->getLexicalDeclContext()->removeDecl(ED);
1984         }
1985       }
1986     }
1987   }
1988 
1989   // If the typedef types are not identical, reject them in all languages and
1990   // with any extensions enabled.
1991   if (isIncompatibleTypedef(Old, New))
1992     return;
1993 
1994   // The types match.  Link up the redeclaration chain and merge attributes if
1995   // the old declaration was a typedef.
1996   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1997     New->setPreviousDecl(Typedef);
1998     mergeDeclAttributes(New, Old);
1999   }
2000 
2001   if (getLangOpts().MicrosoftExt)
2002     return;
2003 
2004   if (getLangOpts().CPlusPlus) {
2005     // C++ [dcl.typedef]p2:
2006     //   In a given non-class scope, a typedef specifier can be used to
2007     //   redefine the name of any type declared in that scope to refer
2008     //   to the type to which it already refers.
2009     if (!isa<CXXRecordDecl>(CurContext))
2010       return;
2011 
2012     // C++0x [dcl.typedef]p4:
2013     //   In a given class scope, a typedef specifier can be used to redefine
2014     //   any class-name declared in that scope that is not also a typedef-name
2015     //   to refer to the type to which it already refers.
2016     //
2017     // This wording came in via DR424, which was a correction to the
2018     // wording in DR56, which accidentally banned code like:
2019     //
2020     //   struct S {
2021     //     typedef struct A { } A;
2022     //   };
2023     //
2024     // in the C++03 standard. We implement the C++0x semantics, which
2025     // allow the above but disallow
2026     //
2027     //   struct S {
2028     //     typedef int I;
2029     //     typedef int I;
2030     //   };
2031     //
2032     // since that was the intent of DR56.
2033     if (!isa<TypedefNameDecl>(Old))
2034       return;
2035 
2036     Diag(New->getLocation(), diag::err_redefinition)
2037       << New->getDeclName();
2038     Diag(Old->getLocation(), diag::note_previous_definition);
2039     return New->setInvalidDecl();
2040   }
2041 
2042   // Modules always permit redefinition of typedefs, as does C11.
2043   if (getLangOpts().Modules || getLangOpts().C11)
2044     return;
2045 
2046   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2047   // is normally mapped to an error, but can be controlled with
2048   // -Wtypedef-redefinition.  If either the original or the redefinition is
2049   // in a system header, don't emit this for compatibility with GCC.
2050   if (getDiagnostics().getSuppressSystemWarnings() &&
2051       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2052        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2053     return;
2054 
2055   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2056     << New->getDeclName();
2057   Diag(Old->getLocation(), diag::note_previous_definition);
2058 }
2059 
2060 /// DeclhasAttr - returns true if decl Declaration already has the target
2061 /// attribute.
2062 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2063   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2064   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2065   for (const auto *i : D->attrs())
2066     if (i->getKind() == A->getKind()) {
2067       if (Ann) {
2068         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2069           return true;
2070         continue;
2071       }
2072       // FIXME: Don't hardcode this check
2073       if (OA && isa<OwnershipAttr>(i))
2074         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2075       return true;
2076     }
2077 
2078   return false;
2079 }
2080 
2081 static bool isAttributeTargetADefinition(Decl *D) {
2082   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2083     return VD->isThisDeclarationADefinition();
2084   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2085     return TD->isCompleteDefinition() || TD->isBeingDefined();
2086   return true;
2087 }
2088 
2089 /// Merge alignment attributes from \p Old to \p New, taking into account the
2090 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2091 ///
2092 /// \return \c true if any attributes were added to \p New.
2093 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2094   // Look for alignas attributes on Old, and pick out whichever attribute
2095   // specifies the strictest alignment requirement.
2096   AlignedAttr *OldAlignasAttr = nullptr;
2097   AlignedAttr *OldStrictestAlignAttr = nullptr;
2098   unsigned OldAlign = 0;
2099   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2100     // FIXME: We have no way of representing inherited dependent alignments
2101     // in a case like:
2102     //   template<int A, int B> struct alignas(A) X;
2103     //   template<int A, int B> struct alignas(B) X {};
2104     // For now, we just ignore any alignas attributes which are not on the
2105     // definition in such a case.
2106     if (I->isAlignmentDependent())
2107       return false;
2108 
2109     if (I->isAlignas())
2110       OldAlignasAttr = I;
2111 
2112     unsigned Align = I->getAlignment(S.Context);
2113     if (Align > OldAlign) {
2114       OldAlign = Align;
2115       OldStrictestAlignAttr = I;
2116     }
2117   }
2118 
2119   // Look for alignas attributes on New.
2120   AlignedAttr *NewAlignasAttr = nullptr;
2121   unsigned NewAlign = 0;
2122   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2123     if (I->isAlignmentDependent())
2124       return false;
2125 
2126     if (I->isAlignas())
2127       NewAlignasAttr = I;
2128 
2129     unsigned Align = I->getAlignment(S.Context);
2130     if (Align > NewAlign)
2131       NewAlign = Align;
2132   }
2133 
2134   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2135     // Both declarations have 'alignas' attributes. We require them to match.
2136     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2137     // fall short. (If two declarations both have alignas, they must both match
2138     // every definition, and so must match each other if there is a definition.)
2139 
2140     // If either declaration only contains 'alignas(0)' specifiers, then it
2141     // specifies the natural alignment for the type.
2142     if (OldAlign == 0 || NewAlign == 0) {
2143       QualType Ty;
2144       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2145         Ty = VD->getType();
2146       else
2147         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2148 
2149       if (OldAlign == 0)
2150         OldAlign = S.Context.getTypeAlign(Ty);
2151       if (NewAlign == 0)
2152         NewAlign = S.Context.getTypeAlign(Ty);
2153     }
2154 
2155     if (OldAlign != NewAlign) {
2156       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2157         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2158         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2159       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2160     }
2161   }
2162 
2163   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2164     // C++11 [dcl.align]p6:
2165     //   if any declaration of an entity has an alignment-specifier,
2166     //   every defining declaration of that entity shall specify an
2167     //   equivalent alignment.
2168     // C11 6.7.5/7:
2169     //   If the definition of an object does not have an alignment
2170     //   specifier, any other declaration of that object shall also
2171     //   have no alignment specifier.
2172     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2173       << OldAlignasAttr;
2174     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2175       << OldAlignasAttr;
2176   }
2177 
2178   bool AnyAdded = false;
2179 
2180   // Ensure we have an attribute representing the strictest alignment.
2181   if (OldAlign > NewAlign) {
2182     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2183     Clone->setInherited(true);
2184     New->addAttr(Clone);
2185     AnyAdded = true;
2186   }
2187 
2188   // Ensure we have an alignas attribute if the old declaration had one.
2189   if (OldAlignasAttr && !NewAlignasAttr &&
2190       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2191     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2192     Clone->setInherited(true);
2193     New->addAttr(Clone);
2194     AnyAdded = true;
2195   }
2196 
2197   return AnyAdded;
2198 }
2199 
2200 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2201                                const InheritableAttr *Attr,
2202                                Sema::AvailabilityMergeKind AMK) {
2203   InheritableAttr *NewAttr = nullptr;
2204   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2205   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2206     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2207                                       AA->getIntroduced(), AA->getDeprecated(),
2208                                       AA->getObsoleted(), AA->getUnavailable(),
2209                                       AA->getMessage(), AA->getStrict(),
2210                                       AA->getReplacement(), AMK,
2211                                       AttrSpellingListIndex);
2212   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2213     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2214                                     AttrSpellingListIndex);
2215   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2216     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2217                                         AttrSpellingListIndex);
2218   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2219     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2220                                    AttrSpellingListIndex);
2221   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2222     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2223                                    AttrSpellingListIndex);
2224   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2225     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2226                                 FA->getFormatIdx(), FA->getFirstArg(),
2227                                 AttrSpellingListIndex);
2228   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2229     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2230                                  AttrSpellingListIndex);
2231   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2232     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2233                                        AttrSpellingListIndex,
2234                                        IA->getSemanticSpelling());
2235   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2236     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2237                                       &S.Context.Idents.get(AA->getSpelling()),
2238                                       AttrSpellingListIndex);
2239   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2240     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2241   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2242     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2243   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2244     NewAttr = S.mergeInternalLinkageAttr(
2245         D, InternalLinkageA->getRange(),
2246         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2247         AttrSpellingListIndex);
2248   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2249     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2250                                 &S.Context.Idents.get(CommonA->getSpelling()),
2251                                 AttrSpellingListIndex);
2252   else if (isa<AlignedAttr>(Attr))
2253     // AlignedAttrs are handled separately, because we need to handle all
2254     // such attributes on a declaration at the same time.
2255     NewAttr = nullptr;
2256   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2257            (AMK == Sema::AMK_Override ||
2258             AMK == Sema::AMK_ProtocolImplementation))
2259     NewAttr = nullptr;
2260   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2261     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2262 
2263   if (NewAttr) {
2264     NewAttr->setInherited(true);
2265     D->addAttr(NewAttr);
2266     if (isa<MSInheritanceAttr>(NewAttr))
2267       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2268     return true;
2269   }
2270 
2271   return false;
2272 }
2273 
2274 static const Decl *getDefinition(const Decl *D) {
2275   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2276     return TD->getDefinition();
2277   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2278     const VarDecl *Def = VD->getDefinition();
2279     if (Def)
2280       return Def;
2281     return VD->getActingDefinition();
2282   }
2283   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2284     const FunctionDecl* Def;
2285     if (FD->isDefined(Def))
2286       return Def;
2287   }
2288   return nullptr;
2289 }
2290 
2291 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2292   for (const auto *Attribute : D->attrs())
2293     if (Attribute->getKind() == Kind)
2294       return true;
2295   return false;
2296 }
2297 
2298 /// checkNewAttributesAfterDef - If we already have a definition, check that
2299 /// there are no new attributes in this declaration.
2300 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2301   if (!New->hasAttrs())
2302     return;
2303 
2304   const Decl *Def = getDefinition(Old);
2305   if (!Def || Def == New)
2306     return;
2307 
2308   AttrVec &NewAttributes = New->getAttrs();
2309   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2310     const Attr *NewAttribute = NewAttributes[I];
2311 
2312     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2313       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2314         Sema::SkipBodyInfo SkipBody;
2315         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2316 
2317         // If we're skipping this definition, drop the "alias" attribute.
2318         if (SkipBody.ShouldSkip) {
2319           NewAttributes.erase(NewAttributes.begin() + I);
2320           --E;
2321           continue;
2322         }
2323       } else {
2324         VarDecl *VD = cast<VarDecl>(New);
2325         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2326                                 VarDecl::TentativeDefinition
2327                             ? diag::err_alias_after_tentative
2328                             : diag::err_redefinition;
2329         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2330         S.Diag(Def->getLocation(), diag::note_previous_definition);
2331         VD->setInvalidDecl();
2332       }
2333       ++I;
2334       continue;
2335     }
2336 
2337     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2338       // Tentative definitions are only interesting for the alias check above.
2339       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2340         ++I;
2341         continue;
2342       }
2343     }
2344 
2345     if (hasAttribute(Def, NewAttribute->getKind())) {
2346       ++I;
2347       continue; // regular attr merging will take care of validating this.
2348     }
2349 
2350     if (isa<C11NoReturnAttr>(NewAttribute)) {
2351       // C's _Noreturn is allowed to be added to a function after it is defined.
2352       ++I;
2353       continue;
2354     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2355       if (AA->isAlignas()) {
2356         // C++11 [dcl.align]p6:
2357         //   if any declaration of an entity has an alignment-specifier,
2358         //   every defining declaration of that entity shall specify an
2359         //   equivalent alignment.
2360         // C11 6.7.5/7:
2361         //   If the definition of an object does not have an alignment
2362         //   specifier, any other declaration of that object shall also
2363         //   have no alignment specifier.
2364         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2365           << AA;
2366         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2367           << AA;
2368         NewAttributes.erase(NewAttributes.begin() + I);
2369         --E;
2370         continue;
2371       }
2372     }
2373 
2374     S.Diag(NewAttribute->getLocation(),
2375            diag::warn_attribute_precede_definition);
2376     S.Diag(Def->getLocation(), diag::note_previous_definition);
2377     NewAttributes.erase(NewAttributes.begin() + I);
2378     --E;
2379   }
2380 }
2381 
2382 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2383 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2384                                AvailabilityMergeKind AMK) {
2385   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2386     UsedAttr *NewAttr = OldAttr->clone(Context);
2387     NewAttr->setInherited(true);
2388     New->addAttr(NewAttr);
2389   }
2390 
2391   if (!Old->hasAttrs() && !New->hasAttrs())
2392     return;
2393 
2394   // Attributes declared post-definition are currently ignored.
2395   checkNewAttributesAfterDef(*this, New, Old);
2396 
2397   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2398     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2399       if (OldA->getLabel() != NewA->getLabel()) {
2400         // This redeclaration changes __asm__ label.
2401         Diag(New->getLocation(), diag::err_different_asm_label);
2402         Diag(OldA->getLocation(), diag::note_previous_declaration);
2403       }
2404     } else if (Old->isUsed()) {
2405       // This redeclaration adds an __asm__ label to a declaration that has
2406       // already been ODR-used.
2407       Diag(New->getLocation(), diag::err_late_asm_label_name)
2408         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2409     }
2410   }
2411 
2412   // Re-declaration cannot add abi_tag's.
2413   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2414     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2415       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2416         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2417                       NewTag) == OldAbiTagAttr->tags_end()) {
2418           Diag(NewAbiTagAttr->getLocation(),
2419                diag::err_new_abi_tag_on_redeclaration)
2420               << NewTag;
2421           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2422         }
2423       }
2424     } else {
2425       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2426       Diag(Old->getLocation(), diag::note_previous_declaration);
2427     }
2428   }
2429 
2430   if (!Old->hasAttrs())
2431     return;
2432 
2433   bool foundAny = New->hasAttrs();
2434 
2435   // Ensure that any moving of objects within the allocated map is done before
2436   // we process them.
2437   if (!foundAny) New->setAttrs(AttrVec());
2438 
2439   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2440     // Ignore deprecated/unavailable/availability attributes if requested.
2441     AvailabilityMergeKind LocalAMK = AMK_None;
2442     if (isa<DeprecatedAttr>(I) ||
2443         isa<UnavailableAttr>(I) ||
2444         isa<AvailabilityAttr>(I)) {
2445       switch (AMK) {
2446       case AMK_None:
2447         continue;
2448 
2449       case AMK_Redeclaration:
2450       case AMK_Override:
2451       case AMK_ProtocolImplementation:
2452         LocalAMK = AMK;
2453         break;
2454       }
2455     }
2456 
2457     // Already handled.
2458     if (isa<UsedAttr>(I))
2459       continue;
2460 
2461     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2462       foundAny = true;
2463   }
2464 
2465   if (mergeAlignedAttrs(*this, New, Old))
2466     foundAny = true;
2467 
2468   if (!foundAny) New->dropAttrs();
2469 }
2470 
2471 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2472 /// to the new one.
2473 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2474                                      const ParmVarDecl *oldDecl,
2475                                      Sema &S) {
2476   // C++11 [dcl.attr.depend]p2:
2477   //   The first declaration of a function shall specify the
2478   //   carries_dependency attribute for its declarator-id if any declaration
2479   //   of the function specifies the carries_dependency attribute.
2480   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2481   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2482     S.Diag(CDA->getLocation(),
2483            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2484     // Find the first declaration of the parameter.
2485     // FIXME: Should we build redeclaration chains for function parameters?
2486     const FunctionDecl *FirstFD =
2487       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2488     const ParmVarDecl *FirstVD =
2489       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2490     S.Diag(FirstVD->getLocation(),
2491            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2492   }
2493 
2494   if (!oldDecl->hasAttrs())
2495     return;
2496 
2497   bool foundAny = newDecl->hasAttrs();
2498 
2499   // Ensure that any moving of objects within the allocated map is
2500   // done before we process them.
2501   if (!foundAny) newDecl->setAttrs(AttrVec());
2502 
2503   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2504     if (!DeclHasAttr(newDecl, I)) {
2505       InheritableAttr *newAttr =
2506         cast<InheritableParamAttr>(I->clone(S.Context));
2507       newAttr->setInherited(true);
2508       newDecl->addAttr(newAttr);
2509       foundAny = true;
2510     }
2511   }
2512 
2513   if (!foundAny) newDecl->dropAttrs();
2514 }
2515 
2516 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2517                                 const ParmVarDecl *OldParam,
2518                                 Sema &S) {
2519   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2520     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2521       if (*Oldnullability != *Newnullability) {
2522         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2523           << DiagNullabilityKind(
2524                *Newnullability,
2525                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2526                 != 0))
2527           << DiagNullabilityKind(
2528                *Oldnullability,
2529                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2530                 != 0));
2531         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2532       }
2533     } else {
2534       QualType NewT = NewParam->getType();
2535       NewT = S.Context.getAttributedType(
2536                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2537                          NewT, NewT);
2538       NewParam->setType(NewT);
2539     }
2540   }
2541 }
2542 
2543 namespace {
2544 
2545 /// Used in MergeFunctionDecl to keep track of function parameters in
2546 /// C.
2547 struct GNUCompatibleParamWarning {
2548   ParmVarDecl *OldParm;
2549   ParmVarDecl *NewParm;
2550   QualType PromotedType;
2551 };
2552 
2553 } // end anonymous namespace
2554 
2555 /// getSpecialMember - get the special member enum for a method.
2556 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2557   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2558     if (Ctor->isDefaultConstructor())
2559       return Sema::CXXDefaultConstructor;
2560 
2561     if (Ctor->isCopyConstructor())
2562       return Sema::CXXCopyConstructor;
2563 
2564     if (Ctor->isMoveConstructor())
2565       return Sema::CXXMoveConstructor;
2566   } else if (isa<CXXDestructorDecl>(MD)) {
2567     return Sema::CXXDestructor;
2568   } else if (MD->isCopyAssignmentOperator()) {
2569     return Sema::CXXCopyAssignment;
2570   } else if (MD->isMoveAssignmentOperator()) {
2571     return Sema::CXXMoveAssignment;
2572   }
2573 
2574   return Sema::CXXInvalid;
2575 }
2576 
2577 // Determine whether the previous declaration was a definition, implicit
2578 // declaration, or a declaration.
2579 template <typename T>
2580 static std::pair<diag::kind, SourceLocation>
2581 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2582   diag::kind PrevDiag;
2583   SourceLocation OldLocation = Old->getLocation();
2584   if (Old->isThisDeclarationADefinition())
2585     PrevDiag = diag::note_previous_definition;
2586   else if (Old->isImplicit()) {
2587     PrevDiag = diag::note_previous_implicit_declaration;
2588     if (OldLocation.isInvalid())
2589       OldLocation = New->getLocation();
2590   } else
2591     PrevDiag = diag::note_previous_declaration;
2592   return std::make_pair(PrevDiag, OldLocation);
2593 }
2594 
2595 /// canRedefineFunction - checks if a function can be redefined. Currently,
2596 /// only extern inline functions can be redefined, and even then only in
2597 /// GNU89 mode.
2598 static bool canRedefineFunction(const FunctionDecl *FD,
2599                                 const LangOptions& LangOpts) {
2600   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2601           !LangOpts.CPlusPlus &&
2602           FD->isInlineSpecified() &&
2603           FD->getStorageClass() == SC_Extern);
2604 }
2605 
2606 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2607   const AttributedType *AT = T->getAs<AttributedType>();
2608   while (AT && !AT->isCallingConv())
2609     AT = AT->getModifiedType()->getAs<AttributedType>();
2610   return AT;
2611 }
2612 
2613 template <typename T>
2614 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2615   const DeclContext *DC = Old->getDeclContext();
2616   if (DC->isRecord())
2617     return false;
2618 
2619   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2620   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2621     return true;
2622   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2623     return true;
2624   return false;
2625 }
2626 
2627 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2628 static bool isExternC(VarTemplateDecl *) { return false; }
2629 
2630 /// \brief Check whether a redeclaration of an entity introduced by a
2631 /// using-declaration is valid, given that we know it's not an overload
2632 /// (nor a hidden tag declaration).
2633 template<typename ExpectedDecl>
2634 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2635                                    ExpectedDecl *New) {
2636   // C++11 [basic.scope.declarative]p4:
2637   //   Given a set of declarations in a single declarative region, each of
2638   //   which specifies the same unqualified name,
2639   //   -- they shall all refer to the same entity, or all refer to functions
2640   //      and function templates; or
2641   //   -- exactly one declaration shall declare a class name or enumeration
2642   //      name that is not a typedef name and the other declarations shall all
2643   //      refer to the same variable or enumerator, or all refer to functions
2644   //      and function templates; in this case the class name or enumeration
2645   //      name is hidden (3.3.10).
2646 
2647   // C++11 [namespace.udecl]p14:
2648   //   If a function declaration in namespace scope or block scope has the
2649   //   same name and the same parameter-type-list as a function introduced
2650   //   by a using-declaration, and the declarations do not declare the same
2651   //   function, the program is ill-formed.
2652 
2653   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2654   if (Old &&
2655       !Old->getDeclContext()->getRedeclContext()->Equals(
2656           New->getDeclContext()->getRedeclContext()) &&
2657       !(isExternC(Old) && isExternC(New)))
2658     Old = nullptr;
2659 
2660   if (!Old) {
2661     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2662     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2663     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2664     return true;
2665   }
2666   return false;
2667 }
2668 
2669 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2670                                             const FunctionDecl *B) {
2671   assert(A->getNumParams() == B->getNumParams());
2672 
2673   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2674     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2675     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2676     if (AttrA == AttrB)
2677       return true;
2678     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2679   };
2680 
2681   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2682 }
2683 
2684 /// MergeFunctionDecl - We just parsed a function 'New' from
2685 /// declarator D which has the same name and scope as a previous
2686 /// declaration 'Old'.  Figure out how to resolve this situation,
2687 /// merging decls or emitting diagnostics as appropriate.
2688 ///
2689 /// In C++, New and Old must be declarations that are not
2690 /// overloaded. Use IsOverload to determine whether New and Old are
2691 /// overloaded, and to select the Old declaration that New should be
2692 /// merged with.
2693 ///
2694 /// Returns true if there was an error, false otherwise.
2695 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2696                              Scope *S, bool MergeTypeWithOld) {
2697   // Verify the old decl was also a function.
2698   FunctionDecl *Old = OldD->getAsFunction();
2699   if (!Old) {
2700     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2701       if (New->getFriendObjectKind()) {
2702         Diag(New->getLocation(), diag::err_using_decl_friend);
2703         Diag(Shadow->getTargetDecl()->getLocation(),
2704              diag::note_using_decl_target);
2705         Diag(Shadow->getUsingDecl()->getLocation(),
2706              diag::note_using_decl) << 0;
2707         return true;
2708       }
2709 
2710       // Check whether the two declarations might declare the same function.
2711       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2712         return true;
2713       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2714     } else {
2715       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2716         << New->getDeclName();
2717       Diag(OldD->getLocation(), diag::note_previous_definition);
2718       return true;
2719     }
2720   }
2721 
2722   // If the old declaration is invalid, just give up here.
2723   if (Old->isInvalidDecl())
2724     return true;
2725 
2726   diag::kind PrevDiag;
2727   SourceLocation OldLocation;
2728   std::tie(PrevDiag, OldLocation) =
2729       getNoteDiagForInvalidRedeclaration(Old, New);
2730 
2731   // Don't complain about this if we're in GNU89 mode and the old function
2732   // is an extern inline function.
2733   // Don't complain about specializations. They are not supposed to have
2734   // storage classes.
2735   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2736       New->getStorageClass() == SC_Static &&
2737       Old->hasExternalFormalLinkage() &&
2738       !New->getTemplateSpecializationInfo() &&
2739       !canRedefineFunction(Old, getLangOpts())) {
2740     if (getLangOpts().MicrosoftExt) {
2741       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2742       Diag(OldLocation, PrevDiag);
2743     } else {
2744       Diag(New->getLocation(), diag::err_static_non_static) << New;
2745       Diag(OldLocation, PrevDiag);
2746       return true;
2747     }
2748   }
2749 
2750   if (New->hasAttr<InternalLinkageAttr>() &&
2751       !Old->hasAttr<InternalLinkageAttr>()) {
2752     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2753         << New->getDeclName();
2754     Diag(Old->getLocation(), diag::note_previous_definition);
2755     New->dropAttr<InternalLinkageAttr>();
2756   }
2757 
2758   // If a function is first declared with a calling convention, but is later
2759   // declared or defined without one, all following decls assume the calling
2760   // convention of the first.
2761   //
2762   // It's OK if a function is first declared without a calling convention,
2763   // but is later declared or defined with the default calling convention.
2764   //
2765   // To test if either decl has an explicit calling convention, we look for
2766   // AttributedType sugar nodes on the type as written.  If they are missing or
2767   // were canonicalized away, we assume the calling convention was implicit.
2768   //
2769   // Note also that we DO NOT return at this point, because we still have
2770   // other tests to run.
2771   QualType OldQType = Context.getCanonicalType(Old->getType());
2772   QualType NewQType = Context.getCanonicalType(New->getType());
2773   const FunctionType *OldType = cast<FunctionType>(OldQType);
2774   const FunctionType *NewType = cast<FunctionType>(NewQType);
2775   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2776   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2777   bool RequiresAdjustment = false;
2778 
2779   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2780     FunctionDecl *First = Old->getFirstDecl();
2781     const FunctionType *FT =
2782         First->getType().getCanonicalType()->castAs<FunctionType>();
2783     FunctionType::ExtInfo FI = FT->getExtInfo();
2784     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2785     if (!NewCCExplicit) {
2786       // Inherit the CC from the previous declaration if it was specified
2787       // there but not here.
2788       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2789       RequiresAdjustment = true;
2790     } else {
2791       // Calling conventions aren't compatible, so complain.
2792       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2793       Diag(New->getLocation(), diag::err_cconv_change)
2794         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2795         << !FirstCCExplicit
2796         << (!FirstCCExplicit ? "" :
2797             FunctionType::getNameForCallConv(FI.getCC()));
2798 
2799       // Put the note on the first decl, since it is the one that matters.
2800       Diag(First->getLocation(), diag::note_previous_declaration);
2801       return true;
2802     }
2803   }
2804 
2805   // FIXME: diagnose the other way around?
2806   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2807     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2808     RequiresAdjustment = true;
2809   }
2810 
2811   // Merge regparm attribute.
2812   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2813       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2814     if (NewTypeInfo.getHasRegParm()) {
2815       Diag(New->getLocation(), diag::err_regparm_mismatch)
2816         << NewType->getRegParmType()
2817         << OldType->getRegParmType();
2818       Diag(OldLocation, diag::note_previous_declaration);
2819       return true;
2820     }
2821 
2822     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2823     RequiresAdjustment = true;
2824   }
2825 
2826   // Merge ns_returns_retained attribute.
2827   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2828     if (NewTypeInfo.getProducesResult()) {
2829       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2830       Diag(OldLocation, diag::note_previous_declaration);
2831       return true;
2832     }
2833 
2834     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2835     RequiresAdjustment = true;
2836   }
2837 
2838   if (RequiresAdjustment) {
2839     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2840     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2841     New->setType(QualType(AdjustedType, 0));
2842     NewQType = Context.getCanonicalType(New->getType());
2843     NewType = cast<FunctionType>(NewQType);
2844   }
2845 
2846   // If this redeclaration makes the function inline, we may need to add it to
2847   // UndefinedButUsed.
2848   if (!Old->isInlined() && New->isInlined() &&
2849       !New->hasAttr<GNUInlineAttr>() &&
2850       !getLangOpts().GNUInline &&
2851       Old->isUsed(false) &&
2852       !Old->isDefined() && !New->isThisDeclarationADefinition())
2853     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2854                                            SourceLocation()));
2855 
2856   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2857   // about it.
2858   if (New->hasAttr<GNUInlineAttr>() &&
2859       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2860     UndefinedButUsed.erase(Old->getCanonicalDecl());
2861   }
2862 
2863   // If pass_object_size params don't match up perfectly, this isn't a valid
2864   // redeclaration.
2865   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2866       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2867     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2868         << New->getDeclName();
2869     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2870     return true;
2871   }
2872 
2873   if (getLangOpts().CPlusPlus) {
2874     // (C++98 13.1p2):
2875     //   Certain function declarations cannot be overloaded:
2876     //     -- Function declarations that differ only in the return type
2877     //        cannot be overloaded.
2878 
2879     // Go back to the type source info to compare the declared return types,
2880     // per C++1y [dcl.type.auto]p13:
2881     //   Redeclarations or specializations of a function or function template
2882     //   with a declared return type that uses a placeholder type shall also
2883     //   use that placeholder, not a deduced type.
2884     QualType OldDeclaredReturnType =
2885         (Old->getTypeSourceInfo()
2886              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2887              : OldType)->getReturnType();
2888     QualType NewDeclaredReturnType =
2889         (New->getTypeSourceInfo()
2890              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2891              : NewType)->getReturnType();
2892     QualType ResQT;
2893     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2894         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2895           New->isLocalExternDecl())) {
2896       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2897           OldDeclaredReturnType->isObjCObjectPointerType())
2898         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2899       if (ResQT.isNull()) {
2900         if (New->isCXXClassMember() && New->isOutOfLine())
2901           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2902               << New << New->getReturnTypeSourceRange();
2903         else
2904           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2905               << New->getReturnTypeSourceRange();
2906         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2907                                     << Old->getReturnTypeSourceRange();
2908         return true;
2909       }
2910       else
2911         NewQType = ResQT;
2912     }
2913 
2914     QualType OldReturnType = OldType->getReturnType();
2915     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2916     if (OldReturnType != NewReturnType) {
2917       // If this function has a deduced return type and has already been
2918       // defined, copy the deduced value from the old declaration.
2919       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2920       if (OldAT && OldAT->isDeduced()) {
2921         New->setType(
2922             SubstAutoType(New->getType(),
2923                           OldAT->isDependentType() ? Context.DependentTy
2924                                                    : OldAT->getDeducedType()));
2925         NewQType = Context.getCanonicalType(
2926             SubstAutoType(NewQType,
2927                           OldAT->isDependentType() ? Context.DependentTy
2928                                                    : OldAT->getDeducedType()));
2929       }
2930     }
2931 
2932     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2933     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2934     if (OldMethod && NewMethod) {
2935       // Preserve triviality.
2936       NewMethod->setTrivial(OldMethod->isTrivial());
2937 
2938       // MSVC allows explicit template specialization at class scope:
2939       // 2 CXXMethodDecls referring to the same function will be injected.
2940       // We don't want a redeclaration error.
2941       bool IsClassScopeExplicitSpecialization =
2942                               OldMethod->isFunctionTemplateSpecialization() &&
2943                               NewMethod->isFunctionTemplateSpecialization();
2944       bool isFriend = NewMethod->getFriendObjectKind();
2945 
2946       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2947           !IsClassScopeExplicitSpecialization) {
2948         //    -- Member function declarations with the same name and the
2949         //       same parameter types cannot be overloaded if any of them
2950         //       is a static member function declaration.
2951         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2952           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2953           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2954           return true;
2955         }
2956 
2957         // C++ [class.mem]p1:
2958         //   [...] A member shall not be declared twice in the
2959         //   member-specification, except that a nested class or member
2960         //   class template can be declared and then later defined.
2961         if (ActiveTemplateInstantiations.empty()) {
2962           unsigned NewDiag;
2963           if (isa<CXXConstructorDecl>(OldMethod))
2964             NewDiag = diag::err_constructor_redeclared;
2965           else if (isa<CXXDestructorDecl>(NewMethod))
2966             NewDiag = diag::err_destructor_redeclared;
2967           else if (isa<CXXConversionDecl>(NewMethod))
2968             NewDiag = diag::err_conv_function_redeclared;
2969           else
2970             NewDiag = diag::err_member_redeclared;
2971 
2972           Diag(New->getLocation(), NewDiag);
2973         } else {
2974           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2975             << New << New->getType();
2976         }
2977         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2978         return true;
2979 
2980       // Complain if this is an explicit declaration of a special
2981       // member that was initially declared implicitly.
2982       //
2983       // As an exception, it's okay to befriend such methods in order
2984       // to permit the implicit constructor/destructor/operator calls.
2985       } else if (OldMethod->isImplicit()) {
2986         if (isFriend) {
2987           NewMethod->setImplicit();
2988         } else {
2989           Diag(NewMethod->getLocation(),
2990                diag::err_definition_of_implicitly_declared_member)
2991             << New << getSpecialMember(OldMethod);
2992           return true;
2993         }
2994       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2995         Diag(NewMethod->getLocation(),
2996              diag::err_definition_of_explicitly_defaulted_member)
2997           << getSpecialMember(OldMethod);
2998         return true;
2999       }
3000     }
3001 
3002     // C++11 [dcl.attr.noreturn]p1:
3003     //   The first declaration of a function shall specify the noreturn
3004     //   attribute if any declaration of that function specifies the noreturn
3005     //   attribute.
3006     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3007     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3008       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3009       Diag(Old->getFirstDecl()->getLocation(),
3010            diag::note_noreturn_missing_first_decl);
3011     }
3012 
3013     // C++11 [dcl.attr.depend]p2:
3014     //   The first declaration of a function shall specify the
3015     //   carries_dependency attribute for its declarator-id if any declaration
3016     //   of the function specifies the carries_dependency attribute.
3017     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3018     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3019       Diag(CDA->getLocation(),
3020            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3021       Diag(Old->getFirstDecl()->getLocation(),
3022            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3023     }
3024 
3025     // (C++98 8.3.5p3):
3026     //   All declarations for a function shall agree exactly in both the
3027     //   return type and the parameter-type-list.
3028     // We also want to respect all the extended bits except noreturn.
3029 
3030     // noreturn should now match unless the old type info didn't have it.
3031     QualType OldQTypeForComparison = OldQType;
3032     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3033       assert(OldQType == QualType(OldType, 0));
3034       const FunctionType *OldTypeForComparison
3035         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3036       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3037       assert(OldQTypeForComparison.isCanonical());
3038     }
3039 
3040     if (haveIncompatibleLanguageLinkages(Old, New)) {
3041       // As a special case, retain the language linkage from previous
3042       // declarations of a friend function as an extension.
3043       //
3044       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3045       // and is useful because there's otherwise no way to specify language
3046       // linkage within class scope.
3047       //
3048       // Check cautiously as the friend object kind isn't yet complete.
3049       if (New->getFriendObjectKind() != Decl::FOK_None) {
3050         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3051         Diag(OldLocation, PrevDiag);
3052       } else {
3053         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3054         Diag(OldLocation, PrevDiag);
3055         return true;
3056       }
3057     }
3058 
3059     if (OldQTypeForComparison == NewQType)
3060       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3061 
3062     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3063         New->isLocalExternDecl()) {
3064       // It's OK if we couldn't merge types for a local function declaraton
3065       // if either the old or new type is dependent. We'll merge the types
3066       // when we instantiate the function.
3067       return false;
3068     }
3069 
3070     // Fall through for conflicting redeclarations and redefinitions.
3071   }
3072 
3073   // C: Function types need to be compatible, not identical. This handles
3074   // duplicate function decls like "void f(int); void f(enum X);" properly.
3075   if (!getLangOpts().CPlusPlus &&
3076       Context.typesAreCompatible(OldQType, NewQType)) {
3077     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3078     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3079     const FunctionProtoType *OldProto = nullptr;
3080     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3081         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3082       // The old declaration provided a function prototype, but the
3083       // new declaration does not. Merge in the prototype.
3084       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3085       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3086       NewQType =
3087           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3088                                   OldProto->getExtProtoInfo());
3089       New->setType(NewQType);
3090       New->setHasInheritedPrototype();
3091 
3092       // Synthesize parameters with the same types.
3093       SmallVector<ParmVarDecl*, 16> Params;
3094       for (const auto &ParamType : OldProto->param_types()) {
3095         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3096                                                  SourceLocation(), nullptr,
3097                                                  ParamType, /*TInfo=*/nullptr,
3098                                                  SC_None, nullptr);
3099         Param->setScopeInfo(0, Params.size());
3100         Param->setImplicit();
3101         Params.push_back(Param);
3102       }
3103 
3104       New->setParams(Params);
3105     }
3106 
3107     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3108   }
3109 
3110   // GNU C permits a K&R definition to follow a prototype declaration
3111   // if the declared types of the parameters in the K&R definition
3112   // match the types in the prototype declaration, even when the
3113   // promoted types of the parameters from the K&R definition differ
3114   // from the types in the prototype. GCC then keeps the types from
3115   // the prototype.
3116   //
3117   // If a variadic prototype is followed by a non-variadic K&R definition,
3118   // the K&R definition becomes variadic.  This is sort of an edge case, but
3119   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3120   // C99 6.9.1p8.
3121   if (!getLangOpts().CPlusPlus &&
3122       Old->hasPrototype() && !New->hasPrototype() &&
3123       New->getType()->getAs<FunctionProtoType>() &&
3124       Old->getNumParams() == New->getNumParams()) {
3125     SmallVector<QualType, 16> ArgTypes;
3126     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3127     const FunctionProtoType *OldProto
3128       = Old->getType()->getAs<FunctionProtoType>();
3129     const FunctionProtoType *NewProto
3130       = New->getType()->getAs<FunctionProtoType>();
3131 
3132     // Determine whether this is the GNU C extension.
3133     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3134                                                NewProto->getReturnType());
3135     bool LooseCompatible = !MergedReturn.isNull();
3136     for (unsigned Idx = 0, End = Old->getNumParams();
3137          LooseCompatible && Idx != End; ++Idx) {
3138       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3139       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3140       if (Context.typesAreCompatible(OldParm->getType(),
3141                                      NewProto->getParamType(Idx))) {
3142         ArgTypes.push_back(NewParm->getType());
3143       } else if (Context.typesAreCompatible(OldParm->getType(),
3144                                             NewParm->getType(),
3145                                             /*CompareUnqualified=*/true)) {
3146         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3147                                            NewProto->getParamType(Idx) };
3148         Warnings.push_back(Warn);
3149         ArgTypes.push_back(NewParm->getType());
3150       } else
3151         LooseCompatible = false;
3152     }
3153 
3154     if (LooseCompatible) {
3155       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3156         Diag(Warnings[Warn].NewParm->getLocation(),
3157              diag::ext_param_promoted_not_compatible_with_prototype)
3158           << Warnings[Warn].PromotedType
3159           << Warnings[Warn].OldParm->getType();
3160         if (Warnings[Warn].OldParm->getLocation().isValid())
3161           Diag(Warnings[Warn].OldParm->getLocation(),
3162                diag::note_previous_declaration);
3163       }
3164 
3165       if (MergeTypeWithOld)
3166         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3167                                              OldProto->getExtProtoInfo()));
3168       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3169     }
3170 
3171     // Fall through to diagnose conflicting types.
3172   }
3173 
3174   // A function that has already been declared has been redeclared or
3175   // defined with a different type; show an appropriate diagnostic.
3176 
3177   // If the previous declaration was an implicitly-generated builtin
3178   // declaration, then at the very least we should use a specialized note.
3179   unsigned BuiltinID;
3180   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3181     // If it's actually a library-defined builtin function like 'malloc'
3182     // or 'printf', just warn about the incompatible redeclaration.
3183     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3184       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3185       Diag(OldLocation, diag::note_previous_builtin_declaration)
3186         << Old << Old->getType();
3187 
3188       // If this is a global redeclaration, just forget hereafter
3189       // about the "builtin-ness" of the function.
3190       //
3191       // Doing this for local extern declarations is problematic.  If
3192       // the builtin declaration remains visible, a second invalid
3193       // local declaration will produce a hard error; if it doesn't
3194       // remain visible, a single bogus local redeclaration (which is
3195       // actually only a warning) could break all the downstream code.
3196       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3197         New->getIdentifier()->revertBuiltin();
3198 
3199       return false;
3200     }
3201 
3202     PrevDiag = diag::note_previous_builtin_declaration;
3203   }
3204 
3205   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3206   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3207   return true;
3208 }
3209 
3210 /// \brief Completes the merge of two function declarations that are
3211 /// known to be compatible.
3212 ///
3213 /// This routine handles the merging of attributes and other
3214 /// properties of function declarations from the old declaration to
3215 /// the new declaration, once we know that New is in fact a
3216 /// redeclaration of Old.
3217 ///
3218 /// \returns false
3219 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3220                                         Scope *S, bool MergeTypeWithOld) {
3221   // Merge the attributes
3222   mergeDeclAttributes(New, Old);
3223 
3224   // Merge "pure" flag.
3225   if (Old->isPure())
3226     New->setPure();
3227 
3228   // Merge "used" flag.
3229   if (Old->getMostRecentDecl()->isUsed(false))
3230     New->setIsUsed();
3231 
3232   // Merge attributes from the parameters.  These can mismatch with K&R
3233   // declarations.
3234   if (New->getNumParams() == Old->getNumParams())
3235       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3236         ParmVarDecl *NewParam = New->getParamDecl(i);
3237         ParmVarDecl *OldParam = Old->getParamDecl(i);
3238         mergeParamDeclAttributes(NewParam, OldParam, *this);
3239         mergeParamDeclTypes(NewParam, OldParam, *this);
3240       }
3241 
3242   if (getLangOpts().CPlusPlus)
3243     return MergeCXXFunctionDecl(New, Old, S);
3244 
3245   // Merge the function types so the we get the composite types for the return
3246   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3247   // was visible.
3248   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3249   if (!Merged.isNull() && MergeTypeWithOld)
3250     New->setType(Merged);
3251 
3252   return false;
3253 }
3254 
3255 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3256                                 ObjCMethodDecl *oldMethod) {
3257   // Merge the attributes, including deprecated/unavailable
3258   AvailabilityMergeKind MergeKind =
3259     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3260       ? AMK_ProtocolImplementation
3261       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3262                                                        : AMK_Override;
3263 
3264   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3265 
3266   // Merge attributes from the parameters.
3267   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3268                                        oe = oldMethod->param_end();
3269   for (ObjCMethodDecl::param_iterator
3270          ni = newMethod->param_begin(), ne = newMethod->param_end();
3271        ni != ne && oi != oe; ++ni, ++oi)
3272     mergeParamDeclAttributes(*ni, *oi, *this);
3273 
3274   CheckObjCMethodOverride(newMethod, oldMethod);
3275 }
3276 
3277 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3278   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3279 
3280   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3281          ? diag::err_redefinition_different_type
3282          : diag::err_redeclaration_different_type)
3283     << New->getDeclName() << New->getType() << Old->getType();
3284 
3285   diag::kind PrevDiag;
3286   SourceLocation OldLocation;
3287   std::tie(PrevDiag, OldLocation)
3288     = getNoteDiagForInvalidRedeclaration(Old, New);
3289   S.Diag(OldLocation, PrevDiag);
3290   New->setInvalidDecl();
3291 }
3292 
3293 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3294 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3295 /// emitting diagnostics as appropriate.
3296 ///
3297 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3298 /// to here in AddInitializerToDecl. We can't check them before the initializer
3299 /// is attached.
3300 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3301                              bool MergeTypeWithOld) {
3302   if (New->isInvalidDecl() || Old->isInvalidDecl())
3303     return;
3304 
3305   QualType MergedT;
3306   if (getLangOpts().CPlusPlus) {
3307     if (New->getType()->isUndeducedType()) {
3308       // We don't know what the new type is until the initializer is attached.
3309       return;
3310     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3311       // These could still be something that needs exception specs checked.
3312       return MergeVarDeclExceptionSpecs(New, Old);
3313     }
3314     // C++ [basic.link]p10:
3315     //   [...] the types specified by all declarations referring to a given
3316     //   object or function shall be identical, except that declarations for an
3317     //   array object can specify array types that differ by the presence or
3318     //   absence of a major array bound (8.3.4).
3319     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3320       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3321       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3322 
3323       // We are merging a variable declaration New into Old. If it has an array
3324       // bound, and that bound differs from Old's bound, we should diagnose the
3325       // mismatch.
3326       if (!NewArray->isIncompleteArrayType()) {
3327         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3328              PrevVD = PrevVD->getPreviousDecl()) {
3329           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3330           if (PrevVDTy->isIncompleteArrayType())
3331             continue;
3332 
3333           if (!Context.hasSameType(NewArray, PrevVDTy))
3334             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3335         }
3336       }
3337 
3338       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3339         if (Context.hasSameType(OldArray->getElementType(),
3340                                 NewArray->getElementType()))
3341           MergedT = New->getType();
3342       }
3343       // FIXME: Check visibility. New is hidden but has a complete type. If New
3344       // has no array bound, it should not inherit one from Old, if Old is not
3345       // visible.
3346       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3347         if (Context.hasSameType(OldArray->getElementType(),
3348                                 NewArray->getElementType()))
3349           MergedT = Old->getType();
3350       }
3351     }
3352     else if (New->getType()->isObjCObjectPointerType() &&
3353                Old->getType()->isObjCObjectPointerType()) {
3354       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3355                                               Old->getType());
3356     }
3357   } else {
3358     // C 6.2.7p2:
3359     //   All declarations that refer to the same object or function shall have
3360     //   compatible type.
3361     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3362   }
3363   if (MergedT.isNull()) {
3364     // It's OK if we couldn't merge types if either type is dependent, for a
3365     // block-scope variable. In other cases (static data members of class
3366     // templates, variable templates, ...), we require the types to be
3367     // equivalent.
3368     // FIXME: The C++ standard doesn't say anything about this.
3369     if ((New->getType()->isDependentType() ||
3370          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3371       // If the old type was dependent, we can't merge with it, so the new type
3372       // becomes dependent for now. We'll reproduce the original type when we
3373       // instantiate the TypeSourceInfo for the variable.
3374       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3375         New->setType(Context.DependentTy);
3376       return;
3377     }
3378     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3379   }
3380 
3381   // Don't actually update the type on the new declaration if the old
3382   // declaration was an extern declaration in a different scope.
3383   if (MergeTypeWithOld)
3384     New->setType(MergedT);
3385 }
3386 
3387 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3388                                   LookupResult &Previous) {
3389   // C11 6.2.7p4:
3390   //   For an identifier with internal or external linkage declared
3391   //   in a scope in which a prior declaration of that identifier is
3392   //   visible, if the prior declaration specifies internal or
3393   //   external linkage, the type of the identifier at the later
3394   //   declaration becomes the composite type.
3395   //
3396   // If the variable isn't visible, we do not merge with its type.
3397   if (Previous.isShadowed())
3398     return false;
3399 
3400   if (S.getLangOpts().CPlusPlus) {
3401     // C++11 [dcl.array]p3:
3402     //   If there is a preceding declaration of the entity in the same
3403     //   scope in which the bound was specified, an omitted array bound
3404     //   is taken to be the same as in that earlier declaration.
3405     return NewVD->isPreviousDeclInSameBlockScope() ||
3406            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3407             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3408   } else {
3409     // If the old declaration was function-local, don't merge with its
3410     // type unless we're in the same function.
3411     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3412            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3413   }
3414 }
3415 
3416 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3417 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3418 /// situation, merging decls or emitting diagnostics as appropriate.
3419 ///
3420 /// Tentative definition rules (C99 6.9.2p2) are checked by
3421 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3422 /// definitions here, since the initializer hasn't been attached.
3423 ///
3424 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3425   // If the new decl is already invalid, don't do any other checking.
3426   if (New->isInvalidDecl())
3427     return;
3428 
3429   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3430     return;
3431 
3432   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3433 
3434   // Verify the old decl was also a variable or variable template.
3435   VarDecl *Old = nullptr;
3436   VarTemplateDecl *OldTemplate = nullptr;
3437   if (Previous.isSingleResult()) {
3438     if (NewTemplate) {
3439       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3440       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3441 
3442       if (auto *Shadow =
3443               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3444         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3445           return New->setInvalidDecl();
3446     } else {
3447       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3448 
3449       if (auto *Shadow =
3450               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3451         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3452           return New->setInvalidDecl();
3453     }
3454   }
3455   if (!Old) {
3456     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3457       << New->getDeclName();
3458     Diag(Previous.getRepresentativeDecl()->getLocation(),
3459          diag::note_previous_definition);
3460     return New->setInvalidDecl();
3461   }
3462 
3463   // Ensure the template parameters are compatible.
3464   if (NewTemplate &&
3465       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3466                                       OldTemplate->getTemplateParameters(),
3467                                       /*Complain=*/true, TPL_TemplateMatch))
3468     return New->setInvalidDecl();
3469 
3470   // C++ [class.mem]p1:
3471   //   A member shall not be declared twice in the member-specification [...]
3472   //
3473   // Here, we need only consider static data members.
3474   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3475     Diag(New->getLocation(), diag::err_duplicate_member)
3476       << New->getIdentifier();
3477     Diag(Old->getLocation(), diag::note_previous_declaration);
3478     New->setInvalidDecl();
3479   }
3480 
3481   mergeDeclAttributes(New, Old);
3482   // Warn if an already-declared variable is made a weak_import in a subsequent
3483   // declaration
3484   if (New->hasAttr<WeakImportAttr>() &&
3485       Old->getStorageClass() == SC_None &&
3486       !Old->hasAttr<WeakImportAttr>()) {
3487     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3488     Diag(Old->getLocation(), diag::note_previous_definition);
3489     // Remove weak_import attribute on new declaration.
3490     New->dropAttr<WeakImportAttr>();
3491   }
3492 
3493   if (New->hasAttr<InternalLinkageAttr>() &&
3494       !Old->hasAttr<InternalLinkageAttr>()) {
3495     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3496         << New->getDeclName();
3497     Diag(Old->getLocation(), diag::note_previous_definition);
3498     New->dropAttr<InternalLinkageAttr>();
3499   }
3500 
3501   // Merge the types.
3502   VarDecl *MostRecent = Old->getMostRecentDecl();
3503   if (MostRecent != Old) {
3504     MergeVarDeclTypes(New, MostRecent,
3505                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3506     if (New->isInvalidDecl())
3507       return;
3508   }
3509 
3510   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3511   if (New->isInvalidDecl())
3512     return;
3513 
3514   diag::kind PrevDiag;
3515   SourceLocation OldLocation;
3516   std::tie(PrevDiag, OldLocation) =
3517       getNoteDiagForInvalidRedeclaration(Old, New);
3518 
3519   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3520   if (New->getStorageClass() == SC_Static &&
3521       !New->isStaticDataMember() &&
3522       Old->hasExternalFormalLinkage()) {
3523     if (getLangOpts().MicrosoftExt) {
3524       Diag(New->getLocation(), diag::ext_static_non_static)
3525           << New->getDeclName();
3526       Diag(OldLocation, PrevDiag);
3527     } else {
3528       Diag(New->getLocation(), diag::err_static_non_static)
3529           << New->getDeclName();
3530       Diag(OldLocation, PrevDiag);
3531       return New->setInvalidDecl();
3532     }
3533   }
3534   // C99 6.2.2p4:
3535   //   For an identifier declared with the storage-class specifier
3536   //   extern in a scope in which a prior declaration of that
3537   //   identifier is visible,23) if the prior declaration specifies
3538   //   internal or external linkage, the linkage of the identifier at
3539   //   the later declaration is the same as the linkage specified at
3540   //   the prior declaration. If no prior declaration is visible, or
3541   //   if the prior declaration specifies no linkage, then the
3542   //   identifier has external linkage.
3543   if (New->hasExternalStorage() && Old->hasLinkage())
3544     /* Okay */;
3545   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3546            !New->isStaticDataMember() &&
3547            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3548     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3549     Diag(OldLocation, PrevDiag);
3550     return New->setInvalidDecl();
3551   }
3552 
3553   // Check if extern is followed by non-extern and vice-versa.
3554   if (New->hasExternalStorage() &&
3555       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3556     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3557     Diag(OldLocation, PrevDiag);
3558     return New->setInvalidDecl();
3559   }
3560   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3561       !New->hasExternalStorage()) {
3562     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3563     Diag(OldLocation, PrevDiag);
3564     return New->setInvalidDecl();
3565   }
3566 
3567   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3568 
3569   // FIXME: The test for external storage here seems wrong? We still
3570   // need to check for mismatches.
3571   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3572       // Don't complain about out-of-line definitions of static members.
3573       !(Old->getLexicalDeclContext()->isRecord() &&
3574         !New->getLexicalDeclContext()->isRecord())) {
3575     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3576     Diag(OldLocation, PrevDiag);
3577     return New->setInvalidDecl();
3578   }
3579 
3580   if (New->getTLSKind() != Old->getTLSKind()) {
3581     if (!Old->getTLSKind()) {
3582       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3583       Diag(OldLocation, PrevDiag);
3584     } else if (!New->getTLSKind()) {
3585       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3586       Diag(OldLocation, PrevDiag);
3587     } else {
3588       // Do not allow redeclaration to change the variable between requiring
3589       // static and dynamic initialization.
3590       // FIXME: GCC allows this, but uses the TLS keyword on the first
3591       // declaration to determine the kind. Do we need to be compatible here?
3592       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3593         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3594       Diag(OldLocation, PrevDiag);
3595     }
3596   }
3597 
3598   // C++ doesn't have tentative definitions, so go right ahead and check here.
3599   VarDecl *Def;
3600   if (getLangOpts().CPlusPlus &&
3601       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3602       (Def = Old->getDefinition())) {
3603     NamedDecl *Hidden = nullptr;
3604     if (!hasVisibleDefinition(Def, &Hidden) &&
3605         (New->getFormalLinkage() == InternalLinkage ||
3606          New->getDescribedVarTemplate() ||
3607          New->getNumTemplateParameterLists() ||
3608          New->getDeclContext()->isDependentContext())) {
3609       // The previous definition is hidden, and multiple definitions are
3610       // permitted (in separate TUs). Form another definition of it.
3611     } else {
3612       Diag(New->getLocation(), diag::err_redefinition) << New;
3613       Diag(Def->getLocation(), diag::note_previous_definition);
3614       New->setInvalidDecl();
3615       return;
3616     }
3617   }
3618 
3619   if (haveIncompatibleLanguageLinkages(Old, New)) {
3620     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3621     Diag(OldLocation, PrevDiag);
3622     New->setInvalidDecl();
3623     return;
3624   }
3625 
3626   // Merge "used" flag.
3627   if (Old->getMostRecentDecl()->isUsed(false))
3628     New->setIsUsed();
3629 
3630   // Keep a chain of previous declarations.
3631   New->setPreviousDecl(Old);
3632   if (NewTemplate)
3633     NewTemplate->setPreviousDecl(OldTemplate);
3634 
3635   // Inherit access appropriately.
3636   New->setAccess(Old->getAccess());
3637   if (NewTemplate)
3638     NewTemplate->setAccess(New->getAccess());
3639 }
3640 
3641 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3642 /// no declarator (e.g. "struct foo;") is parsed.
3643 Decl *
3644 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3645                                  RecordDecl *&AnonRecord) {
3646   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3647                                     AnonRecord);
3648 }
3649 
3650 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3651 // disambiguate entities defined in different scopes.
3652 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3653 // compatibility.
3654 // We will pick our mangling number depending on which version of MSVC is being
3655 // targeted.
3656 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3657   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3658              ? S->getMSCurManglingNumber()
3659              : S->getMSLastManglingNumber();
3660 }
3661 
3662 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3663   if (!Context.getLangOpts().CPlusPlus)
3664     return;
3665 
3666   if (isa<CXXRecordDecl>(Tag->getParent())) {
3667     // If this tag is the direct child of a class, number it if
3668     // it is anonymous.
3669     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3670       return;
3671     MangleNumberingContext &MCtx =
3672         Context.getManglingNumberContext(Tag->getParent());
3673     Context.setManglingNumber(
3674         Tag, MCtx.getManglingNumber(
3675                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3676     return;
3677   }
3678 
3679   // If this tag isn't a direct child of a class, number it if it is local.
3680   Decl *ManglingContextDecl;
3681   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3682           Tag->getDeclContext(), ManglingContextDecl)) {
3683     Context.setManglingNumber(
3684         Tag, MCtx->getManglingNumber(
3685                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3686   }
3687 }
3688 
3689 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3690                                         TypedefNameDecl *NewTD) {
3691   if (TagFromDeclSpec->isInvalidDecl())
3692     return;
3693 
3694   // Do nothing if the tag already has a name for linkage purposes.
3695   if (TagFromDeclSpec->hasNameForLinkage())
3696     return;
3697 
3698   // A well-formed anonymous tag must always be a TUK_Definition.
3699   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3700 
3701   // The type must match the tag exactly;  no qualifiers allowed.
3702   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3703                            Context.getTagDeclType(TagFromDeclSpec))) {
3704     if (getLangOpts().CPlusPlus)
3705       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3706     return;
3707   }
3708 
3709   // If we've already computed linkage for the anonymous tag, then
3710   // adding a typedef name for the anonymous decl can change that
3711   // linkage, which might be a serious problem.  Diagnose this as
3712   // unsupported and ignore the typedef name.  TODO: we should
3713   // pursue this as a language defect and establish a formal rule
3714   // for how to handle it.
3715   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3716     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3717 
3718     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3719     tagLoc = getLocForEndOfToken(tagLoc);
3720 
3721     llvm::SmallString<40> textToInsert;
3722     textToInsert += ' ';
3723     textToInsert += NewTD->getIdentifier()->getName();
3724     Diag(tagLoc, diag::note_typedef_changes_linkage)
3725         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3726     return;
3727   }
3728 
3729   // Otherwise, set this is the anon-decl typedef for the tag.
3730   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3731 }
3732 
3733 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3734   switch (T) {
3735   case DeclSpec::TST_class:
3736     return 0;
3737   case DeclSpec::TST_struct:
3738     return 1;
3739   case DeclSpec::TST_interface:
3740     return 2;
3741   case DeclSpec::TST_union:
3742     return 3;
3743   case DeclSpec::TST_enum:
3744     return 4;
3745   default:
3746     llvm_unreachable("unexpected type specifier");
3747   }
3748 }
3749 
3750 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3751 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3752 /// parameters to cope with template friend declarations.
3753 Decl *
3754 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3755                                  MultiTemplateParamsArg TemplateParams,
3756                                  bool IsExplicitInstantiation,
3757                                  RecordDecl *&AnonRecord) {
3758   Decl *TagD = nullptr;
3759   TagDecl *Tag = nullptr;
3760   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3761       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3762       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3763       DS.getTypeSpecType() == DeclSpec::TST_union ||
3764       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3765     TagD = DS.getRepAsDecl();
3766 
3767     if (!TagD) // We probably had an error
3768       return nullptr;
3769 
3770     // Note that the above type specs guarantee that the
3771     // type rep is a Decl, whereas in many of the others
3772     // it's a Type.
3773     if (isa<TagDecl>(TagD))
3774       Tag = cast<TagDecl>(TagD);
3775     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3776       Tag = CTD->getTemplatedDecl();
3777   }
3778 
3779   if (Tag) {
3780     handleTagNumbering(Tag, S);
3781     Tag->setFreeStanding();
3782     if (Tag->isInvalidDecl())
3783       return Tag;
3784   }
3785 
3786   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3787     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3788     // or incomplete types shall not be restrict-qualified."
3789     if (TypeQuals & DeclSpec::TQ_restrict)
3790       Diag(DS.getRestrictSpecLoc(),
3791            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3792            << DS.getSourceRange();
3793   }
3794 
3795   if (DS.isConstexprSpecified()) {
3796     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3797     // and definitions of functions and variables.
3798     if (Tag)
3799       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3800           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3801     else
3802       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3803     // Don't emit warnings after this error.
3804     return TagD;
3805   }
3806 
3807   if (DS.isConceptSpecified()) {
3808     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3809     // either a function concept and its definition or a variable concept and
3810     // its initializer.
3811     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3812     return TagD;
3813   }
3814 
3815   DiagnoseFunctionSpecifiers(DS);
3816 
3817   if (DS.isFriendSpecified()) {
3818     // If we're dealing with a decl but not a TagDecl, assume that
3819     // whatever routines created it handled the friendship aspect.
3820     if (TagD && !Tag)
3821       return nullptr;
3822     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3823   }
3824 
3825   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3826   bool IsExplicitSpecialization =
3827     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3828   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3829       !IsExplicitInstantiation && !IsExplicitSpecialization &&
3830       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3831     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3832     // nested-name-specifier unless it is an explicit instantiation
3833     // or an explicit specialization.
3834     //
3835     // FIXME: We allow class template partial specializations here too, per the
3836     // obvious intent of DR1819.
3837     //
3838     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3839     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3840         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3841     return nullptr;
3842   }
3843 
3844   // Track whether this decl-specifier declares anything.
3845   bool DeclaresAnything = true;
3846 
3847   // Handle anonymous struct definitions.
3848   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3849     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3850         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3851       if (getLangOpts().CPlusPlus ||
3852           Record->getDeclContext()->isRecord()) {
3853         // If CurContext is a DeclContext that can contain statements,
3854         // RecursiveASTVisitor won't visit the decls that
3855         // BuildAnonymousStructOrUnion() will put into CurContext.
3856         // Also store them here so that they can be part of the
3857         // DeclStmt that gets created in this case.
3858         // FIXME: Also return the IndirectFieldDecls created by
3859         // BuildAnonymousStructOr union, for the same reason?
3860         if (CurContext->isFunctionOrMethod())
3861           AnonRecord = Record;
3862         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3863                                            Context.getPrintingPolicy());
3864       }
3865 
3866       DeclaresAnything = false;
3867     }
3868   }
3869 
3870   // C11 6.7.2.1p2:
3871   //   A struct-declaration that does not declare an anonymous structure or
3872   //   anonymous union shall contain a struct-declarator-list.
3873   //
3874   // This rule also existed in C89 and C99; the grammar for struct-declaration
3875   // did not permit a struct-declaration without a struct-declarator-list.
3876   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3877       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3878     // Check for Microsoft C extension: anonymous struct/union member.
3879     // Handle 2 kinds of anonymous struct/union:
3880     //   struct STRUCT;
3881     //   union UNION;
3882     // and
3883     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3884     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3885     if ((Tag && Tag->getDeclName()) ||
3886         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3887       RecordDecl *Record = nullptr;
3888       if (Tag)
3889         Record = dyn_cast<RecordDecl>(Tag);
3890       else if (const RecordType *RT =
3891                    DS.getRepAsType().get()->getAsStructureType())
3892         Record = RT->getDecl();
3893       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3894         Record = UT->getDecl();
3895 
3896       if (Record && getLangOpts().MicrosoftExt) {
3897         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3898           << Record->isUnion() << DS.getSourceRange();
3899         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3900       }
3901 
3902       DeclaresAnything = false;
3903     }
3904   }
3905 
3906   // Skip all the checks below if we have a type error.
3907   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3908       (TagD && TagD->isInvalidDecl()))
3909     return TagD;
3910 
3911   if (getLangOpts().CPlusPlus &&
3912       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3913     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3914       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3915           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3916         DeclaresAnything = false;
3917 
3918   if (!DS.isMissingDeclaratorOk()) {
3919     // Customize diagnostic for a typedef missing a name.
3920     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3921       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3922         << DS.getSourceRange();
3923     else
3924       DeclaresAnything = false;
3925   }
3926 
3927   if (DS.isModulePrivateSpecified() &&
3928       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3929     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3930       << Tag->getTagKind()
3931       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3932 
3933   ActOnDocumentableDecl(TagD);
3934 
3935   // C 6.7/2:
3936   //   A declaration [...] shall declare at least a declarator [...], a tag,
3937   //   or the members of an enumeration.
3938   // C++ [dcl.dcl]p3:
3939   //   [If there are no declarators], and except for the declaration of an
3940   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3941   //   names into the program, or shall redeclare a name introduced by a
3942   //   previous declaration.
3943   if (!DeclaresAnything) {
3944     // In C, we allow this as a (popular) extension / bug. Don't bother
3945     // producing further diagnostics for redundant qualifiers after this.
3946     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3947     return TagD;
3948   }
3949 
3950   // C++ [dcl.stc]p1:
3951   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3952   //   init-declarator-list of the declaration shall not be empty.
3953   // C++ [dcl.fct.spec]p1:
3954   //   If a cv-qualifier appears in a decl-specifier-seq, the
3955   //   init-declarator-list of the declaration shall not be empty.
3956   //
3957   // Spurious qualifiers here appear to be valid in C.
3958   unsigned DiagID = diag::warn_standalone_specifier;
3959   if (getLangOpts().CPlusPlus)
3960     DiagID = diag::ext_standalone_specifier;
3961 
3962   // Note that a linkage-specification sets a storage class, but
3963   // 'extern "C" struct foo;' is actually valid and not theoretically
3964   // useless.
3965   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3966     if (SCS == DeclSpec::SCS_mutable)
3967       // Since mutable is not a viable storage class specifier in C, there is
3968       // no reason to treat it as an extension. Instead, diagnose as an error.
3969       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3970     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3971       Diag(DS.getStorageClassSpecLoc(), DiagID)
3972         << DeclSpec::getSpecifierName(SCS);
3973   }
3974 
3975   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3976     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3977       << DeclSpec::getSpecifierName(TSCS);
3978   if (DS.getTypeQualifiers()) {
3979     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3980       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3981     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3982       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3983     // Restrict is covered above.
3984     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3985       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3986   }
3987 
3988   // Warn about ignored type attributes, for example:
3989   // __attribute__((aligned)) struct A;
3990   // Attributes should be placed after tag to apply to type declaration.
3991   if (!DS.getAttributes().empty()) {
3992     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3993     if (TypeSpecType == DeclSpec::TST_class ||
3994         TypeSpecType == DeclSpec::TST_struct ||
3995         TypeSpecType == DeclSpec::TST_interface ||
3996         TypeSpecType == DeclSpec::TST_union ||
3997         TypeSpecType == DeclSpec::TST_enum) {
3998       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
3999            attrs = attrs->getNext())
4000         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4001             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4002     }
4003   }
4004 
4005   return TagD;
4006 }
4007 
4008 /// We are trying to inject an anonymous member into the given scope;
4009 /// check if there's an existing declaration that can't be overloaded.
4010 ///
4011 /// \return true if this is a forbidden redeclaration
4012 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4013                                          Scope *S,
4014                                          DeclContext *Owner,
4015                                          DeclarationName Name,
4016                                          SourceLocation NameLoc,
4017                                          bool IsUnion) {
4018   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4019                  Sema::ForRedeclaration);
4020   if (!SemaRef.LookupName(R, S)) return false;
4021 
4022   // Pick a representative declaration.
4023   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4024   assert(PrevDecl && "Expected a non-null Decl");
4025 
4026   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4027     return false;
4028 
4029   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4030     << IsUnion << Name;
4031   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4032 
4033   return true;
4034 }
4035 
4036 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4037 /// anonymous struct or union AnonRecord into the owning context Owner
4038 /// and scope S. This routine will be invoked just after we realize
4039 /// that an unnamed union or struct is actually an anonymous union or
4040 /// struct, e.g.,
4041 ///
4042 /// @code
4043 /// union {
4044 ///   int i;
4045 ///   float f;
4046 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4047 ///    // f into the surrounding scope.x
4048 /// @endcode
4049 ///
4050 /// This routine is recursive, injecting the names of nested anonymous
4051 /// structs/unions into the owning context and scope as well.
4052 static bool
4053 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4054                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4055                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4056   bool Invalid = false;
4057 
4058   // Look every FieldDecl and IndirectFieldDecl with a name.
4059   for (auto *D : AnonRecord->decls()) {
4060     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4061         cast<NamedDecl>(D)->getDeclName()) {
4062       ValueDecl *VD = cast<ValueDecl>(D);
4063       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4064                                        VD->getLocation(),
4065                                        AnonRecord->isUnion())) {
4066         // C++ [class.union]p2:
4067         //   The names of the members of an anonymous union shall be
4068         //   distinct from the names of any other entity in the
4069         //   scope in which the anonymous union is declared.
4070         Invalid = true;
4071       } else {
4072         // C++ [class.union]p2:
4073         //   For the purpose of name lookup, after the anonymous union
4074         //   definition, the members of the anonymous union are
4075         //   considered to have been defined in the scope in which the
4076         //   anonymous union is declared.
4077         unsigned OldChainingSize = Chaining.size();
4078         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4079           Chaining.append(IF->chain_begin(), IF->chain_end());
4080         else
4081           Chaining.push_back(VD);
4082 
4083         assert(Chaining.size() >= 2);
4084         NamedDecl **NamedChain =
4085           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4086         for (unsigned i = 0; i < Chaining.size(); i++)
4087           NamedChain[i] = Chaining[i];
4088 
4089         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4090             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4091             VD->getType(), NamedChain, Chaining.size());
4092 
4093         for (const auto *Attr : VD->attrs())
4094           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4095 
4096         IndirectField->setAccess(AS);
4097         IndirectField->setImplicit();
4098         SemaRef.PushOnScopeChains(IndirectField, S);
4099 
4100         // That includes picking up the appropriate access specifier.
4101         if (AS != AS_none) IndirectField->setAccess(AS);
4102 
4103         Chaining.resize(OldChainingSize);
4104       }
4105     }
4106   }
4107 
4108   return Invalid;
4109 }
4110 
4111 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4112 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4113 /// illegal input values are mapped to SC_None.
4114 static StorageClass
4115 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4116   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4117   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4118          "Parser allowed 'typedef' as storage class VarDecl.");
4119   switch (StorageClassSpec) {
4120   case DeclSpec::SCS_unspecified:    return SC_None;
4121   case DeclSpec::SCS_extern:
4122     if (DS.isExternInLinkageSpec())
4123       return SC_None;
4124     return SC_Extern;
4125   case DeclSpec::SCS_static:         return SC_Static;
4126   case DeclSpec::SCS_auto:           return SC_Auto;
4127   case DeclSpec::SCS_register:       return SC_Register;
4128   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4129     // Illegal SCSs map to None: error reporting is up to the caller.
4130   case DeclSpec::SCS_mutable:        // Fall through.
4131   case DeclSpec::SCS_typedef:        return SC_None;
4132   }
4133   llvm_unreachable("unknown storage class specifier");
4134 }
4135 
4136 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4137   assert(Record->hasInClassInitializer());
4138 
4139   for (const auto *I : Record->decls()) {
4140     const auto *FD = dyn_cast<FieldDecl>(I);
4141     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4142       FD = IFD->getAnonField();
4143     if (FD && FD->hasInClassInitializer())
4144       return FD->getLocation();
4145   }
4146 
4147   llvm_unreachable("couldn't find in-class initializer");
4148 }
4149 
4150 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4151                                       SourceLocation DefaultInitLoc) {
4152   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4153     return;
4154 
4155   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4156   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4157 }
4158 
4159 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4160                                       CXXRecordDecl *AnonUnion) {
4161   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4162     return;
4163 
4164   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4165 }
4166 
4167 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4168 /// anonymous structure or union. Anonymous unions are a C++ feature
4169 /// (C++ [class.union]) and a C11 feature; anonymous structures
4170 /// are a C11 feature and GNU C++ extension.
4171 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4172                                         AccessSpecifier AS,
4173                                         RecordDecl *Record,
4174                                         const PrintingPolicy &Policy) {
4175   DeclContext *Owner = Record->getDeclContext();
4176 
4177   // Diagnose whether this anonymous struct/union is an extension.
4178   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4179     Diag(Record->getLocation(), diag::ext_anonymous_union);
4180   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4181     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4182   else if (!Record->isUnion() && !getLangOpts().C11)
4183     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4184 
4185   // C and C++ require different kinds of checks for anonymous
4186   // structs/unions.
4187   bool Invalid = false;
4188   if (getLangOpts().CPlusPlus) {
4189     const char *PrevSpec = nullptr;
4190     unsigned DiagID;
4191     if (Record->isUnion()) {
4192       // C++ [class.union]p6:
4193       //   Anonymous unions declared in a named namespace or in the
4194       //   global namespace shall be declared static.
4195       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4196           (isa<TranslationUnitDecl>(Owner) ||
4197            (isa<NamespaceDecl>(Owner) &&
4198             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4199         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4200           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4201 
4202         // Recover by adding 'static'.
4203         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4204                                PrevSpec, DiagID, Policy);
4205       }
4206       // C++ [class.union]p6:
4207       //   A storage class is not allowed in a declaration of an
4208       //   anonymous union in a class scope.
4209       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4210                isa<RecordDecl>(Owner)) {
4211         Diag(DS.getStorageClassSpecLoc(),
4212              diag::err_anonymous_union_with_storage_spec)
4213           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4214 
4215         // Recover by removing the storage specifier.
4216         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4217                                SourceLocation(),
4218                                PrevSpec, DiagID, Context.getPrintingPolicy());
4219       }
4220     }
4221 
4222     // Ignore const/volatile/restrict qualifiers.
4223     if (DS.getTypeQualifiers()) {
4224       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4225         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4226           << Record->isUnion() << "const"
4227           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4228       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4229         Diag(DS.getVolatileSpecLoc(),
4230              diag::ext_anonymous_struct_union_qualified)
4231           << Record->isUnion() << "volatile"
4232           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4233       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4234         Diag(DS.getRestrictSpecLoc(),
4235              diag::ext_anonymous_struct_union_qualified)
4236           << Record->isUnion() << "restrict"
4237           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4238       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4239         Diag(DS.getAtomicSpecLoc(),
4240              diag::ext_anonymous_struct_union_qualified)
4241           << Record->isUnion() << "_Atomic"
4242           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4243 
4244       DS.ClearTypeQualifiers();
4245     }
4246 
4247     // C++ [class.union]p2:
4248     //   The member-specification of an anonymous union shall only
4249     //   define non-static data members. [Note: nested types and
4250     //   functions cannot be declared within an anonymous union. ]
4251     for (auto *Mem : Record->decls()) {
4252       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4253         // C++ [class.union]p3:
4254         //   An anonymous union shall not have private or protected
4255         //   members (clause 11).
4256         assert(FD->getAccess() != AS_none);
4257         if (FD->getAccess() != AS_public) {
4258           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4259             << Record->isUnion() << (FD->getAccess() == AS_protected);
4260           Invalid = true;
4261         }
4262 
4263         // C++ [class.union]p1
4264         //   An object of a class with a non-trivial constructor, a non-trivial
4265         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4266         //   assignment operator cannot be a member of a union, nor can an
4267         //   array of such objects.
4268         if (CheckNontrivialField(FD))
4269           Invalid = true;
4270       } else if (Mem->isImplicit()) {
4271         // Any implicit members are fine.
4272       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4273         // This is a type that showed up in an
4274         // elaborated-type-specifier inside the anonymous struct or
4275         // union, but which actually declares a type outside of the
4276         // anonymous struct or union. It's okay.
4277       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4278         if (!MemRecord->isAnonymousStructOrUnion() &&
4279             MemRecord->getDeclName()) {
4280           // Visual C++ allows type definition in anonymous struct or union.
4281           if (getLangOpts().MicrosoftExt)
4282             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4283               << Record->isUnion();
4284           else {
4285             // This is a nested type declaration.
4286             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4287               << Record->isUnion();
4288             Invalid = true;
4289           }
4290         } else {
4291           // This is an anonymous type definition within another anonymous type.
4292           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4293           // not part of standard C++.
4294           Diag(MemRecord->getLocation(),
4295                diag::ext_anonymous_record_with_anonymous_type)
4296             << Record->isUnion();
4297         }
4298       } else if (isa<AccessSpecDecl>(Mem)) {
4299         // Any access specifier is fine.
4300       } else if (isa<StaticAssertDecl>(Mem)) {
4301         // In C++1z, static_assert declarations are also fine.
4302       } else {
4303         // We have something that isn't a non-static data
4304         // member. Complain about it.
4305         unsigned DK = diag::err_anonymous_record_bad_member;
4306         if (isa<TypeDecl>(Mem))
4307           DK = diag::err_anonymous_record_with_type;
4308         else if (isa<FunctionDecl>(Mem))
4309           DK = diag::err_anonymous_record_with_function;
4310         else if (isa<VarDecl>(Mem))
4311           DK = diag::err_anonymous_record_with_static;
4312 
4313         // Visual C++ allows type definition in anonymous struct or union.
4314         if (getLangOpts().MicrosoftExt &&
4315             DK == diag::err_anonymous_record_with_type)
4316           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4317             << Record->isUnion();
4318         else {
4319           Diag(Mem->getLocation(), DK) << Record->isUnion();
4320           Invalid = true;
4321         }
4322       }
4323     }
4324 
4325     // C++11 [class.union]p8 (DR1460):
4326     //   At most one variant member of a union may have a
4327     //   brace-or-equal-initializer.
4328     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4329         Owner->isRecord())
4330       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4331                                 cast<CXXRecordDecl>(Record));
4332   }
4333 
4334   if (!Record->isUnion() && !Owner->isRecord()) {
4335     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4336       << getLangOpts().CPlusPlus;
4337     Invalid = true;
4338   }
4339 
4340   // Mock up a declarator.
4341   Declarator Dc(DS, Declarator::MemberContext);
4342   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4343   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4344 
4345   // Create a declaration for this anonymous struct/union.
4346   NamedDecl *Anon = nullptr;
4347   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4348     Anon = FieldDecl::Create(Context, OwningClass,
4349                              DS.getLocStart(),
4350                              Record->getLocation(),
4351                              /*IdentifierInfo=*/nullptr,
4352                              Context.getTypeDeclType(Record),
4353                              TInfo,
4354                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4355                              /*InitStyle=*/ICIS_NoInit);
4356     Anon->setAccess(AS);
4357     if (getLangOpts().CPlusPlus)
4358       FieldCollector->Add(cast<FieldDecl>(Anon));
4359   } else {
4360     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4361     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4362     if (SCSpec == DeclSpec::SCS_mutable) {
4363       // mutable can only appear on non-static class members, so it's always
4364       // an error here
4365       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4366       Invalid = true;
4367       SC = SC_None;
4368     }
4369 
4370     Anon = VarDecl::Create(Context, Owner,
4371                            DS.getLocStart(),
4372                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4373                            Context.getTypeDeclType(Record),
4374                            TInfo, SC);
4375 
4376     // Default-initialize the implicit variable. This initialization will be
4377     // trivial in almost all cases, except if a union member has an in-class
4378     // initializer:
4379     //   union { int n = 0; };
4380     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4381   }
4382   Anon->setImplicit();
4383 
4384   // Mark this as an anonymous struct/union type.
4385   Record->setAnonymousStructOrUnion(true);
4386 
4387   // Add the anonymous struct/union object to the current
4388   // context. We'll be referencing this object when we refer to one of
4389   // its members.
4390   Owner->addDecl(Anon);
4391 
4392   // Inject the members of the anonymous struct/union into the owning
4393   // context and into the identifier resolver chain for name lookup
4394   // purposes.
4395   SmallVector<NamedDecl*, 2> Chain;
4396   Chain.push_back(Anon);
4397 
4398   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4399     Invalid = true;
4400 
4401   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4402     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4403       Decl *ManglingContextDecl;
4404       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4405               NewVD->getDeclContext(), ManglingContextDecl)) {
4406         Context.setManglingNumber(
4407             NewVD, MCtx->getManglingNumber(
4408                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4409         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4410       }
4411     }
4412   }
4413 
4414   if (Invalid)
4415     Anon->setInvalidDecl();
4416 
4417   return Anon;
4418 }
4419 
4420 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4421 /// Microsoft C anonymous structure.
4422 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4423 /// Example:
4424 ///
4425 /// struct A { int a; };
4426 /// struct B { struct A; int b; };
4427 ///
4428 /// void foo() {
4429 ///   B var;
4430 ///   var.a = 3;
4431 /// }
4432 ///
4433 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4434                                            RecordDecl *Record) {
4435   assert(Record && "expected a record!");
4436 
4437   // Mock up a declarator.
4438   Declarator Dc(DS, Declarator::TypeNameContext);
4439   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4440   assert(TInfo && "couldn't build declarator info for anonymous struct");
4441 
4442   auto *ParentDecl = cast<RecordDecl>(CurContext);
4443   QualType RecTy = Context.getTypeDeclType(Record);
4444 
4445   // Create a declaration for this anonymous struct.
4446   NamedDecl *Anon = FieldDecl::Create(Context,
4447                              ParentDecl,
4448                              DS.getLocStart(),
4449                              DS.getLocStart(),
4450                              /*IdentifierInfo=*/nullptr,
4451                              RecTy,
4452                              TInfo,
4453                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4454                              /*InitStyle=*/ICIS_NoInit);
4455   Anon->setImplicit();
4456 
4457   // Add the anonymous struct object to the current context.
4458   CurContext->addDecl(Anon);
4459 
4460   // Inject the members of the anonymous struct into the current
4461   // context and into the identifier resolver chain for name lookup
4462   // purposes.
4463   SmallVector<NamedDecl*, 2> Chain;
4464   Chain.push_back(Anon);
4465 
4466   RecordDecl *RecordDef = Record->getDefinition();
4467   if (RequireCompleteType(Anon->getLocation(), RecTy,
4468                           diag::err_field_incomplete) ||
4469       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4470                                           AS_none, Chain)) {
4471     Anon->setInvalidDecl();
4472     ParentDecl->setInvalidDecl();
4473   }
4474 
4475   return Anon;
4476 }
4477 
4478 /// GetNameForDeclarator - Determine the full declaration name for the
4479 /// given Declarator.
4480 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4481   return GetNameFromUnqualifiedId(D.getName());
4482 }
4483 
4484 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4485 DeclarationNameInfo
4486 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4487   DeclarationNameInfo NameInfo;
4488   NameInfo.setLoc(Name.StartLocation);
4489 
4490   switch (Name.getKind()) {
4491 
4492   case UnqualifiedId::IK_ImplicitSelfParam:
4493   case UnqualifiedId::IK_Identifier:
4494     NameInfo.setName(Name.Identifier);
4495     NameInfo.setLoc(Name.StartLocation);
4496     return NameInfo;
4497 
4498   case UnqualifiedId::IK_OperatorFunctionId:
4499     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4500                                            Name.OperatorFunctionId.Operator));
4501     NameInfo.setLoc(Name.StartLocation);
4502     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4503       = Name.OperatorFunctionId.SymbolLocations[0];
4504     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4505       = Name.EndLocation.getRawEncoding();
4506     return NameInfo;
4507 
4508   case UnqualifiedId::IK_LiteralOperatorId:
4509     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4510                                                            Name.Identifier));
4511     NameInfo.setLoc(Name.StartLocation);
4512     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4513     return NameInfo;
4514 
4515   case UnqualifiedId::IK_ConversionFunctionId: {
4516     TypeSourceInfo *TInfo;
4517     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4518     if (Ty.isNull())
4519       return DeclarationNameInfo();
4520     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4521                                                Context.getCanonicalType(Ty)));
4522     NameInfo.setLoc(Name.StartLocation);
4523     NameInfo.setNamedTypeInfo(TInfo);
4524     return NameInfo;
4525   }
4526 
4527   case UnqualifiedId::IK_ConstructorName: {
4528     TypeSourceInfo *TInfo;
4529     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4530     if (Ty.isNull())
4531       return DeclarationNameInfo();
4532     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4533                                               Context.getCanonicalType(Ty)));
4534     NameInfo.setLoc(Name.StartLocation);
4535     NameInfo.setNamedTypeInfo(TInfo);
4536     return NameInfo;
4537   }
4538 
4539   case UnqualifiedId::IK_ConstructorTemplateId: {
4540     // In well-formed code, we can only have a constructor
4541     // template-id that refers to the current context, so go there
4542     // to find the actual type being constructed.
4543     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4544     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4545       return DeclarationNameInfo();
4546 
4547     // Determine the type of the class being constructed.
4548     QualType CurClassType = Context.getTypeDeclType(CurClass);
4549 
4550     // FIXME: Check two things: that the template-id names the same type as
4551     // CurClassType, and that the template-id does not occur when the name
4552     // was qualified.
4553 
4554     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4555                                     Context.getCanonicalType(CurClassType)));
4556     NameInfo.setLoc(Name.StartLocation);
4557     // FIXME: should we retrieve TypeSourceInfo?
4558     NameInfo.setNamedTypeInfo(nullptr);
4559     return NameInfo;
4560   }
4561 
4562   case UnqualifiedId::IK_DestructorName: {
4563     TypeSourceInfo *TInfo;
4564     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4565     if (Ty.isNull())
4566       return DeclarationNameInfo();
4567     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4568                                               Context.getCanonicalType(Ty)));
4569     NameInfo.setLoc(Name.StartLocation);
4570     NameInfo.setNamedTypeInfo(TInfo);
4571     return NameInfo;
4572   }
4573 
4574   case UnqualifiedId::IK_TemplateId: {
4575     TemplateName TName = Name.TemplateId->Template.get();
4576     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4577     return Context.getNameForTemplate(TName, TNameLoc);
4578   }
4579 
4580   } // switch (Name.getKind())
4581 
4582   llvm_unreachable("Unknown name kind");
4583 }
4584 
4585 static QualType getCoreType(QualType Ty) {
4586   do {
4587     if (Ty->isPointerType() || Ty->isReferenceType())
4588       Ty = Ty->getPointeeType();
4589     else if (Ty->isArrayType())
4590       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4591     else
4592       return Ty.withoutLocalFastQualifiers();
4593   } while (true);
4594 }
4595 
4596 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4597 /// and Definition have "nearly" matching parameters. This heuristic is
4598 /// used to improve diagnostics in the case where an out-of-line function
4599 /// definition doesn't match any declaration within the class or namespace.
4600 /// Also sets Params to the list of indices to the parameters that differ
4601 /// between the declaration and the definition. If hasSimilarParameters
4602 /// returns true and Params is empty, then all of the parameters match.
4603 static bool hasSimilarParameters(ASTContext &Context,
4604                                      FunctionDecl *Declaration,
4605                                      FunctionDecl *Definition,
4606                                      SmallVectorImpl<unsigned> &Params) {
4607   Params.clear();
4608   if (Declaration->param_size() != Definition->param_size())
4609     return false;
4610   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4611     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4612     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4613 
4614     // The parameter types are identical
4615     if (Context.hasSameType(DefParamTy, DeclParamTy))
4616       continue;
4617 
4618     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4619     QualType DefParamBaseTy = getCoreType(DefParamTy);
4620     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4621     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4622 
4623     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4624         (DeclTyName && DeclTyName == DefTyName))
4625       Params.push_back(Idx);
4626     else  // The two parameters aren't even close
4627       return false;
4628   }
4629 
4630   return true;
4631 }
4632 
4633 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4634 /// declarator needs to be rebuilt in the current instantiation.
4635 /// Any bits of declarator which appear before the name are valid for
4636 /// consideration here.  That's specifically the type in the decl spec
4637 /// and the base type in any member-pointer chunks.
4638 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4639                                                     DeclarationName Name) {
4640   // The types we specifically need to rebuild are:
4641   //   - typenames, typeofs, and decltypes
4642   //   - types which will become injected class names
4643   // Of course, we also need to rebuild any type referencing such a
4644   // type.  It's safest to just say "dependent", but we call out a
4645   // few cases here.
4646 
4647   DeclSpec &DS = D.getMutableDeclSpec();
4648   switch (DS.getTypeSpecType()) {
4649   case DeclSpec::TST_typename:
4650   case DeclSpec::TST_typeofType:
4651   case DeclSpec::TST_underlyingType:
4652   case DeclSpec::TST_atomic: {
4653     // Grab the type from the parser.
4654     TypeSourceInfo *TSI = nullptr;
4655     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4656     if (T.isNull() || !T->isDependentType()) break;
4657 
4658     // Make sure there's a type source info.  This isn't really much
4659     // of a waste; most dependent types should have type source info
4660     // attached already.
4661     if (!TSI)
4662       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4663 
4664     // Rebuild the type in the current instantiation.
4665     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4666     if (!TSI) return true;
4667 
4668     // Store the new type back in the decl spec.
4669     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4670     DS.UpdateTypeRep(LocType);
4671     break;
4672   }
4673 
4674   case DeclSpec::TST_decltype:
4675   case DeclSpec::TST_typeofExpr: {
4676     Expr *E = DS.getRepAsExpr();
4677     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4678     if (Result.isInvalid()) return true;
4679     DS.UpdateExprRep(Result.get());
4680     break;
4681   }
4682 
4683   default:
4684     // Nothing to do for these decl specs.
4685     break;
4686   }
4687 
4688   // It doesn't matter what order we do this in.
4689   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4690     DeclaratorChunk &Chunk = D.getTypeObject(I);
4691 
4692     // The only type information in the declarator which can come
4693     // before the declaration name is the base type of a member
4694     // pointer.
4695     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4696       continue;
4697 
4698     // Rebuild the scope specifier in-place.
4699     CXXScopeSpec &SS = Chunk.Mem.Scope();
4700     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4701       return true;
4702   }
4703 
4704   return false;
4705 }
4706 
4707 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4708   D.setFunctionDefinitionKind(FDK_Declaration);
4709   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4710 
4711   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4712       Dcl && Dcl->getDeclContext()->isFileContext())
4713     Dcl->setTopLevelDeclInObjCContainer();
4714 
4715   return Dcl;
4716 }
4717 
4718 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4719 ///   If T is the name of a class, then each of the following shall have a
4720 ///   name different from T:
4721 ///     - every static data member of class T;
4722 ///     - every member function of class T
4723 ///     - every member of class T that is itself a type;
4724 /// \returns true if the declaration name violates these rules.
4725 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4726                                    DeclarationNameInfo NameInfo) {
4727   DeclarationName Name = NameInfo.getName();
4728 
4729   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4730   while (Record && Record->isAnonymousStructOrUnion())
4731     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4732   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4733     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4734     return true;
4735   }
4736 
4737   return false;
4738 }
4739 
4740 /// \brief Diagnose a declaration whose declarator-id has the given
4741 /// nested-name-specifier.
4742 ///
4743 /// \param SS The nested-name-specifier of the declarator-id.
4744 ///
4745 /// \param DC The declaration context to which the nested-name-specifier
4746 /// resolves.
4747 ///
4748 /// \param Name The name of the entity being declared.
4749 ///
4750 /// \param Loc The location of the name of the entity being declared.
4751 ///
4752 /// \returns true if we cannot safely recover from this error, false otherwise.
4753 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4754                                         DeclarationName Name,
4755                                         SourceLocation Loc) {
4756   DeclContext *Cur = CurContext;
4757   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4758     Cur = Cur->getParent();
4759 
4760   // If the user provided a superfluous scope specifier that refers back to the
4761   // class in which the entity is already declared, diagnose and ignore it.
4762   //
4763   // class X {
4764   //   void X::f();
4765   // };
4766   //
4767   // Note, it was once ill-formed to give redundant qualification in all
4768   // contexts, but that rule was removed by DR482.
4769   if (Cur->Equals(DC)) {
4770     if (Cur->isRecord()) {
4771       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4772                                       : diag::err_member_extra_qualification)
4773         << Name << FixItHint::CreateRemoval(SS.getRange());
4774       SS.clear();
4775     } else {
4776       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4777     }
4778     return false;
4779   }
4780 
4781   // Check whether the qualifying scope encloses the scope of the original
4782   // declaration.
4783   if (!Cur->Encloses(DC)) {
4784     if (Cur->isRecord())
4785       Diag(Loc, diag::err_member_qualification)
4786         << Name << SS.getRange();
4787     else if (isa<TranslationUnitDecl>(DC))
4788       Diag(Loc, diag::err_invalid_declarator_global_scope)
4789         << Name << SS.getRange();
4790     else if (isa<FunctionDecl>(Cur))
4791       Diag(Loc, diag::err_invalid_declarator_in_function)
4792         << Name << SS.getRange();
4793     else if (isa<BlockDecl>(Cur))
4794       Diag(Loc, diag::err_invalid_declarator_in_block)
4795         << Name << SS.getRange();
4796     else
4797       Diag(Loc, diag::err_invalid_declarator_scope)
4798       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4799 
4800     return true;
4801   }
4802 
4803   if (Cur->isRecord()) {
4804     // Cannot qualify members within a class.
4805     Diag(Loc, diag::err_member_qualification)
4806       << Name << SS.getRange();
4807     SS.clear();
4808 
4809     // C++ constructors and destructors with incorrect scopes can break
4810     // our AST invariants by having the wrong underlying types. If
4811     // that's the case, then drop this declaration entirely.
4812     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4813          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4814         !Context.hasSameType(Name.getCXXNameType(),
4815                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4816       return true;
4817 
4818     return false;
4819   }
4820 
4821   // C++11 [dcl.meaning]p1:
4822   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4823   //   not begin with a decltype-specifer"
4824   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4825   while (SpecLoc.getPrefix())
4826     SpecLoc = SpecLoc.getPrefix();
4827   if (dyn_cast_or_null<DecltypeType>(
4828         SpecLoc.getNestedNameSpecifier()->getAsType()))
4829     Diag(Loc, diag::err_decltype_in_declarator)
4830       << SpecLoc.getTypeLoc().getSourceRange();
4831 
4832   return false;
4833 }
4834 
4835 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4836                                   MultiTemplateParamsArg TemplateParamLists) {
4837   // TODO: consider using NameInfo for diagnostic.
4838   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4839   DeclarationName Name = NameInfo.getName();
4840 
4841   // All of these full declarators require an identifier.  If it doesn't have
4842   // one, the ParsedFreeStandingDeclSpec action should be used.
4843   if (!Name) {
4844     if (!D.isInvalidType())  // Reject this if we think it is valid.
4845       Diag(D.getDeclSpec().getLocStart(),
4846            diag::err_declarator_need_ident)
4847         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4848     return nullptr;
4849   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4850     return nullptr;
4851 
4852   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4853   // we find one that is.
4854   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4855          (S->getFlags() & Scope::TemplateParamScope) != 0)
4856     S = S->getParent();
4857 
4858   DeclContext *DC = CurContext;
4859   if (D.getCXXScopeSpec().isInvalid())
4860     D.setInvalidType();
4861   else if (D.getCXXScopeSpec().isSet()) {
4862     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4863                                         UPPC_DeclarationQualifier))
4864       return nullptr;
4865 
4866     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4867     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4868     if (!DC || isa<EnumDecl>(DC)) {
4869       // If we could not compute the declaration context, it's because the
4870       // declaration context is dependent but does not refer to a class,
4871       // class template, or class template partial specialization. Complain
4872       // and return early, to avoid the coming semantic disaster.
4873       Diag(D.getIdentifierLoc(),
4874            diag::err_template_qualified_declarator_no_match)
4875         << D.getCXXScopeSpec().getScopeRep()
4876         << D.getCXXScopeSpec().getRange();
4877       return nullptr;
4878     }
4879     bool IsDependentContext = DC->isDependentContext();
4880 
4881     if (!IsDependentContext &&
4882         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4883       return nullptr;
4884 
4885     // If a class is incomplete, do not parse entities inside it.
4886     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4887       Diag(D.getIdentifierLoc(),
4888            diag::err_member_def_undefined_record)
4889         << Name << DC << D.getCXXScopeSpec().getRange();
4890       return nullptr;
4891     }
4892     if (!D.getDeclSpec().isFriendSpecified()) {
4893       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4894                                       Name, D.getIdentifierLoc())) {
4895         if (DC->isRecord())
4896           return nullptr;
4897 
4898         D.setInvalidType();
4899       }
4900     }
4901 
4902     // Check whether we need to rebuild the type of the given
4903     // declaration in the current instantiation.
4904     if (EnteringContext && IsDependentContext &&
4905         TemplateParamLists.size() != 0) {
4906       ContextRAII SavedContext(*this, DC);
4907       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4908         D.setInvalidType();
4909     }
4910   }
4911 
4912   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4913   QualType R = TInfo->getType();
4914 
4915   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4916     // If this is a typedef, we'll end up spewing multiple diagnostics.
4917     // Just return early; it's safer. If this is a function, let the
4918     // "constructor cannot have a return type" diagnostic handle it.
4919     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4920       return nullptr;
4921 
4922   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4923                                       UPPC_DeclarationType))
4924     D.setInvalidType();
4925 
4926   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4927                         ForRedeclaration);
4928 
4929   // See if this is a redefinition of a variable in the same scope.
4930   if (!D.getCXXScopeSpec().isSet()) {
4931     bool IsLinkageLookup = false;
4932     bool CreateBuiltins = false;
4933 
4934     // If the declaration we're planning to build will be a function
4935     // or object with linkage, then look for another declaration with
4936     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4937     //
4938     // If the declaration we're planning to build will be declared with
4939     // external linkage in the translation unit, create any builtin with
4940     // the same name.
4941     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4942       /* Do nothing*/;
4943     else if (CurContext->isFunctionOrMethod() &&
4944              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4945               R->isFunctionType())) {
4946       IsLinkageLookup = true;
4947       CreateBuiltins =
4948           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4949     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4950                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4951       CreateBuiltins = true;
4952 
4953     if (IsLinkageLookup)
4954       Previous.clear(LookupRedeclarationWithLinkage);
4955 
4956     LookupName(Previous, S, CreateBuiltins);
4957   } else { // Something like "int foo::x;"
4958     LookupQualifiedName(Previous, DC);
4959 
4960     // C++ [dcl.meaning]p1:
4961     //   When the declarator-id is qualified, the declaration shall refer to a
4962     //  previously declared member of the class or namespace to which the
4963     //  qualifier refers (or, in the case of a namespace, of an element of the
4964     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4965     //  thereof; [...]
4966     //
4967     // Note that we already checked the context above, and that we do not have
4968     // enough information to make sure that Previous contains the declaration
4969     // we want to match. For example, given:
4970     //
4971     //   class X {
4972     //     void f();
4973     //     void f(float);
4974     //   };
4975     //
4976     //   void X::f(int) { } // ill-formed
4977     //
4978     // In this case, Previous will point to the overload set
4979     // containing the two f's declared in X, but neither of them
4980     // matches.
4981 
4982     // C++ [dcl.meaning]p1:
4983     //   [...] the member shall not merely have been introduced by a
4984     //   using-declaration in the scope of the class or namespace nominated by
4985     //   the nested-name-specifier of the declarator-id.
4986     RemoveUsingDecls(Previous);
4987   }
4988 
4989   if (Previous.isSingleResult() &&
4990       Previous.getFoundDecl()->isTemplateParameter()) {
4991     // Maybe we will complain about the shadowed template parameter.
4992     if (!D.isInvalidType())
4993       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4994                                       Previous.getFoundDecl());
4995 
4996     // Just pretend that we didn't see the previous declaration.
4997     Previous.clear();
4998   }
4999 
5000   // In C++, the previous declaration we find might be a tag type
5001   // (class or enum). In this case, the new declaration will hide the
5002   // tag type. Note that this does does not apply if we're declaring a
5003   // typedef (C++ [dcl.typedef]p4).
5004   if (Previous.isSingleTagDecl() &&
5005       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5006     Previous.clear();
5007 
5008   // Check that there are no default arguments other than in the parameters
5009   // of a function declaration (C++ only).
5010   if (getLangOpts().CPlusPlus)
5011     CheckExtraCXXDefaultArguments(D);
5012 
5013   if (D.getDeclSpec().isConceptSpecified()) {
5014     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5015     // applied only to the definition of a function template or variable
5016     // template, declared in namespace scope
5017     if (!TemplateParamLists.size()) {
5018       Diag(D.getDeclSpec().getConceptSpecLoc(),
5019            diag:: err_concept_wrong_decl_kind);
5020       return nullptr;
5021     }
5022 
5023     if (!DC->getRedeclContext()->isFileContext()) {
5024       Diag(D.getIdentifierLoc(),
5025            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5026       return nullptr;
5027     }
5028   }
5029 
5030   NamedDecl *New;
5031 
5032   bool AddToScope = true;
5033   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5034     if (TemplateParamLists.size()) {
5035       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5036       return nullptr;
5037     }
5038 
5039     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5040   } else if (R->isFunctionType()) {
5041     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5042                                   TemplateParamLists,
5043                                   AddToScope);
5044   } else {
5045     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5046                                   AddToScope);
5047   }
5048 
5049   if (!New)
5050     return nullptr;
5051 
5052   // If this has an identifier and is not an invalid redeclaration or
5053   // function template specialization, add it to the scope stack.
5054   if (New->getDeclName() && AddToScope &&
5055        !(D.isRedeclaration() && New->isInvalidDecl())) {
5056     // Only make a locally-scoped extern declaration visible if it is the first
5057     // declaration of this entity. Qualified lookup for such an entity should
5058     // only find this declaration if there is no visible declaration of it.
5059     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5060     PushOnScopeChains(New, S, AddToContext);
5061     if (!AddToContext)
5062       CurContext->addHiddenDecl(New);
5063   }
5064 
5065   if (isInOpenMPDeclareTargetContext())
5066     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5067 
5068   return New;
5069 }
5070 
5071 /// Helper method to turn variable array types into constant array
5072 /// types in certain situations which would otherwise be errors (for
5073 /// GCC compatibility).
5074 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5075                                                     ASTContext &Context,
5076                                                     bool &SizeIsNegative,
5077                                                     llvm::APSInt &Oversized) {
5078   // This method tries to turn a variable array into a constant
5079   // array even when the size isn't an ICE.  This is necessary
5080   // for compatibility with code that depends on gcc's buggy
5081   // constant expression folding, like struct {char x[(int)(char*)2];}
5082   SizeIsNegative = false;
5083   Oversized = 0;
5084 
5085   if (T->isDependentType())
5086     return QualType();
5087 
5088   QualifierCollector Qs;
5089   const Type *Ty = Qs.strip(T);
5090 
5091   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5092     QualType Pointee = PTy->getPointeeType();
5093     QualType FixedType =
5094         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5095                                             Oversized);
5096     if (FixedType.isNull()) return FixedType;
5097     FixedType = Context.getPointerType(FixedType);
5098     return Qs.apply(Context, FixedType);
5099   }
5100   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5101     QualType Inner = PTy->getInnerType();
5102     QualType FixedType =
5103         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5104                                             Oversized);
5105     if (FixedType.isNull()) return FixedType;
5106     FixedType = Context.getParenType(FixedType);
5107     return Qs.apply(Context, FixedType);
5108   }
5109 
5110   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5111   if (!VLATy)
5112     return QualType();
5113   // FIXME: We should probably handle this case
5114   if (VLATy->getElementType()->isVariablyModifiedType())
5115     return QualType();
5116 
5117   llvm::APSInt Res;
5118   if (!VLATy->getSizeExpr() ||
5119       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5120     return QualType();
5121 
5122   // Check whether the array size is negative.
5123   if (Res.isSigned() && Res.isNegative()) {
5124     SizeIsNegative = true;
5125     return QualType();
5126   }
5127 
5128   // Check whether the array is too large to be addressed.
5129   unsigned ActiveSizeBits
5130     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5131                                               Res);
5132   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5133     Oversized = Res;
5134     return QualType();
5135   }
5136 
5137   return Context.getConstantArrayType(VLATy->getElementType(),
5138                                       Res, ArrayType::Normal, 0);
5139 }
5140 
5141 static void
5142 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5143   SrcTL = SrcTL.getUnqualifiedLoc();
5144   DstTL = DstTL.getUnqualifiedLoc();
5145   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5146     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5147     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5148                                       DstPTL.getPointeeLoc());
5149     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5150     return;
5151   }
5152   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5153     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5154     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5155                                       DstPTL.getInnerLoc());
5156     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5157     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5158     return;
5159   }
5160   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5161   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5162   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5163   TypeLoc DstElemTL = DstATL.getElementLoc();
5164   DstElemTL.initializeFullCopy(SrcElemTL);
5165   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5166   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5167   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5168 }
5169 
5170 /// Helper method to turn variable array types into constant array
5171 /// types in certain situations which would otherwise be errors (for
5172 /// GCC compatibility).
5173 static TypeSourceInfo*
5174 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5175                                               ASTContext &Context,
5176                                               bool &SizeIsNegative,
5177                                               llvm::APSInt &Oversized) {
5178   QualType FixedTy
5179     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5180                                           SizeIsNegative, Oversized);
5181   if (FixedTy.isNull())
5182     return nullptr;
5183   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5184   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5185                                     FixedTInfo->getTypeLoc());
5186   return FixedTInfo;
5187 }
5188 
5189 /// \brief Register the given locally-scoped extern "C" declaration so
5190 /// that it can be found later for redeclarations. We include any extern "C"
5191 /// declaration that is not visible in the translation unit here, not just
5192 /// function-scope declarations.
5193 void
5194 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5195   if (!getLangOpts().CPlusPlus &&
5196       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5197     // Don't need to track declarations in the TU in C.
5198     return;
5199 
5200   // Note that we have a locally-scoped external with this name.
5201   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5202 }
5203 
5204 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5205   // FIXME: We can have multiple results via __attribute__((overloadable)).
5206   auto Result = Context.getExternCContextDecl()->lookup(Name);
5207   return Result.empty() ? nullptr : *Result.begin();
5208 }
5209 
5210 /// \brief Diagnose function specifiers on a declaration of an identifier that
5211 /// does not identify a function.
5212 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5213   // FIXME: We should probably indicate the identifier in question to avoid
5214   // confusion for constructs like "inline int a(), b;"
5215   if (DS.isInlineSpecified())
5216     Diag(DS.getInlineSpecLoc(),
5217          diag::err_inline_non_function);
5218 
5219   if (DS.isVirtualSpecified())
5220     Diag(DS.getVirtualSpecLoc(),
5221          diag::err_virtual_non_function);
5222 
5223   if (DS.isExplicitSpecified())
5224     Diag(DS.getExplicitSpecLoc(),
5225          diag::err_explicit_non_function);
5226 
5227   if (DS.isNoreturnSpecified())
5228     Diag(DS.getNoreturnSpecLoc(),
5229          diag::err_noreturn_non_function);
5230 }
5231 
5232 NamedDecl*
5233 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5234                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5235   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5236   if (D.getCXXScopeSpec().isSet()) {
5237     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5238       << D.getCXXScopeSpec().getRange();
5239     D.setInvalidType();
5240     // Pretend we didn't see the scope specifier.
5241     DC = CurContext;
5242     Previous.clear();
5243   }
5244 
5245   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5246 
5247   if (D.getDeclSpec().isConstexprSpecified())
5248     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5249       << 1;
5250   if (D.getDeclSpec().isConceptSpecified())
5251     Diag(D.getDeclSpec().getConceptSpecLoc(),
5252          diag::err_concept_wrong_decl_kind);
5253 
5254   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5255     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5256       << D.getName().getSourceRange();
5257     return nullptr;
5258   }
5259 
5260   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5261   if (!NewTD) return nullptr;
5262 
5263   // Handle attributes prior to checking for duplicates in MergeVarDecl
5264   ProcessDeclAttributes(S, NewTD, D);
5265 
5266   CheckTypedefForVariablyModifiedType(S, NewTD);
5267 
5268   bool Redeclaration = D.isRedeclaration();
5269   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5270   D.setRedeclaration(Redeclaration);
5271   return ND;
5272 }
5273 
5274 void
5275 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5276   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5277   // then it shall have block scope.
5278   // Note that variably modified types must be fixed before merging the decl so
5279   // that redeclarations will match.
5280   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5281   QualType T = TInfo->getType();
5282   if (T->isVariablyModifiedType()) {
5283     getCurFunction()->setHasBranchProtectedScope();
5284 
5285     if (S->getFnParent() == nullptr) {
5286       bool SizeIsNegative;
5287       llvm::APSInt Oversized;
5288       TypeSourceInfo *FixedTInfo =
5289         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5290                                                       SizeIsNegative,
5291                                                       Oversized);
5292       if (FixedTInfo) {
5293         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5294         NewTD->setTypeSourceInfo(FixedTInfo);
5295       } else {
5296         if (SizeIsNegative)
5297           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5298         else if (T->isVariableArrayType())
5299           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5300         else if (Oversized.getBoolValue())
5301           Diag(NewTD->getLocation(), diag::err_array_too_large)
5302             << Oversized.toString(10);
5303         else
5304           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5305         NewTD->setInvalidDecl();
5306       }
5307     }
5308   }
5309 }
5310 
5311 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5312 /// declares a typedef-name, either using the 'typedef' type specifier or via
5313 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5314 NamedDecl*
5315 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5316                            LookupResult &Previous, bool &Redeclaration) {
5317   // Merge the decl with the existing one if appropriate. If the decl is
5318   // in an outer scope, it isn't the same thing.
5319   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5320                        /*AllowInlineNamespace*/false);
5321   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5322   if (!Previous.empty()) {
5323     Redeclaration = true;
5324     MergeTypedefNameDecl(S, NewTD, Previous);
5325   }
5326 
5327   // If this is the C FILE type, notify the AST context.
5328   if (IdentifierInfo *II = NewTD->getIdentifier())
5329     if (!NewTD->isInvalidDecl() &&
5330         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5331       if (II->isStr("FILE"))
5332         Context.setFILEDecl(NewTD);
5333       else if (II->isStr("jmp_buf"))
5334         Context.setjmp_bufDecl(NewTD);
5335       else if (II->isStr("sigjmp_buf"))
5336         Context.setsigjmp_bufDecl(NewTD);
5337       else if (II->isStr("ucontext_t"))
5338         Context.setucontext_tDecl(NewTD);
5339     }
5340 
5341   return NewTD;
5342 }
5343 
5344 /// \brief Determines whether the given declaration is an out-of-scope
5345 /// previous declaration.
5346 ///
5347 /// This routine should be invoked when name lookup has found a
5348 /// previous declaration (PrevDecl) that is not in the scope where a
5349 /// new declaration by the same name is being introduced. If the new
5350 /// declaration occurs in a local scope, previous declarations with
5351 /// linkage may still be considered previous declarations (C99
5352 /// 6.2.2p4-5, C++ [basic.link]p6).
5353 ///
5354 /// \param PrevDecl the previous declaration found by name
5355 /// lookup
5356 ///
5357 /// \param DC the context in which the new declaration is being
5358 /// declared.
5359 ///
5360 /// \returns true if PrevDecl is an out-of-scope previous declaration
5361 /// for a new delcaration with the same name.
5362 static bool
5363 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5364                                 ASTContext &Context) {
5365   if (!PrevDecl)
5366     return false;
5367 
5368   if (!PrevDecl->hasLinkage())
5369     return false;
5370 
5371   if (Context.getLangOpts().CPlusPlus) {
5372     // C++ [basic.link]p6:
5373     //   If there is a visible declaration of an entity with linkage
5374     //   having the same name and type, ignoring entities declared
5375     //   outside the innermost enclosing namespace scope, the block
5376     //   scope declaration declares that same entity and receives the
5377     //   linkage of the previous declaration.
5378     DeclContext *OuterContext = DC->getRedeclContext();
5379     if (!OuterContext->isFunctionOrMethod())
5380       // This rule only applies to block-scope declarations.
5381       return false;
5382 
5383     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5384     if (PrevOuterContext->isRecord())
5385       // We found a member function: ignore it.
5386       return false;
5387 
5388     // Find the innermost enclosing namespace for the new and
5389     // previous declarations.
5390     OuterContext = OuterContext->getEnclosingNamespaceContext();
5391     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5392 
5393     // The previous declaration is in a different namespace, so it
5394     // isn't the same function.
5395     if (!OuterContext->Equals(PrevOuterContext))
5396       return false;
5397   }
5398 
5399   return true;
5400 }
5401 
5402 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5403   CXXScopeSpec &SS = D.getCXXScopeSpec();
5404   if (!SS.isSet()) return;
5405   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5406 }
5407 
5408 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5409   QualType type = decl->getType();
5410   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5411   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5412     // Various kinds of declaration aren't allowed to be __autoreleasing.
5413     unsigned kind = -1U;
5414     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5415       if (var->hasAttr<BlocksAttr>())
5416         kind = 0; // __block
5417       else if (!var->hasLocalStorage())
5418         kind = 1; // global
5419     } else if (isa<ObjCIvarDecl>(decl)) {
5420       kind = 3; // ivar
5421     } else if (isa<FieldDecl>(decl)) {
5422       kind = 2; // field
5423     }
5424 
5425     if (kind != -1U) {
5426       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5427         << kind;
5428     }
5429   } else if (lifetime == Qualifiers::OCL_None) {
5430     // Try to infer lifetime.
5431     if (!type->isObjCLifetimeType())
5432       return false;
5433 
5434     lifetime = type->getObjCARCImplicitLifetime();
5435     type = Context.getLifetimeQualifiedType(type, lifetime);
5436     decl->setType(type);
5437   }
5438 
5439   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5440     // Thread-local variables cannot have lifetime.
5441     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5442         var->getTLSKind()) {
5443       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5444         << var->getType();
5445       return true;
5446     }
5447   }
5448 
5449   return false;
5450 }
5451 
5452 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5453   // Ensure that an auto decl is deduced otherwise the checks below might cache
5454   // the wrong linkage.
5455   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5456 
5457   // 'weak' only applies to declarations with external linkage.
5458   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5459     if (!ND.isExternallyVisible()) {
5460       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5461       ND.dropAttr<WeakAttr>();
5462     }
5463   }
5464   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5465     if (ND.isExternallyVisible()) {
5466       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5467       ND.dropAttr<WeakRefAttr>();
5468       ND.dropAttr<AliasAttr>();
5469     }
5470   }
5471 
5472   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5473     if (VD->hasInit()) {
5474       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5475         assert(VD->isThisDeclarationADefinition() &&
5476                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5477         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5478         VD->dropAttr<AliasAttr>();
5479       }
5480     }
5481   }
5482 
5483   // 'selectany' only applies to externally visible variable declarations.
5484   // It does not apply to functions.
5485   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5486     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5487       S.Diag(Attr->getLocation(),
5488              diag::err_attribute_selectany_non_extern_data);
5489       ND.dropAttr<SelectAnyAttr>();
5490     }
5491   }
5492 
5493   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5494     // dll attributes require external linkage. Static locals may have external
5495     // linkage but still cannot be explicitly imported or exported.
5496     auto *VD = dyn_cast<VarDecl>(&ND);
5497     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5498       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5499         << &ND << Attr;
5500       ND.setInvalidDecl();
5501     }
5502   }
5503 
5504   // Virtual functions cannot be marked as 'notail'.
5505   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5506     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5507       if (MD->isVirtual()) {
5508         S.Diag(ND.getLocation(),
5509                diag::err_invalid_attribute_on_virtual_function)
5510             << Attr;
5511         ND.dropAttr<NotTailCalledAttr>();
5512       }
5513 }
5514 
5515 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5516                                            NamedDecl *NewDecl,
5517                                            bool IsSpecialization) {
5518   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5519     OldDecl = OldTD->getTemplatedDecl();
5520   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5521     NewDecl = NewTD->getTemplatedDecl();
5522 
5523   if (!OldDecl || !NewDecl)
5524     return;
5525 
5526   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5527   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5528   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5529   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5530 
5531   // dllimport and dllexport are inheritable attributes so we have to exclude
5532   // inherited attribute instances.
5533   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5534                     (NewExportAttr && !NewExportAttr->isInherited());
5535 
5536   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5537   // the only exception being explicit specializations.
5538   // Implicitly generated declarations are also excluded for now because there
5539   // is no other way to switch these to use dllimport or dllexport.
5540   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5541 
5542   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5543     // Allow with a warning for free functions and global variables.
5544     bool JustWarn = false;
5545     if (!OldDecl->isCXXClassMember()) {
5546       auto *VD = dyn_cast<VarDecl>(OldDecl);
5547       if (VD && !VD->getDescribedVarTemplate())
5548         JustWarn = true;
5549       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5550       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5551         JustWarn = true;
5552     }
5553 
5554     // We cannot change a declaration that's been used because IR has already
5555     // been emitted. Dllimported functions will still work though (modulo
5556     // address equality) as they can use the thunk.
5557     if (OldDecl->isUsed())
5558       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5559         JustWarn = false;
5560 
5561     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5562                                : diag::err_attribute_dll_redeclaration;
5563     S.Diag(NewDecl->getLocation(), DiagID)
5564         << NewDecl
5565         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5566     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5567     if (!JustWarn) {
5568       NewDecl->setInvalidDecl();
5569       return;
5570     }
5571   }
5572 
5573   // A redeclaration is not allowed to drop a dllimport attribute, the only
5574   // exceptions being inline function definitions, local extern declarations,
5575   // and qualified friend declarations.
5576   // NB: MSVC converts such a declaration to dllexport.
5577   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5578   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5579     // Ignore static data because out-of-line definitions are diagnosed
5580     // separately.
5581     IsStaticDataMember = VD->isStaticDataMember();
5582   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5583     IsInline = FD->isInlined();
5584     IsQualifiedFriend = FD->getQualifier() &&
5585                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5586   }
5587 
5588   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5589       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5590     S.Diag(NewDecl->getLocation(),
5591            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5592       << NewDecl << OldImportAttr;
5593     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5594     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5595     OldDecl->dropAttr<DLLImportAttr>();
5596     NewDecl->dropAttr<DLLImportAttr>();
5597   } else if (IsInline && OldImportAttr &&
5598              !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5599     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5600     OldDecl->dropAttr<DLLImportAttr>();
5601     NewDecl->dropAttr<DLLImportAttr>();
5602     S.Diag(NewDecl->getLocation(),
5603            diag::warn_dllimport_dropped_from_inline_function)
5604         << NewDecl << OldImportAttr;
5605   }
5606 }
5607 
5608 /// Given that we are within the definition of the given function,
5609 /// will that definition behave like C99's 'inline', where the
5610 /// definition is discarded except for optimization purposes?
5611 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5612   // Try to avoid calling GetGVALinkageForFunction.
5613 
5614   // All cases of this require the 'inline' keyword.
5615   if (!FD->isInlined()) return false;
5616 
5617   // This is only possible in C++ with the gnu_inline attribute.
5618   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5619     return false;
5620 
5621   // Okay, go ahead and call the relatively-more-expensive function.
5622 
5623 #ifndef NDEBUG
5624   // AST quite reasonably asserts that it's working on a function
5625   // definition.  We don't really have a way to tell it that we're
5626   // currently defining the function, so just lie to it in +Asserts
5627   // builds.  This is an awful hack.
5628   FD->setLazyBody(1);
5629 #endif
5630 
5631   bool isC99Inline =
5632       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5633 
5634 #ifndef NDEBUG
5635   FD->setLazyBody(0);
5636 #endif
5637 
5638   return isC99Inline;
5639 }
5640 
5641 /// Determine whether a variable is extern "C" prior to attaching
5642 /// an initializer. We can't just call isExternC() here, because that
5643 /// will also compute and cache whether the declaration is externally
5644 /// visible, which might change when we attach the initializer.
5645 ///
5646 /// This can only be used if the declaration is known to not be a
5647 /// redeclaration of an internal linkage declaration.
5648 ///
5649 /// For instance:
5650 ///
5651 ///   auto x = []{};
5652 ///
5653 /// Attaching the initializer here makes this declaration not externally
5654 /// visible, because its type has internal linkage.
5655 ///
5656 /// FIXME: This is a hack.
5657 template<typename T>
5658 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5659   if (S.getLangOpts().CPlusPlus) {
5660     // In C++, the overloadable attribute negates the effects of extern "C".
5661     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5662       return false;
5663 
5664     // So do CUDA's host/device attributes.
5665     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5666                                  D->template hasAttr<CUDAHostAttr>()))
5667       return false;
5668   }
5669   return D->isExternC();
5670 }
5671 
5672 static bool shouldConsiderLinkage(const VarDecl *VD) {
5673   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5674   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5675     return VD->hasExternalStorage();
5676   if (DC->isFileContext())
5677     return true;
5678   if (DC->isRecord())
5679     return false;
5680   llvm_unreachable("Unexpected context");
5681 }
5682 
5683 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5684   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5685   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5686       isa<OMPDeclareReductionDecl>(DC))
5687     return true;
5688   if (DC->isRecord())
5689     return false;
5690   llvm_unreachable("Unexpected context");
5691 }
5692 
5693 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5694                           AttributeList::Kind Kind) {
5695   for (const AttributeList *L = AttrList; L; L = L->getNext())
5696     if (L->getKind() == Kind)
5697       return true;
5698   return false;
5699 }
5700 
5701 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5702                           AttributeList::Kind Kind) {
5703   // Check decl attributes on the DeclSpec.
5704   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5705     return true;
5706 
5707   // Walk the declarator structure, checking decl attributes that were in a type
5708   // position to the decl itself.
5709   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5710     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5711       return true;
5712   }
5713 
5714   // Finally, check attributes on the decl itself.
5715   return hasParsedAttr(S, PD.getAttributes(), Kind);
5716 }
5717 
5718 /// Adjust the \c DeclContext for a function or variable that might be a
5719 /// function-local external declaration.
5720 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5721   if (!DC->isFunctionOrMethod())
5722     return false;
5723 
5724   // If this is a local extern function or variable declared within a function
5725   // template, don't add it into the enclosing namespace scope until it is
5726   // instantiated; it might have a dependent type right now.
5727   if (DC->isDependentContext())
5728     return true;
5729 
5730   // C++11 [basic.link]p7:
5731   //   When a block scope declaration of an entity with linkage is not found to
5732   //   refer to some other declaration, then that entity is a member of the
5733   //   innermost enclosing namespace.
5734   //
5735   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5736   // semantically-enclosing namespace, not a lexically-enclosing one.
5737   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5738     DC = DC->getParent();
5739   return true;
5740 }
5741 
5742 /// \brief Returns true if given declaration has external C language linkage.
5743 static bool isDeclExternC(const Decl *D) {
5744   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5745     return FD->isExternC();
5746   if (const auto *VD = dyn_cast<VarDecl>(D))
5747     return VD->isExternC();
5748 
5749   llvm_unreachable("Unknown type of decl!");
5750 }
5751 
5752 NamedDecl *
5753 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5754                               TypeSourceInfo *TInfo, LookupResult &Previous,
5755                               MultiTemplateParamsArg TemplateParamLists,
5756                               bool &AddToScope) {
5757   QualType R = TInfo->getType();
5758   DeclarationName Name = GetNameForDeclarator(D).getName();
5759 
5760   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5761   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5762   // argument.
5763   if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) {
5764     Diag(D.getIdentifierLoc(),
5765          diag::err_opencl_type_can_only_be_used_as_function_parameter)
5766         << R;
5767     D.setInvalidType();
5768     return nullptr;
5769   }
5770 
5771   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5772   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5773 
5774   // dllimport globals without explicit storage class are treated as extern. We
5775   // have to change the storage class this early to get the right DeclContext.
5776   if (SC == SC_None && !DC->isRecord() &&
5777       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5778       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5779     SC = SC_Extern;
5780 
5781   DeclContext *OriginalDC = DC;
5782   bool IsLocalExternDecl = SC == SC_Extern &&
5783                            adjustContextForLocalExternDecl(DC);
5784 
5785   if (getLangOpts().OpenCL) {
5786     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5787     QualType NR = R;
5788     while (NR->isPointerType()) {
5789       if (NR->isFunctionPointerType()) {
5790         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5791         D.setInvalidType();
5792         break;
5793       }
5794       NR = NR->getPointeeType();
5795     }
5796 
5797     if (!getOpenCLOptions().cl_khr_fp16) {
5798       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5799       // half array type (unless the cl_khr_fp16 extension is enabled).
5800       if (Context.getBaseElementType(R)->isHalfType()) {
5801         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5802         D.setInvalidType();
5803       }
5804     }
5805   }
5806 
5807   if (SCSpec == DeclSpec::SCS_mutable) {
5808     // mutable can only appear on non-static class members, so it's always
5809     // an error here
5810     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5811     D.setInvalidType();
5812     SC = SC_None;
5813   }
5814 
5815   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5816       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5817                               D.getDeclSpec().getStorageClassSpecLoc())) {
5818     // In C++11, the 'register' storage class specifier is deprecated.
5819     // Suppress the warning in system macros, it's used in macros in some
5820     // popular C system headers, such as in glibc's htonl() macro.
5821     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5822          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5823                                    : diag::warn_deprecated_register)
5824       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5825   }
5826 
5827   IdentifierInfo *II = Name.getAsIdentifierInfo();
5828   if (!II) {
5829     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5830       << Name;
5831     return nullptr;
5832   }
5833 
5834   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5835 
5836   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5837     // C99 6.9p2: The storage-class specifiers auto and register shall not
5838     // appear in the declaration specifiers in an external declaration.
5839     // Global Register+Asm is a GNU extension we support.
5840     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5841       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5842       D.setInvalidType();
5843     }
5844   }
5845 
5846   if (getLangOpts().OpenCL) {
5847     // OpenCL v1.2 s6.9.b p4:
5848     // The sampler type cannot be used with the __local and __global address
5849     // space qualifiers.
5850     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5851       R.getAddressSpace() == LangAS::opencl_global)) {
5852       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5853     }
5854 
5855     // OpenCL 1.2 spec, p6.9 r:
5856     // The event type cannot be used to declare a program scope variable.
5857     // The event type cannot be used with the __local, __constant and __global
5858     // address space qualifiers.
5859     if (R->isEventT()) {
5860       if (S->getParent() == nullptr) {
5861         Diag(D.getLocStart(), diag::err_event_t_global_var);
5862         D.setInvalidType();
5863       }
5864 
5865       if (R.getAddressSpace()) {
5866         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5867         D.setInvalidType();
5868       }
5869     }
5870   }
5871 
5872   bool IsExplicitSpecialization = false;
5873   bool IsVariableTemplateSpecialization = false;
5874   bool IsPartialSpecialization = false;
5875   bool IsVariableTemplate = false;
5876   VarDecl *NewVD = nullptr;
5877   VarTemplateDecl *NewTemplate = nullptr;
5878   TemplateParameterList *TemplateParams = nullptr;
5879   if (!getLangOpts().CPlusPlus) {
5880     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5881                             D.getIdentifierLoc(), II,
5882                             R, TInfo, SC);
5883 
5884     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5885       ParsingInitForAutoVars.insert(NewVD);
5886 
5887     if (D.isInvalidType())
5888       NewVD->setInvalidDecl();
5889   } else {
5890     bool Invalid = false;
5891 
5892     if (DC->isRecord() && !CurContext->isRecord()) {
5893       // This is an out-of-line definition of a static data member.
5894       switch (SC) {
5895       case SC_None:
5896         break;
5897       case SC_Static:
5898         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5899              diag::err_static_out_of_line)
5900           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5901         break;
5902       case SC_Auto:
5903       case SC_Register:
5904       case SC_Extern:
5905         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5906         // to names of variables declared in a block or to function parameters.
5907         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5908         // of class members
5909 
5910         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5911              diag::err_storage_class_for_static_member)
5912           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5913         break;
5914       case SC_PrivateExtern:
5915         llvm_unreachable("C storage class in c++!");
5916       }
5917     }
5918 
5919     if (SC == SC_Static && CurContext->isRecord()) {
5920       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5921         if (RD->isLocalClass())
5922           Diag(D.getIdentifierLoc(),
5923                diag::err_static_data_member_not_allowed_in_local_class)
5924             << Name << RD->getDeclName();
5925 
5926         // C++98 [class.union]p1: If a union contains a static data member,
5927         // the program is ill-formed. C++11 drops this restriction.
5928         if (RD->isUnion())
5929           Diag(D.getIdentifierLoc(),
5930                getLangOpts().CPlusPlus11
5931                  ? diag::warn_cxx98_compat_static_data_member_in_union
5932                  : diag::ext_static_data_member_in_union) << Name;
5933         // We conservatively disallow static data members in anonymous structs.
5934         else if (!RD->getDeclName())
5935           Diag(D.getIdentifierLoc(),
5936                diag::err_static_data_member_not_allowed_in_anon_struct)
5937             << Name << RD->isUnion();
5938       }
5939     }
5940 
5941     // Match up the template parameter lists with the scope specifier, then
5942     // determine whether we have a template or a template specialization.
5943     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5944         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5945         D.getCXXScopeSpec(),
5946         D.getName().getKind() == UnqualifiedId::IK_TemplateId
5947             ? D.getName().TemplateId
5948             : nullptr,
5949         TemplateParamLists,
5950         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5951 
5952     if (TemplateParams) {
5953       if (!TemplateParams->size() &&
5954           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5955         // There is an extraneous 'template<>' for this variable. Complain
5956         // about it, but allow the declaration of the variable.
5957         Diag(TemplateParams->getTemplateLoc(),
5958              diag::err_template_variable_noparams)
5959           << II
5960           << SourceRange(TemplateParams->getTemplateLoc(),
5961                          TemplateParams->getRAngleLoc());
5962         TemplateParams = nullptr;
5963       } else {
5964         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5965           // This is an explicit specialization or a partial specialization.
5966           // FIXME: Check that we can declare a specialization here.
5967           IsVariableTemplateSpecialization = true;
5968           IsPartialSpecialization = TemplateParams->size() > 0;
5969         } else { // if (TemplateParams->size() > 0)
5970           // This is a template declaration.
5971           IsVariableTemplate = true;
5972 
5973           // Check that we can declare a template here.
5974           if (CheckTemplateDeclScope(S, TemplateParams))
5975             return nullptr;
5976 
5977           // Only C++1y supports variable templates (N3651).
5978           Diag(D.getIdentifierLoc(),
5979                getLangOpts().CPlusPlus14
5980                    ? diag::warn_cxx11_compat_variable_template
5981                    : diag::ext_variable_template);
5982         }
5983       }
5984     } else {
5985       assert(
5986           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5987           "should have a 'template<>' for this decl");
5988     }
5989 
5990     if (IsVariableTemplateSpecialization) {
5991       SourceLocation TemplateKWLoc =
5992           TemplateParamLists.size() > 0
5993               ? TemplateParamLists[0]->getTemplateLoc()
5994               : SourceLocation();
5995       DeclResult Res = ActOnVarTemplateSpecialization(
5996           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5997           IsPartialSpecialization);
5998       if (Res.isInvalid())
5999         return nullptr;
6000       NewVD = cast<VarDecl>(Res.get());
6001       AddToScope = false;
6002     } else
6003       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6004                               D.getIdentifierLoc(), II, R, TInfo, SC);
6005 
6006     // If this is supposed to be a variable template, create it as such.
6007     if (IsVariableTemplate) {
6008       NewTemplate =
6009           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6010                                   TemplateParams, NewVD);
6011       NewVD->setDescribedVarTemplate(NewTemplate);
6012     }
6013 
6014     // If this decl has an auto type in need of deduction, make a note of the
6015     // Decl so we can diagnose uses of it in its own initializer.
6016     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6017       ParsingInitForAutoVars.insert(NewVD);
6018 
6019     if (D.isInvalidType() || Invalid) {
6020       NewVD->setInvalidDecl();
6021       if (NewTemplate)
6022         NewTemplate->setInvalidDecl();
6023     }
6024 
6025     SetNestedNameSpecifier(NewVD, D);
6026 
6027     // If we have any template parameter lists that don't directly belong to
6028     // the variable (matching the scope specifier), store them.
6029     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6030     if (TemplateParamLists.size() > VDTemplateParamLists)
6031       NewVD->setTemplateParameterListsInfo(
6032           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6033 
6034     if (D.getDeclSpec().isConstexprSpecified())
6035       NewVD->setConstexpr(true);
6036 
6037     if (D.getDeclSpec().isConceptSpecified()) {
6038       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6039         VTD->setConcept();
6040 
6041       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6042       // be declared with the thread_local, inline, friend, or constexpr
6043       // specifiers, [...]
6044       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6045         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6046              diag::err_concept_decl_invalid_specifiers)
6047             << 0 << 0;
6048         NewVD->setInvalidDecl(true);
6049       }
6050 
6051       if (D.getDeclSpec().isConstexprSpecified()) {
6052         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6053              diag::err_concept_decl_invalid_specifiers)
6054             << 0 << 3;
6055         NewVD->setInvalidDecl(true);
6056       }
6057 
6058       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6059       // applied only to the definition of a function template or variable
6060       // template, declared in namespace scope.
6061       if (IsVariableTemplateSpecialization) {
6062         Diag(D.getDeclSpec().getConceptSpecLoc(),
6063              diag::err_concept_specified_specialization)
6064             << (IsPartialSpecialization ? 2 : 1);
6065       }
6066 
6067       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6068       // following restrictions:
6069       // - The declared type shall have the type bool.
6070       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6071           !NewVD->isInvalidDecl()) {
6072         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6073         NewVD->setInvalidDecl(true);
6074       }
6075     }
6076   }
6077 
6078   // Set the lexical context. If the declarator has a C++ scope specifier, the
6079   // lexical context will be different from the semantic context.
6080   NewVD->setLexicalDeclContext(CurContext);
6081   if (NewTemplate)
6082     NewTemplate->setLexicalDeclContext(CurContext);
6083 
6084   if (IsLocalExternDecl)
6085     NewVD->setLocalExternDecl();
6086 
6087   bool EmitTLSUnsupportedError = false;
6088   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6089     // C++11 [dcl.stc]p4:
6090     //   When thread_local is applied to a variable of block scope the
6091     //   storage-class-specifier static is implied if it does not appear
6092     //   explicitly.
6093     // Core issue: 'static' is not implied if the variable is declared
6094     //   'extern'.
6095     if (NewVD->hasLocalStorage() &&
6096         (SCSpec != DeclSpec::SCS_unspecified ||
6097          TSCS != DeclSpec::TSCS_thread_local ||
6098          !DC->isFunctionOrMethod()))
6099       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6100            diag::err_thread_non_global)
6101         << DeclSpec::getSpecifierName(TSCS);
6102     else if (!Context.getTargetInfo().isTLSSupported()) {
6103       if (getLangOpts().CUDA) {
6104         // Postpone error emission until we've collected attributes required to
6105         // figure out whether it's a host or device variable and whether the
6106         // error should be ignored.
6107         EmitTLSUnsupportedError = true;
6108         // We still need to mark the variable as TLS so it shows up in AST with
6109         // proper storage class for other tools to use even if we're not going
6110         // to emit any code for it.
6111         NewVD->setTSCSpec(TSCS);
6112       } else
6113         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6114              diag::err_thread_unsupported);
6115     } else
6116       NewVD->setTSCSpec(TSCS);
6117   }
6118 
6119   // C99 6.7.4p3
6120   //   An inline definition of a function with external linkage shall
6121   //   not contain a definition of a modifiable object with static or
6122   //   thread storage duration...
6123   // We only apply this when the function is required to be defined
6124   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6125   // that a local variable with thread storage duration still has to
6126   // be marked 'static'.  Also note that it's possible to get these
6127   // semantics in C++ using __attribute__((gnu_inline)).
6128   if (SC == SC_Static && S->getFnParent() != nullptr &&
6129       !NewVD->getType().isConstQualified()) {
6130     FunctionDecl *CurFD = getCurFunctionDecl();
6131     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6132       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6133            diag::warn_static_local_in_extern_inline);
6134       MaybeSuggestAddingStaticToDecl(CurFD);
6135     }
6136   }
6137 
6138   if (D.getDeclSpec().isModulePrivateSpecified()) {
6139     if (IsVariableTemplateSpecialization)
6140       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6141           << (IsPartialSpecialization ? 1 : 0)
6142           << FixItHint::CreateRemoval(
6143                  D.getDeclSpec().getModulePrivateSpecLoc());
6144     else if (IsExplicitSpecialization)
6145       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6146         << 2
6147         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6148     else if (NewVD->hasLocalStorage())
6149       Diag(NewVD->getLocation(), diag::err_module_private_local)
6150         << 0 << NewVD->getDeclName()
6151         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6152         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6153     else {
6154       NewVD->setModulePrivate();
6155       if (NewTemplate)
6156         NewTemplate->setModulePrivate();
6157     }
6158   }
6159 
6160   // Handle attributes prior to checking for duplicates in MergeVarDecl
6161   ProcessDeclAttributes(S, NewVD, D);
6162 
6163   if (getLangOpts().CUDA) {
6164     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6165       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6166            diag::err_thread_unsupported);
6167     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6168     // storage [duration]."
6169     if (SC == SC_None && S->getFnParent() != nullptr &&
6170         (NewVD->hasAttr<CUDASharedAttr>() ||
6171          NewVD->hasAttr<CUDAConstantAttr>())) {
6172       NewVD->setStorageClass(SC_Static);
6173     }
6174   }
6175 
6176   // Ensure that dllimport globals without explicit storage class are treated as
6177   // extern. The storage class is set above using parsed attributes. Now we can
6178   // check the VarDecl itself.
6179   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6180          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6181          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6182 
6183   // In auto-retain/release, infer strong retension for variables of
6184   // retainable type.
6185   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6186     NewVD->setInvalidDecl();
6187 
6188   // Handle GNU asm-label extension (encoded as an attribute).
6189   if (Expr *E = (Expr*)D.getAsmLabel()) {
6190     // The parser guarantees this is a string.
6191     StringLiteral *SE = cast<StringLiteral>(E);
6192     StringRef Label = SE->getString();
6193     if (S->getFnParent() != nullptr) {
6194       switch (SC) {
6195       case SC_None:
6196       case SC_Auto:
6197         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6198         break;
6199       case SC_Register:
6200         // Local Named register
6201         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6202             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6203           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6204         break;
6205       case SC_Static:
6206       case SC_Extern:
6207       case SC_PrivateExtern:
6208         break;
6209       }
6210     } else if (SC == SC_Register) {
6211       // Global Named register
6212       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6213         const auto &TI = Context.getTargetInfo();
6214         bool HasSizeMismatch;
6215 
6216         if (!TI.isValidGCCRegisterName(Label))
6217           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6218         else if (!TI.validateGlobalRegisterVariable(Label,
6219                                                     Context.getTypeSize(R),
6220                                                     HasSizeMismatch))
6221           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6222         else if (HasSizeMismatch)
6223           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6224       }
6225 
6226       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6227         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6228         NewVD->setInvalidDecl(true);
6229       }
6230     }
6231 
6232     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6233                                                 Context, Label, 0));
6234   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6235     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6236       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6237     if (I != ExtnameUndeclaredIdentifiers.end()) {
6238       if (isDeclExternC(NewVD)) {
6239         NewVD->addAttr(I->second);
6240         ExtnameUndeclaredIdentifiers.erase(I);
6241       } else
6242         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6243             << /*Variable*/1 << NewVD;
6244     }
6245   }
6246 
6247   // Diagnose shadowed variables before filtering for scope.
6248   if (D.getCXXScopeSpec().isEmpty())
6249     CheckShadow(S, NewVD, Previous);
6250 
6251   // Don't consider existing declarations that are in a different
6252   // scope and are out-of-semantic-context declarations (if the new
6253   // declaration has linkage).
6254   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6255                        D.getCXXScopeSpec().isNotEmpty() ||
6256                        IsExplicitSpecialization ||
6257                        IsVariableTemplateSpecialization);
6258 
6259   // Check whether the previous declaration is in the same block scope. This
6260   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6261   if (getLangOpts().CPlusPlus &&
6262       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6263     NewVD->setPreviousDeclInSameBlockScope(
6264         Previous.isSingleResult() && !Previous.isShadowed() &&
6265         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6266 
6267   if (!getLangOpts().CPlusPlus) {
6268     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6269   } else {
6270     // If this is an explicit specialization of a static data member, check it.
6271     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6272         CheckMemberSpecialization(NewVD, Previous))
6273       NewVD->setInvalidDecl();
6274 
6275     // Merge the decl with the existing one if appropriate.
6276     if (!Previous.empty()) {
6277       if (Previous.isSingleResult() &&
6278           isa<FieldDecl>(Previous.getFoundDecl()) &&
6279           D.getCXXScopeSpec().isSet()) {
6280         // The user tried to define a non-static data member
6281         // out-of-line (C++ [dcl.meaning]p1).
6282         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6283           << D.getCXXScopeSpec().getRange();
6284         Previous.clear();
6285         NewVD->setInvalidDecl();
6286       }
6287     } else if (D.getCXXScopeSpec().isSet()) {
6288       // No previous declaration in the qualifying scope.
6289       Diag(D.getIdentifierLoc(), diag::err_no_member)
6290         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6291         << D.getCXXScopeSpec().getRange();
6292       NewVD->setInvalidDecl();
6293     }
6294 
6295     if (!IsVariableTemplateSpecialization)
6296       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6297 
6298     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6299     // an explicit specialization (14.8.3) or a partial specialization of a
6300     // concept definition.
6301     if (IsVariableTemplateSpecialization &&
6302         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6303         Previous.isSingleResult()) {
6304       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6305       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6306         if (VarTmpl->isConcept()) {
6307           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6308               << 1                            /*variable*/
6309               << (IsPartialSpecialization ? 2 /*partially specialized*/
6310                                           : 1 /*explicitly specialized*/);
6311           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6312           NewVD->setInvalidDecl();
6313         }
6314       }
6315     }
6316 
6317     if (NewTemplate) {
6318       VarTemplateDecl *PrevVarTemplate =
6319           NewVD->getPreviousDecl()
6320               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6321               : nullptr;
6322 
6323       // Check the template parameter list of this declaration, possibly
6324       // merging in the template parameter list from the previous variable
6325       // template declaration.
6326       if (CheckTemplateParameterList(
6327               TemplateParams,
6328               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6329                               : nullptr,
6330               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6331                DC->isDependentContext())
6332                   ? TPC_ClassTemplateMember
6333                   : TPC_VarTemplate))
6334         NewVD->setInvalidDecl();
6335 
6336       // If we are providing an explicit specialization of a static variable
6337       // template, make a note of that.
6338       if (PrevVarTemplate &&
6339           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6340         PrevVarTemplate->setMemberSpecialization();
6341     }
6342   }
6343 
6344   ProcessPragmaWeak(S, NewVD);
6345 
6346   // If this is the first declaration of an extern C variable, update
6347   // the map of such variables.
6348   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6349       isIncompleteDeclExternC(*this, NewVD))
6350     RegisterLocallyScopedExternCDecl(NewVD, S);
6351 
6352   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6353     Decl *ManglingContextDecl;
6354     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6355             NewVD->getDeclContext(), ManglingContextDecl)) {
6356       Context.setManglingNumber(
6357           NewVD, MCtx->getManglingNumber(
6358                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6359       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6360     }
6361   }
6362 
6363   // Special handling of variable named 'main'.
6364   if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6365       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6366       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6367 
6368     // C++ [basic.start.main]p3
6369     // A program that declares a variable main at global scope is ill-formed.
6370     if (getLangOpts().CPlusPlus)
6371       Diag(D.getLocStart(), diag::err_main_global_variable);
6372 
6373     // In C, and external-linkage variable named main results in undefined
6374     // behavior.
6375     else if (NewVD->hasExternalFormalLinkage())
6376       Diag(D.getLocStart(), diag::warn_main_redefined);
6377   }
6378 
6379   if (D.isRedeclaration() && !Previous.empty()) {
6380     checkDLLAttributeRedeclaration(
6381         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6382         IsExplicitSpecialization);
6383   }
6384 
6385   if (NewTemplate) {
6386     if (NewVD->isInvalidDecl())
6387       NewTemplate->setInvalidDecl();
6388     ActOnDocumentableDecl(NewTemplate);
6389     return NewTemplate;
6390   }
6391 
6392   return NewVD;
6393 }
6394 
6395 /// Enum describing the %select options in diag::warn_decl_shadow.
6396 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
6397 
6398 /// Determine what kind of declaration we're shadowing.
6399 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6400                                                 const DeclContext *OldDC) {
6401   if (isa<RecordDecl>(OldDC))
6402     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6403   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6404 }
6405 
6406 /// \brief Diagnose variable or built-in function shadowing.  Implements
6407 /// -Wshadow.
6408 ///
6409 /// This method is called whenever a VarDecl is added to a "useful"
6410 /// scope.
6411 ///
6412 /// \param S the scope in which the shadowing name is being declared
6413 /// \param R the lookup of the name
6414 ///
6415 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6416   // Return if warning is ignored.
6417   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6418     return;
6419 
6420   // Don't diagnose declarations at file scope.
6421   if (D->hasGlobalStorage())
6422     return;
6423 
6424   DeclContext *NewDC = D->getDeclContext();
6425 
6426   // Only diagnose if we're shadowing an unambiguous field or variable.
6427   if (R.getResultKind() != LookupResult::Found)
6428     return;
6429 
6430   NamedDecl* ShadowedDecl = R.getFoundDecl();
6431   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6432     return;
6433 
6434   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6435     // Fields are not shadowed by variables in C++ static methods.
6436     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6437       if (MD->isStatic())
6438         return;
6439 
6440     // Fields shadowed by constructor parameters are a special case. Usually
6441     // the constructor initializes the field with the parameter.
6442     if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
6443       // Remember that this was shadowed so we can either warn about its
6444       // modification or its existence depending on warning settings.
6445       D = D->getCanonicalDecl();
6446       ShadowingDecls.insert({D, FD});
6447       return;
6448     }
6449   }
6450 
6451   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6452     if (shadowedVar->isExternC()) {
6453       // For shadowing external vars, make sure that we point to the global
6454       // declaration, not a locally scoped extern declaration.
6455       for (auto I : shadowedVar->redecls())
6456         if (I->isFileVarDecl()) {
6457           ShadowedDecl = I;
6458           break;
6459         }
6460     }
6461 
6462   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6463 
6464   // Only warn about certain kinds of shadowing for class members.
6465   if (NewDC && NewDC->isRecord()) {
6466     // In particular, don't warn about shadowing non-class members.
6467     if (!OldDC->isRecord())
6468       return;
6469 
6470     // TODO: should we warn about static data members shadowing
6471     // static data members from base classes?
6472 
6473     // TODO: don't diagnose for inaccessible shadowed members.
6474     // This is hard to do perfectly because we might friend the
6475     // shadowing context, but that's just a false negative.
6476   }
6477 
6478 
6479   DeclarationName Name = R.getLookupName();
6480 
6481   // Emit warning and note.
6482   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6483     return;
6484   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6485   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6486   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6487 }
6488 
6489 /// \brief Check -Wshadow without the advantage of a previous lookup.
6490 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6491   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6492     return;
6493 
6494   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6495                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6496   LookupName(R, S);
6497   CheckShadow(S, D, R);
6498 }
6499 
6500 /// Check if 'E', which is an expression that is about to be modified, refers
6501 /// to a constructor parameter that shadows a field.
6502 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6503   // Quickly ignore expressions that can't be shadowing ctor parameters.
6504   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6505     return;
6506   E = E->IgnoreParenImpCasts();
6507   auto *DRE = dyn_cast<DeclRefExpr>(E);
6508   if (!DRE)
6509     return;
6510   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6511   auto I = ShadowingDecls.find(D);
6512   if (I == ShadowingDecls.end())
6513     return;
6514   const NamedDecl *ShadowedDecl = I->second;
6515   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6516   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6517   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6518   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6519 
6520   // Avoid issuing multiple warnings about the same decl.
6521   ShadowingDecls.erase(I);
6522 }
6523 
6524 /// Check for conflict between this global or extern "C" declaration and
6525 /// previous global or extern "C" declarations. This is only used in C++.
6526 template<typename T>
6527 static bool checkGlobalOrExternCConflict(
6528     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6529   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6530   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6531 
6532   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6533     // The common case: this global doesn't conflict with any extern "C"
6534     // declaration.
6535     return false;
6536   }
6537 
6538   if (Prev) {
6539     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6540       // Both the old and new declarations have C language linkage. This is a
6541       // redeclaration.
6542       Previous.clear();
6543       Previous.addDecl(Prev);
6544       return true;
6545     }
6546 
6547     // This is a global, non-extern "C" declaration, and there is a previous
6548     // non-global extern "C" declaration. Diagnose if this is a variable
6549     // declaration.
6550     if (!isa<VarDecl>(ND))
6551       return false;
6552   } else {
6553     // The declaration is extern "C". Check for any declaration in the
6554     // translation unit which might conflict.
6555     if (IsGlobal) {
6556       // We have already performed the lookup into the translation unit.
6557       IsGlobal = false;
6558       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6559            I != E; ++I) {
6560         if (isa<VarDecl>(*I)) {
6561           Prev = *I;
6562           break;
6563         }
6564       }
6565     } else {
6566       DeclContext::lookup_result R =
6567           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6568       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6569            I != E; ++I) {
6570         if (isa<VarDecl>(*I)) {
6571           Prev = *I;
6572           break;
6573         }
6574         // FIXME: If we have any other entity with this name in global scope,
6575         // the declaration is ill-formed, but that is a defect: it breaks the
6576         // 'stat' hack, for instance. Only variables can have mangled name
6577         // clashes with extern "C" declarations, so only they deserve a
6578         // diagnostic.
6579       }
6580     }
6581 
6582     if (!Prev)
6583       return false;
6584   }
6585 
6586   // Use the first declaration's location to ensure we point at something which
6587   // is lexically inside an extern "C" linkage-spec.
6588   assert(Prev && "should have found a previous declaration to diagnose");
6589   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6590     Prev = FD->getFirstDecl();
6591   else
6592     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6593 
6594   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6595     << IsGlobal << ND;
6596   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6597     << IsGlobal;
6598   return false;
6599 }
6600 
6601 /// Apply special rules for handling extern "C" declarations. Returns \c true
6602 /// if we have found that this is a redeclaration of some prior entity.
6603 ///
6604 /// Per C++ [dcl.link]p6:
6605 ///   Two declarations [for a function or variable] with C language linkage
6606 ///   with the same name that appear in different scopes refer to the same
6607 ///   [entity]. An entity with C language linkage shall not be declared with
6608 ///   the same name as an entity in global scope.
6609 template<typename T>
6610 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6611                                                   LookupResult &Previous) {
6612   if (!S.getLangOpts().CPlusPlus) {
6613     // In C, when declaring a global variable, look for a corresponding 'extern'
6614     // variable declared in function scope. We don't need this in C++, because
6615     // we find local extern decls in the surrounding file-scope DeclContext.
6616     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6617       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6618         Previous.clear();
6619         Previous.addDecl(Prev);
6620         return true;
6621       }
6622     }
6623     return false;
6624   }
6625 
6626   // A declaration in the translation unit can conflict with an extern "C"
6627   // declaration.
6628   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6629     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6630 
6631   // An extern "C" declaration can conflict with a declaration in the
6632   // translation unit or can be a redeclaration of an extern "C" declaration
6633   // in another scope.
6634   if (isIncompleteDeclExternC(S,ND))
6635     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6636 
6637   // Neither global nor extern "C": nothing to do.
6638   return false;
6639 }
6640 
6641 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6642   // If the decl is already known invalid, don't check it.
6643   if (NewVD->isInvalidDecl())
6644     return;
6645 
6646   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6647   QualType T = TInfo->getType();
6648 
6649   // Defer checking an 'auto' type until its initializer is attached.
6650   if (T->isUndeducedType())
6651     return;
6652 
6653   if (NewVD->hasAttrs())
6654     CheckAlignasUnderalignment(NewVD);
6655 
6656   if (T->isObjCObjectType()) {
6657     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6658       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6659     T = Context.getObjCObjectPointerType(T);
6660     NewVD->setType(T);
6661   }
6662 
6663   // Emit an error if an address space was applied to decl with local storage.
6664   // This includes arrays of objects with address space qualifiers, but not
6665   // automatic variables that point to other address spaces.
6666   // ISO/IEC TR 18037 S5.1.2
6667   if (!getLangOpts().OpenCL
6668       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6669     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6670     NewVD->setInvalidDecl();
6671     return;
6672   }
6673 
6674   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
6675   // scope.
6676   if (getLangOpts().OpenCLVersion == 120 &&
6677       !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6678       NewVD->isStaticLocal()) {
6679     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6680     NewVD->setInvalidDecl();
6681     return;
6682   }
6683 
6684   if (getLangOpts().OpenCL) {
6685     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
6686     if (NewVD->hasAttr<BlocksAttr>()) {
6687       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
6688       return;
6689     }
6690 
6691     if (T->isBlockPointerType()) {
6692       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
6693       // can't use 'extern' storage class.
6694       if (!T.isConstQualified()) {
6695         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
6696             << 0 /*const*/;
6697         NewVD->setInvalidDecl();
6698         return;
6699       }
6700       if (NewVD->hasExternalStorage()) {
6701         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
6702         NewVD->setInvalidDecl();
6703         return;
6704       }
6705       // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported.
6706       // TODO: this check is not enough as it doesn't diagnose the typedef
6707       const BlockPointerType *BlkTy = T->getAs<BlockPointerType>();
6708       const FunctionProtoType *FTy =
6709           BlkTy->getPointeeType()->getAs<FunctionProtoType>();
6710       if (FTy && FTy->isVariadic()) {
6711         Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic)
6712             << T << NewVD->getSourceRange();
6713         NewVD->setInvalidDecl();
6714         return;
6715       }
6716     }
6717     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6718     // __constant address space.
6719     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6720     // variables inside a function can also be declared in the global
6721     // address space.
6722     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
6723         NewVD->hasExternalStorage()) {
6724       if (!T->isSamplerT() &&
6725           !(T.getAddressSpace() == LangAS::opencl_constant ||
6726             (T.getAddressSpace() == LangAS::opencl_global &&
6727              getLangOpts().OpenCLVersion == 200))) {
6728         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
6729         if (getLangOpts().OpenCLVersion == 200)
6730           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6731               << Scope << "global or constant";
6732         else
6733           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6734               << Scope << "constant";
6735         NewVD->setInvalidDecl();
6736         return;
6737       }
6738     } else {
6739       if (T.getAddressSpace() == LangAS::opencl_global) {
6740         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6741             << 1 /*is any function*/ << "global";
6742         NewVD->setInvalidDecl();
6743         return;
6744       }
6745       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6746       // in functions.
6747       if (T.getAddressSpace() == LangAS::opencl_constant ||
6748           T.getAddressSpace() == LangAS::opencl_local) {
6749         FunctionDecl *FD = getCurFunctionDecl();
6750         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6751           if (T.getAddressSpace() == LangAS::opencl_constant)
6752             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6753                 << 0 /*non-kernel only*/ << "constant";
6754           else
6755             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6756                 << 0 /*non-kernel only*/ << "local";
6757           NewVD->setInvalidDecl();
6758           return;
6759         }
6760       }
6761     }
6762   }
6763 
6764   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6765       && !NewVD->hasAttr<BlocksAttr>()) {
6766     if (getLangOpts().getGC() != LangOptions::NonGC)
6767       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6768     else {
6769       assert(!getLangOpts().ObjCAutoRefCount);
6770       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6771     }
6772   }
6773 
6774   bool isVM = T->isVariablyModifiedType();
6775   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6776       NewVD->hasAttr<BlocksAttr>())
6777     getCurFunction()->setHasBranchProtectedScope();
6778 
6779   if ((isVM && NewVD->hasLinkage()) ||
6780       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6781     bool SizeIsNegative;
6782     llvm::APSInt Oversized;
6783     TypeSourceInfo *FixedTInfo =
6784       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6785                                                     SizeIsNegative, Oversized);
6786     if (!FixedTInfo && T->isVariableArrayType()) {
6787       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6788       // FIXME: This won't give the correct result for
6789       // int a[10][n];
6790       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6791 
6792       if (NewVD->isFileVarDecl())
6793         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6794         << SizeRange;
6795       else if (NewVD->isStaticLocal())
6796         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6797         << SizeRange;
6798       else
6799         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6800         << SizeRange;
6801       NewVD->setInvalidDecl();
6802       return;
6803     }
6804 
6805     if (!FixedTInfo) {
6806       if (NewVD->isFileVarDecl())
6807         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6808       else
6809         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6810       NewVD->setInvalidDecl();
6811       return;
6812     }
6813 
6814     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6815     NewVD->setType(FixedTInfo->getType());
6816     NewVD->setTypeSourceInfo(FixedTInfo);
6817   }
6818 
6819   if (T->isVoidType()) {
6820     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6821     //                    of objects and functions.
6822     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6823       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6824         << T;
6825       NewVD->setInvalidDecl();
6826       return;
6827     }
6828   }
6829 
6830   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6831     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6832     NewVD->setInvalidDecl();
6833     return;
6834   }
6835 
6836   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6837     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6838     NewVD->setInvalidDecl();
6839     return;
6840   }
6841 
6842   if (NewVD->isConstexpr() && !T->isDependentType() &&
6843       RequireLiteralType(NewVD->getLocation(), T,
6844                          diag::err_constexpr_var_non_literal)) {
6845     NewVD->setInvalidDecl();
6846     return;
6847   }
6848 }
6849 
6850 /// \brief Perform semantic checking on a newly-created variable
6851 /// declaration.
6852 ///
6853 /// This routine performs all of the type-checking required for a
6854 /// variable declaration once it has been built. It is used both to
6855 /// check variables after they have been parsed and their declarators
6856 /// have been translated into a declaration, and to check variables
6857 /// that have been instantiated from a template.
6858 ///
6859 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6860 ///
6861 /// Returns true if the variable declaration is a redeclaration.
6862 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6863   CheckVariableDeclarationType(NewVD);
6864 
6865   // If the decl is already known invalid, don't check it.
6866   if (NewVD->isInvalidDecl())
6867     return false;
6868 
6869   // If we did not find anything by this name, look for a non-visible
6870   // extern "C" declaration with the same name.
6871   if (Previous.empty() &&
6872       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6873     Previous.setShadowed();
6874 
6875   if (!Previous.empty()) {
6876     MergeVarDecl(NewVD, Previous);
6877     return true;
6878   }
6879   return false;
6880 }
6881 
6882 namespace {
6883 struct FindOverriddenMethod {
6884   Sema *S;
6885   CXXMethodDecl *Method;
6886 
6887   /// Member lookup function that determines whether a given C++
6888   /// method overrides a method in a base class, to be used with
6889   /// CXXRecordDecl::lookupInBases().
6890   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6891     RecordDecl *BaseRecord =
6892         Specifier->getType()->getAs<RecordType>()->getDecl();
6893 
6894     DeclarationName Name = Method->getDeclName();
6895 
6896     // FIXME: Do we care about other names here too?
6897     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6898       // We really want to find the base class destructor here.
6899       QualType T = S->Context.getTypeDeclType(BaseRecord);
6900       CanQualType CT = S->Context.getCanonicalType(T);
6901 
6902       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
6903     }
6904 
6905     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6906          Path.Decls = Path.Decls.slice(1)) {
6907       NamedDecl *D = Path.Decls.front();
6908       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6909         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
6910           return true;
6911       }
6912     }
6913 
6914     return false;
6915   }
6916 };
6917 
6918 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6919 } // end anonymous namespace
6920 
6921 /// \brief Report an error regarding overriding, along with any relevant
6922 /// overriden methods.
6923 ///
6924 /// \param DiagID the primary error to report.
6925 /// \param MD the overriding method.
6926 /// \param OEK which overrides to include as notes.
6927 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6928                             OverrideErrorKind OEK = OEK_All) {
6929   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6930   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6931                                       E = MD->end_overridden_methods();
6932        I != E; ++I) {
6933     // This check (& the OEK parameter) could be replaced by a predicate, but
6934     // without lambdas that would be overkill. This is still nicer than writing
6935     // out the diag loop 3 times.
6936     if ((OEK == OEK_All) ||
6937         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6938         (OEK == OEK_Deleted && (*I)->isDeleted()))
6939       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6940   }
6941 }
6942 
6943 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6944 /// and if so, check that it's a valid override and remember it.
6945 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6946   // Look for methods in base classes that this method might override.
6947   CXXBasePaths Paths;
6948   FindOverriddenMethod FOM;
6949   FOM.Method = MD;
6950   FOM.S = this;
6951   bool hasDeletedOverridenMethods = false;
6952   bool hasNonDeletedOverridenMethods = false;
6953   bool AddedAny = false;
6954   if (DC->lookupInBases(FOM, Paths)) {
6955     for (auto *I : Paths.found_decls()) {
6956       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6957         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6958         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6959             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6960             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6961             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6962           hasDeletedOverridenMethods |= OldMD->isDeleted();
6963           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6964           AddedAny = true;
6965         }
6966       }
6967     }
6968   }
6969 
6970   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6971     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6972   }
6973   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6974     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6975   }
6976 
6977   return AddedAny;
6978 }
6979 
6980 namespace {
6981   // Struct for holding all of the extra arguments needed by
6982   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6983   struct ActOnFDArgs {
6984     Scope *S;
6985     Declarator &D;
6986     MultiTemplateParamsArg TemplateParamLists;
6987     bool AddToScope;
6988   };
6989 } // end anonymous namespace
6990 
6991 namespace {
6992 
6993 // Callback to only accept typo corrections that have a non-zero edit distance.
6994 // Also only accept corrections that have the same parent decl.
6995 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6996  public:
6997   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6998                             CXXRecordDecl *Parent)
6999       : Context(Context), OriginalFD(TypoFD),
7000         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7001 
7002   bool ValidateCandidate(const TypoCorrection &candidate) override {
7003     if (candidate.getEditDistance() == 0)
7004       return false;
7005 
7006     SmallVector<unsigned, 1> MismatchedParams;
7007     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7008                                           CDeclEnd = candidate.end();
7009          CDecl != CDeclEnd; ++CDecl) {
7010       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7011 
7012       if (FD && !FD->hasBody() &&
7013           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7014         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7015           CXXRecordDecl *Parent = MD->getParent();
7016           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7017             return true;
7018         } else if (!ExpectedParent) {
7019           return true;
7020         }
7021       }
7022     }
7023 
7024     return false;
7025   }
7026 
7027  private:
7028   ASTContext &Context;
7029   FunctionDecl *OriginalFD;
7030   CXXRecordDecl *ExpectedParent;
7031 };
7032 
7033 } // end anonymous namespace
7034 
7035 /// \brief Generate diagnostics for an invalid function redeclaration.
7036 ///
7037 /// This routine handles generating the diagnostic messages for an invalid
7038 /// function redeclaration, including finding possible similar declarations
7039 /// or performing typo correction if there are no previous declarations with
7040 /// the same name.
7041 ///
7042 /// Returns a NamedDecl iff typo correction was performed and substituting in
7043 /// the new declaration name does not cause new errors.
7044 static NamedDecl *DiagnoseInvalidRedeclaration(
7045     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7046     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7047   DeclarationName Name = NewFD->getDeclName();
7048   DeclContext *NewDC = NewFD->getDeclContext();
7049   SmallVector<unsigned, 1> MismatchedParams;
7050   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7051   TypoCorrection Correction;
7052   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7053   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7054                                    : diag::err_member_decl_does_not_match;
7055   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7056                     IsLocalFriend ? Sema::LookupLocalFriendName
7057                                   : Sema::LookupOrdinaryName,
7058                     Sema::ForRedeclaration);
7059 
7060   NewFD->setInvalidDecl();
7061   if (IsLocalFriend)
7062     SemaRef.LookupName(Prev, S);
7063   else
7064     SemaRef.LookupQualifiedName(Prev, NewDC);
7065   assert(!Prev.isAmbiguous() &&
7066          "Cannot have an ambiguity in previous-declaration lookup");
7067   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7068   if (!Prev.empty()) {
7069     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7070          Func != FuncEnd; ++Func) {
7071       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7072       if (FD &&
7073           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7074         // Add 1 to the index so that 0 can mean the mismatch didn't
7075         // involve a parameter
7076         unsigned ParamNum =
7077             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7078         NearMatches.push_back(std::make_pair(FD, ParamNum));
7079       }
7080     }
7081   // If the qualified name lookup yielded nothing, try typo correction
7082   } else if ((Correction = SemaRef.CorrectTypo(
7083                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7084                   &ExtraArgs.D.getCXXScopeSpec(),
7085                   llvm::make_unique<DifferentNameValidatorCCC>(
7086                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7087                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7088     // Set up everything for the call to ActOnFunctionDeclarator
7089     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7090                               ExtraArgs.D.getIdentifierLoc());
7091     Previous.clear();
7092     Previous.setLookupName(Correction.getCorrection());
7093     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7094                                     CDeclEnd = Correction.end();
7095          CDecl != CDeclEnd; ++CDecl) {
7096       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7097       if (FD && !FD->hasBody() &&
7098           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7099         Previous.addDecl(FD);
7100       }
7101     }
7102     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7103 
7104     NamedDecl *Result;
7105     // Retry building the function declaration with the new previous
7106     // declarations, and with errors suppressed.
7107     {
7108       // Trap errors.
7109       Sema::SFINAETrap Trap(SemaRef);
7110 
7111       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7112       // pieces need to verify the typo-corrected C++ declaration and hopefully
7113       // eliminate the need for the parameter pack ExtraArgs.
7114       Result = SemaRef.ActOnFunctionDeclarator(
7115           ExtraArgs.S, ExtraArgs.D,
7116           Correction.getCorrectionDecl()->getDeclContext(),
7117           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7118           ExtraArgs.AddToScope);
7119 
7120       if (Trap.hasErrorOccurred())
7121         Result = nullptr;
7122     }
7123 
7124     if (Result) {
7125       // Determine which correction we picked.
7126       Decl *Canonical = Result->getCanonicalDecl();
7127       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7128            I != E; ++I)
7129         if ((*I)->getCanonicalDecl() == Canonical)
7130           Correction.setCorrectionDecl(*I);
7131 
7132       SemaRef.diagnoseTypo(
7133           Correction,
7134           SemaRef.PDiag(IsLocalFriend
7135                           ? diag::err_no_matching_local_friend_suggest
7136                           : diag::err_member_decl_does_not_match_suggest)
7137             << Name << NewDC << IsDefinition);
7138       return Result;
7139     }
7140 
7141     // Pretend the typo correction never occurred
7142     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7143                               ExtraArgs.D.getIdentifierLoc());
7144     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7145     Previous.clear();
7146     Previous.setLookupName(Name);
7147   }
7148 
7149   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7150       << Name << NewDC << IsDefinition << NewFD->getLocation();
7151 
7152   bool NewFDisConst = false;
7153   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7154     NewFDisConst = NewMD->isConst();
7155 
7156   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7157        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7158        NearMatch != NearMatchEnd; ++NearMatch) {
7159     FunctionDecl *FD = NearMatch->first;
7160     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7161     bool FDisConst = MD && MD->isConst();
7162     bool IsMember = MD || !IsLocalFriend;
7163 
7164     // FIXME: These notes are poorly worded for the local friend case.
7165     if (unsigned Idx = NearMatch->second) {
7166       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7167       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7168       if (Loc.isInvalid()) Loc = FD->getLocation();
7169       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7170                                  : diag::note_local_decl_close_param_match)
7171         << Idx << FDParam->getType()
7172         << NewFD->getParamDecl(Idx - 1)->getType();
7173     } else if (FDisConst != NewFDisConst) {
7174       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7175           << NewFDisConst << FD->getSourceRange().getEnd();
7176     } else
7177       SemaRef.Diag(FD->getLocation(),
7178                    IsMember ? diag::note_member_def_close_match
7179                             : diag::note_local_decl_close_match);
7180   }
7181   return nullptr;
7182 }
7183 
7184 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7185   switch (D.getDeclSpec().getStorageClassSpec()) {
7186   default: llvm_unreachable("Unknown storage class!");
7187   case DeclSpec::SCS_auto:
7188   case DeclSpec::SCS_register:
7189   case DeclSpec::SCS_mutable:
7190     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7191                  diag::err_typecheck_sclass_func);
7192     D.setInvalidType();
7193     break;
7194   case DeclSpec::SCS_unspecified: break;
7195   case DeclSpec::SCS_extern:
7196     if (D.getDeclSpec().isExternInLinkageSpec())
7197       return SC_None;
7198     return SC_Extern;
7199   case DeclSpec::SCS_static: {
7200     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7201       // C99 6.7.1p5:
7202       //   The declaration of an identifier for a function that has
7203       //   block scope shall have no explicit storage-class specifier
7204       //   other than extern
7205       // See also (C++ [dcl.stc]p4).
7206       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7207                    diag::err_static_block_func);
7208       break;
7209     } else
7210       return SC_Static;
7211   }
7212   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7213   }
7214 
7215   // No explicit storage class has already been returned
7216   return SC_None;
7217 }
7218 
7219 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7220                                            DeclContext *DC, QualType &R,
7221                                            TypeSourceInfo *TInfo,
7222                                            StorageClass SC,
7223                                            bool &IsVirtualOkay) {
7224   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7225   DeclarationName Name = NameInfo.getName();
7226 
7227   FunctionDecl *NewFD = nullptr;
7228   bool isInline = D.getDeclSpec().isInlineSpecified();
7229 
7230   if (!SemaRef.getLangOpts().CPlusPlus) {
7231     // Determine whether the function was written with a
7232     // prototype. This true when:
7233     //   - there is a prototype in the declarator, or
7234     //   - the type R of the function is some kind of typedef or other reference
7235     //     to a type name (which eventually refers to a function type).
7236     bool HasPrototype =
7237       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7238       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7239 
7240     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7241                                  D.getLocStart(), NameInfo, R,
7242                                  TInfo, SC, isInline,
7243                                  HasPrototype, false);
7244     if (D.isInvalidType())
7245       NewFD->setInvalidDecl();
7246 
7247     return NewFD;
7248   }
7249 
7250   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7251   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7252 
7253   // Check that the return type is not an abstract class type.
7254   // For record types, this is done by the AbstractClassUsageDiagnoser once
7255   // the class has been completely parsed.
7256   if (!DC->isRecord() &&
7257       SemaRef.RequireNonAbstractType(
7258           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7259           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7260     D.setInvalidType();
7261 
7262   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7263     // This is a C++ constructor declaration.
7264     assert(DC->isRecord() &&
7265            "Constructors can only be declared in a member context");
7266 
7267     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7268     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7269                                       D.getLocStart(), NameInfo,
7270                                       R, TInfo, isExplicit, isInline,
7271                                       /*isImplicitlyDeclared=*/false,
7272                                       isConstexpr);
7273 
7274   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7275     // This is a C++ destructor declaration.
7276     if (DC->isRecord()) {
7277       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7278       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7279       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7280                                         SemaRef.Context, Record,
7281                                         D.getLocStart(),
7282                                         NameInfo, R, TInfo, isInline,
7283                                         /*isImplicitlyDeclared=*/false);
7284 
7285       // If the class is complete, then we now create the implicit exception
7286       // specification. If the class is incomplete or dependent, we can't do
7287       // it yet.
7288       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7289           Record->getDefinition() && !Record->isBeingDefined() &&
7290           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7291         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7292       }
7293 
7294       IsVirtualOkay = true;
7295       return NewDD;
7296 
7297     } else {
7298       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7299       D.setInvalidType();
7300 
7301       // Create a FunctionDecl to satisfy the function definition parsing
7302       // code path.
7303       return FunctionDecl::Create(SemaRef.Context, DC,
7304                                   D.getLocStart(),
7305                                   D.getIdentifierLoc(), Name, R, TInfo,
7306                                   SC, isInline,
7307                                   /*hasPrototype=*/true, isConstexpr);
7308     }
7309 
7310   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7311     if (!DC->isRecord()) {
7312       SemaRef.Diag(D.getIdentifierLoc(),
7313            diag::err_conv_function_not_member);
7314       return nullptr;
7315     }
7316 
7317     SemaRef.CheckConversionDeclarator(D, R, SC);
7318     IsVirtualOkay = true;
7319     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7320                                      D.getLocStart(), NameInfo,
7321                                      R, TInfo, isInline, isExplicit,
7322                                      isConstexpr, SourceLocation());
7323 
7324   } else if (DC->isRecord()) {
7325     // If the name of the function is the same as the name of the record,
7326     // then this must be an invalid constructor that has a return type.
7327     // (The parser checks for a return type and makes the declarator a
7328     // constructor if it has no return type).
7329     if (Name.getAsIdentifierInfo() &&
7330         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7331       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7332         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7333         << SourceRange(D.getIdentifierLoc());
7334       return nullptr;
7335     }
7336 
7337     // This is a C++ method declaration.
7338     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7339                                                cast<CXXRecordDecl>(DC),
7340                                                D.getLocStart(), NameInfo, R,
7341                                                TInfo, SC, isInline,
7342                                                isConstexpr, SourceLocation());
7343     IsVirtualOkay = !Ret->isStatic();
7344     return Ret;
7345   } else {
7346     bool isFriend =
7347         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7348     if (!isFriend && SemaRef.CurContext->isRecord())
7349       return nullptr;
7350 
7351     // Determine whether the function was written with a
7352     // prototype. This true when:
7353     //   - we're in C++ (where every function has a prototype),
7354     return FunctionDecl::Create(SemaRef.Context, DC,
7355                                 D.getLocStart(),
7356                                 NameInfo, R, TInfo, SC, isInline,
7357                                 true/*HasPrototype*/, isConstexpr);
7358   }
7359 }
7360 
7361 enum OpenCLParamType {
7362   ValidKernelParam,
7363   PtrPtrKernelParam,
7364   PtrKernelParam,
7365   PrivatePtrKernelParam,
7366   InvalidKernelParam,
7367   RecordKernelParam
7368 };
7369 
7370 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7371   if (PT->isPointerType()) {
7372     QualType PointeeType = PT->getPointeeType();
7373     if (PointeeType->isPointerType())
7374       return PtrPtrKernelParam;
7375     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7376                                               : PtrKernelParam;
7377   }
7378 
7379   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7380   // be used as builtin types.
7381 
7382   if (PT->isImageType())
7383     return PtrKernelParam;
7384 
7385   if (PT->isBooleanType())
7386     return InvalidKernelParam;
7387 
7388   if (PT->isEventT())
7389     return InvalidKernelParam;
7390 
7391   if (PT->isHalfType())
7392     return InvalidKernelParam;
7393 
7394   if (PT->isRecordType())
7395     return RecordKernelParam;
7396 
7397   return ValidKernelParam;
7398 }
7399 
7400 static void checkIsValidOpenCLKernelParameter(
7401   Sema &S,
7402   Declarator &D,
7403   ParmVarDecl *Param,
7404   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7405   QualType PT = Param->getType();
7406 
7407   // Cache the valid types we encounter to avoid rechecking structs that are
7408   // used again
7409   if (ValidTypes.count(PT.getTypePtr()))
7410     return;
7411 
7412   switch (getOpenCLKernelParameterType(PT)) {
7413   case PtrPtrKernelParam:
7414     // OpenCL v1.2 s6.9.a:
7415     // A kernel function argument cannot be declared as a
7416     // pointer to a pointer type.
7417     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7418     D.setInvalidType();
7419     return;
7420 
7421   case PrivatePtrKernelParam:
7422     // OpenCL v1.2 s6.9.a:
7423     // A kernel function argument cannot be declared as a
7424     // pointer to the private address space.
7425     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7426     D.setInvalidType();
7427     return;
7428 
7429     // OpenCL v1.2 s6.9.k:
7430     // Arguments to kernel functions in a program cannot be declared with the
7431     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7432     // uintptr_t or a struct and/or union that contain fields declared to be
7433     // one of these built-in scalar types.
7434 
7435   case InvalidKernelParam:
7436     // OpenCL v1.2 s6.8 n:
7437     // A kernel function argument cannot be declared
7438     // of event_t type.
7439     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7440     D.setInvalidType();
7441     return;
7442 
7443   case PtrKernelParam:
7444   case ValidKernelParam:
7445     ValidTypes.insert(PT.getTypePtr());
7446     return;
7447 
7448   case RecordKernelParam:
7449     break;
7450   }
7451 
7452   // Track nested structs we will inspect
7453   SmallVector<const Decl *, 4> VisitStack;
7454 
7455   // Track where we are in the nested structs. Items will migrate from
7456   // VisitStack to HistoryStack as we do the DFS for bad field.
7457   SmallVector<const FieldDecl *, 4> HistoryStack;
7458   HistoryStack.push_back(nullptr);
7459 
7460   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7461   VisitStack.push_back(PD);
7462 
7463   assert(VisitStack.back() && "First decl null?");
7464 
7465   do {
7466     const Decl *Next = VisitStack.pop_back_val();
7467     if (!Next) {
7468       assert(!HistoryStack.empty());
7469       // Found a marker, we have gone up a level
7470       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7471         ValidTypes.insert(Hist->getType().getTypePtr());
7472 
7473       continue;
7474     }
7475 
7476     // Adds everything except the original parameter declaration (which is not a
7477     // field itself) to the history stack.
7478     const RecordDecl *RD;
7479     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7480       HistoryStack.push_back(Field);
7481       RD = Field->getType()->castAs<RecordType>()->getDecl();
7482     } else {
7483       RD = cast<RecordDecl>(Next);
7484     }
7485 
7486     // Add a null marker so we know when we've gone back up a level
7487     VisitStack.push_back(nullptr);
7488 
7489     for (const auto *FD : RD->fields()) {
7490       QualType QT = FD->getType();
7491 
7492       if (ValidTypes.count(QT.getTypePtr()))
7493         continue;
7494 
7495       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7496       if (ParamType == ValidKernelParam)
7497         continue;
7498 
7499       if (ParamType == RecordKernelParam) {
7500         VisitStack.push_back(FD);
7501         continue;
7502       }
7503 
7504       // OpenCL v1.2 s6.9.p:
7505       // Arguments to kernel functions that are declared to be a struct or union
7506       // do not allow OpenCL objects to be passed as elements of the struct or
7507       // union.
7508       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7509           ParamType == PrivatePtrKernelParam) {
7510         S.Diag(Param->getLocation(),
7511                diag::err_record_with_pointers_kernel_param)
7512           << PT->isUnionType()
7513           << PT;
7514       } else {
7515         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7516       }
7517 
7518       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7519         << PD->getDeclName();
7520 
7521       // We have an error, now let's go back up through history and show where
7522       // the offending field came from
7523       for (ArrayRef<const FieldDecl *>::const_iterator
7524                I = HistoryStack.begin() + 1,
7525                E = HistoryStack.end();
7526            I != E; ++I) {
7527         const FieldDecl *OuterField = *I;
7528         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7529           << OuterField->getType();
7530       }
7531 
7532       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7533         << QT->isPointerType()
7534         << QT;
7535       D.setInvalidType();
7536       return;
7537     }
7538   } while (!VisitStack.empty());
7539 }
7540 
7541 NamedDecl*
7542 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7543                               TypeSourceInfo *TInfo, LookupResult &Previous,
7544                               MultiTemplateParamsArg TemplateParamLists,
7545                               bool &AddToScope) {
7546   QualType R = TInfo->getType();
7547 
7548   assert(R.getTypePtr()->isFunctionType());
7549 
7550   // TODO: consider using NameInfo for diagnostic.
7551   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7552   DeclarationName Name = NameInfo.getName();
7553   StorageClass SC = getFunctionStorageClass(*this, D);
7554 
7555   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7556     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7557          diag::err_invalid_thread)
7558       << DeclSpec::getSpecifierName(TSCS);
7559 
7560   if (D.isFirstDeclarationOfMember())
7561     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7562                            D.getIdentifierLoc());
7563 
7564   bool isFriend = false;
7565   FunctionTemplateDecl *FunctionTemplate = nullptr;
7566   bool isExplicitSpecialization = false;
7567   bool isFunctionTemplateSpecialization = false;
7568 
7569   bool isDependentClassScopeExplicitSpecialization = false;
7570   bool HasExplicitTemplateArgs = false;
7571   TemplateArgumentListInfo TemplateArgs;
7572 
7573   bool isVirtualOkay = false;
7574 
7575   DeclContext *OriginalDC = DC;
7576   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7577 
7578   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7579                                               isVirtualOkay);
7580   if (!NewFD) return nullptr;
7581 
7582   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7583     NewFD->setTopLevelDeclInObjCContainer();
7584 
7585   // Set the lexical context. If this is a function-scope declaration, or has a
7586   // C++ scope specifier, or is the object of a friend declaration, the lexical
7587   // context will be different from the semantic context.
7588   NewFD->setLexicalDeclContext(CurContext);
7589 
7590   if (IsLocalExternDecl)
7591     NewFD->setLocalExternDecl();
7592 
7593   if (getLangOpts().CPlusPlus) {
7594     bool isInline = D.getDeclSpec().isInlineSpecified();
7595     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7596     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7597     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7598     bool isConcept = D.getDeclSpec().isConceptSpecified();
7599     isFriend = D.getDeclSpec().isFriendSpecified();
7600     if (isFriend && !isInline && D.isFunctionDefinition()) {
7601       // C++ [class.friend]p5
7602       //   A function can be defined in a friend declaration of a
7603       //   class . . . . Such a function is implicitly inline.
7604       NewFD->setImplicitlyInline();
7605     }
7606 
7607     // If this is a method defined in an __interface, and is not a constructor
7608     // or an overloaded operator, then set the pure flag (isVirtual will already
7609     // return true).
7610     if (const CXXRecordDecl *Parent =
7611           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7612       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7613         NewFD->setPure(true);
7614 
7615       // C++ [class.union]p2
7616       //   A union can have member functions, but not virtual functions.
7617       if (isVirtual && Parent->isUnion())
7618         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7619     }
7620 
7621     SetNestedNameSpecifier(NewFD, D);
7622     isExplicitSpecialization = false;
7623     isFunctionTemplateSpecialization = false;
7624     if (D.isInvalidType())
7625       NewFD->setInvalidDecl();
7626 
7627     // Match up the template parameter lists with the scope specifier, then
7628     // determine whether we have a template or a template specialization.
7629     bool Invalid = false;
7630     if (TemplateParameterList *TemplateParams =
7631             MatchTemplateParametersToScopeSpecifier(
7632                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7633                 D.getCXXScopeSpec(),
7634                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7635                     ? D.getName().TemplateId
7636                     : nullptr,
7637                 TemplateParamLists, isFriend, isExplicitSpecialization,
7638                 Invalid)) {
7639       if (TemplateParams->size() > 0) {
7640         // This is a function template
7641 
7642         // Check that we can declare a template here.
7643         if (CheckTemplateDeclScope(S, TemplateParams))
7644           NewFD->setInvalidDecl();
7645 
7646         // A destructor cannot be a template.
7647         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7648           Diag(NewFD->getLocation(), diag::err_destructor_template);
7649           NewFD->setInvalidDecl();
7650         }
7651 
7652         // If we're adding a template to a dependent context, we may need to
7653         // rebuilding some of the types used within the template parameter list,
7654         // now that we know what the current instantiation is.
7655         if (DC->isDependentContext()) {
7656           ContextRAII SavedContext(*this, DC);
7657           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7658             Invalid = true;
7659         }
7660 
7661         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7662                                                         NewFD->getLocation(),
7663                                                         Name, TemplateParams,
7664                                                         NewFD);
7665         FunctionTemplate->setLexicalDeclContext(CurContext);
7666         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7667 
7668         // For source fidelity, store the other template param lists.
7669         if (TemplateParamLists.size() > 1) {
7670           NewFD->setTemplateParameterListsInfo(Context,
7671                                                TemplateParamLists.drop_back(1));
7672         }
7673       } else {
7674         // This is a function template specialization.
7675         isFunctionTemplateSpecialization = true;
7676         // For source fidelity, store all the template param lists.
7677         if (TemplateParamLists.size() > 0)
7678           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7679 
7680         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7681         if (isFriend) {
7682           // We want to remove the "template<>", found here.
7683           SourceRange RemoveRange = TemplateParams->getSourceRange();
7684 
7685           // If we remove the template<> and the name is not a
7686           // template-id, we're actually silently creating a problem:
7687           // the friend declaration will refer to an untemplated decl,
7688           // and clearly the user wants a template specialization.  So
7689           // we need to insert '<>' after the name.
7690           SourceLocation InsertLoc;
7691           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7692             InsertLoc = D.getName().getSourceRange().getEnd();
7693             InsertLoc = getLocForEndOfToken(InsertLoc);
7694           }
7695 
7696           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7697             << Name << RemoveRange
7698             << FixItHint::CreateRemoval(RemoveRange)
7699             << FixItHint::CreateInsertion(InsertLoc, "<>");
7700         }
7701       }
7702     }
7703     else {
7704       // All template param lists were matched against the scope specifier:
7705       // this is NOT (an explicit specialization of) a template.
7706       if (TemplateParamLists.size() > 0)
7707         // For source fidelity, store all the template param lists.
7708         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7709     }
7710 
7711     if (Invalid) {
7712       NewFD->setInvalidDecl();
7713       if (FunctionTemplate)
7714         FunctionTemplate->setInvalidDecl();
7715     }
7716 
7717     // C++ [dcl.fct.spec]p5:
7718     //   The virtual specifier shall only be used in declarations of
7719     //   nonstatic class member functions that appear within a
7720     //   member-specification of a class declaration; see 10.3.
7721     //
7722     if (isVirtual && !NewFD->isInvalidDecl()) {
7723       if (!isVirtualOkay) {
7724         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7725              diag::err_virtual_non_function);
7726       } else if (!CurContext->isRecord()) {
7727         // 'virtual' was specified outside of the class.
7728         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7729              diag::err_virtual_out_of_class)
7730           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7731       } else if (NewFD->getDescribedFunctionTemplate()) {
7732         // C++ [temp.mem]p3:
7733         //  A member function template shall not be virtual.
7734         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7735              diag::err_virtual_member_function_template)
7736           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7737       } else {
7738         // Okay: Add virtual to the method.
7739         NewFD->setVirtualAsWritten(true);
7740       }
7741 
7742       if (getLangOpts().CPlusPlus14 &&
7743           NewFD->getReturnType()->isUndeducedType())
7744         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7745     }
7746 
7747     if (getLangOpts().CPlusPlus14 &&
7748         (NewFD->isDependentContext() ||
7749          (isFriend && CurContext->isDependentContext())) &&
7750         NewFD->getReturnType()->isUndeducedType()) {
7751       // If the function template is referenced directly (for instance, as a
7752       // member of the current instantiation), pretend it has a dependent type.
7753       // This is not really justified by the standard, but is the only sane
7754       // thing to do.
7755       // FIXME: For a friend function, we have not marked the function as being
7756       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7757       const FunctionProtoType *FPT =
7758           NewFD->getType()->castAs<FunctionProtoType>();
7759       QualType Result =
7760           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7761       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7762                                              FPT->getExtProtoInfo()));
7763     }
7764 
7765     // C++ [dcl.fct.spec]p3:
7766     //  The inline specifier shall not appear on a block scope function
7767     //  declaration.
7768     if (isInline && !NewFD->isInvalidDecl()) {
7769       if (CurContext->isFunctionOrMethod()) {
7770         // 'inline' is not allowed on block scope function declaration.
7771         Diag(D.getDeclSpec().getInlineSpecLoc(),
7772              diag::err_inline_declaration_block_scope) << Name
7773           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7774       }
7775     }
7776 
7777     // C++ [dcl.fct.spec]p6:
7778     //  The explicit specifier shall be used only in the declaration of a
7779     //  constructor or conversion function within its class definition;
7780     //  see 12.3.1 and 12.3.2.
7781     if (isExplicit && !NewFD->isInvalidDecl()) {
7782       if (!CurContext->isRecord()) {
7783         // 'explicit' was specified outside of the class.
7784         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7785              diag::err_explicit_out_of_class)
7786           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7787       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7788                  !isa<CXXConversionDecl>(NewFD)) {
7789         // 'explicit' was specified on a function that wasn't a constructor
7790         // or conversion function.
7791         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7792              diag::err_explicit_non_ctor_or_conv_function)
7793           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7794       }
7795     }
7796 
7797     if (isConstexpr) {
7798       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7799       // are implicitly inline.
7800       NewFD->setImplicitlyInline();
7801 
7802       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7803       // be either constructors or to return a literal type. Therefore,
7804       // destructors cannot be declared constexpr.
7805       if (isa<CXXDestructorDecl>(NewFD))
7806         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7807     }
7808 
7809     if (isConcept) {
7810       // This is a function concept.
7811       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
7812         FTD->setConcept();
7813 
7814       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7815       // applied only to the definition of a function template [...]
7816       if (!D.isFunctionDefinition()) {
7817         Diag(D.getDeclSpec().getConceptSpecLoc(),
7818              diag::err_function_concept_not_defined);
7819         NewFD->setInvalidDecl();
7820       }
7821 
7822       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7823       // have no exception-specification and is treated as if it were specified
7824       // with noexcept(true) (15.4). [...]
7825       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7826         if (FPT->hasExceptionSpec()) {
7827           SourceRange Range;
7828           if (D.isFunctionDeclarator())
7829             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7830           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7831               << FixItHint::CreateRemoval(Range);
7832           NewFD->setInvalidDecl();
7833         } else {
7834           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7835         }
7836 
7837         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7838         // following restrictions:
7839         // - The declared return type shall have the type bool.
7840         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
7841           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
7842           NewFD->setInvalidDecl();
7843         }
7844 
7845         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7846         // following restrictions:
7847         // - The declaration's parameter list shall be equivalent to an empty
7848         //   parameter list.
7849         if (FPT->getNumParams() > 0 || FPT->isVariadic())
7850           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7851       }
7852 
7853       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7854       // implicity defined to be a constexpr declaration (implicitly inline)
7855       NewFD->setImplicitlyInline();
7856 
7857       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7858       // be declared with the thread_local, inline, friend, or constexpr
7859       // specifiers, [...]
7860       if (isInline) {
7861         Diag(D.getDeclSpec().getInlineSpecLoc(),
7862              diag::err_concept_decl_invalid_specifiers)
7863             << 1 << 1;
7864         NewFD->setInvalidDecl(true);
7865       }
7866 
7867       if (isFriend) {
7868         Diag(D.getDeclSpec().getFriendSpecLoc(),
7869              diag::err_concept_decl_invalid_specifiers)
7870             << 1 << 2;
7871         NewFD->setInvalidDecl(true);
7872       }
7873 
7874       if (isConstexpr) {
7875         Diag(D.getDeclSpec().getConstexprSpecLoc(),
7876              diag::err_concept_decl_invalid_specifiers)
7877             << 1 << 3;
7878         NewFD->setInvalidDecl(true);
7879       }
7880 
7881       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7882       // applied only to the definition of a function template or variable
7883       // template, declared in namespace scope.
7884       if (isFunctionTemplateSpecialization) {
7885         Diag(D.getDeclSpec().getConceptSpecLoc(),
7886              diag::err_concept_specified_specialization) << 1;
7887         NewFD->setInvalidDecl(true);
7888         return NewFD;
7889       }
7890     }
7891 
7892     // If __module_private__ was specified, mark the function accordingly.
7893     if (D.getDeclSpec().isModulePrivateSpecified()) {
7894       if (isFunctionTemplateSpecialization) {
7895         SourceLocation ModulePrivateLoc
7896           = D.getDeclSpec().getModulePrivateSpecLoc();
7897         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7898           << 0
7899           << FixItHint::CreateRemoval(ModulePrivateLoc);
7900       } else {
7901         NewFD->setModulePrivate();
7902         if (FunctionTemplate)
7903           FunctionTemplate->setModulePrivate();
7904       }
7905     }
7906 
7907     if (isFriend) {
7908       if (FunctionTemplate) {
7909         FunctionTemplate->setObjectOfFriendDecl();
7910         FunctionTemplate->setAccess(AS_public);
7911       }
7912       NewFD->setObjectOfFriendDecl();
7913       NewFD->setAccess(AS_public);
7914     }
7915 
7916     // If a function is defined as defaulted or deleted, mark it as such now.
7917     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7918     // definition kind to FDK_Definition.
7919     switch (D.getFunctionDefinitionKind()) {
7920       case FDK_Declaration:
7921       case FDK_Definition:
7922         break;
7923 
7924       case FDK_Defaulted:
7925         NewFD->setDefaulted();
7926         break;
7927 
7928       case FDK_Deleted:
7929         NewFD->setDeletedAsWritten();
7930         break;
7931     }
7932 
7933     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7934         D.isFunctionDefinition()) {
7935       // C++ [class.mfct]p2:
7936       //   A member function may be defined (8.4) in its class definition, in
7937       //   which case it is an inline member function (7.1.2)
7938       NewFD->setImplicitlyInline();
7939     }
7940 
7941     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7942         !CurContext->isRecord()) {
7943       // C++ [class.static]p1:
7944       //   A data or function member of a class may be declared static
7945       //   in a class definition, in which case it is a static member of
7946       //   the class.
7947 
7948       // Complain about the 'static' specifier if it's on an out-of-line
7949       // member function definition.
7950       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7951            diag::err_static_out_of_line)
7952         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7953     }
7954 
7955     // C++11 [except.spec]p15:
7956     //   A deallocation function with no exception-specification is treated
7957     //   as if it were specified with noexcept(true).
7958     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7959     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7960          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7961         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7962       NewFD->setType(Context.getFunctionType(
7963           FPT->getReturnType(), FPT->getParamTypes(),
7964           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7965   }
7966 
7967   // Filter out previous declarations that don't match the scope.
7968   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7969                        D.getCXXScopeSpec().isNotEmpty() ||
7970                        isExplicitSpecialization ||
7971                        isFunctionTemplateSpecialization);
7972 
7973   // Handle GNU asm-label extension (encoded as an attribute).
7974   if (Expr *E = (Expr*) D.getAsmLabel()) {
7975     // The parser guarantees this is a string.
7976     StringLiteral *SE = cast<StringLiteral>(E);
7977     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7978                                                 SE->getString(), 0));
7979   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7980     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7981       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7982     if (I != ExtnameUndeclaredIdentifiers.end()) {
7983       if (isDeclExternC(NewFD)) {
7984         NewFD->addAttr(I->second);
7985         ExtnameUndeclaredIdentifiers.erase(I);
7986       } else
7987         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
7988             << /*Variable*/0 << NewFD;
7989     }
7990   }
7991 
7992   // Copy the parameter declarations from the declarator D to the function
7993   // declaration NewFD, if they are available.  First scavenge them into Params.
7994   SmallVector<ParmVarDecl*, 16> Params;
7995   if (D.isFunctionDeclarator()) {
7996     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7997 
7998     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7999     // function that takes no arguments, not a function that takes a
8000     // single void argument.
8001     // We let through "const void" here because Sema::GetTypeForDeclarator
8002     // already checks for that case.
8003     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8004       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8005         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8006         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8007         Param->setDeclContext(NewFD);
8008         Params.push_back(Param);
8009 
8010         if (Param->isInvalidDecl())
8011           NewFD->setInvalidDecl();
8012       }
8013     }
8014   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8015     // When we're declaring a function with a typedef, typeof, etc as in the
8016     // following example, we'll need to synthesize (unnamed)
8017     // parameters for use in the declaration.
8018     //
8019     // @code
8020     // typedef void fn(int);
8021     // fn f;
8022     // @endcode
8023 
8024     // Synthesize a parameter for each argument type.
8025     for (const auto &AI : FT->param_types()) {
8026       ParmVarDecl *Param =
8027           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8028       Param->setScopeInfo(0, Params.size());
8029       Params.push_back(Param);
8030     }
8031   } else {
8032     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8033            "Should not need args for typedef of non-prototype fn");
8034   }
8035 
8036   // Finally, we know we have the right number of parameters, install them.
8037   NewFD->setParams(Params);
8038 
8039   // Find all anonymous symbols defined during the declaration of this function
8040   // and add to NewFD. This lets us track decls such 'enum Y' in:
8041   //
8042   //   void f(enum Y {AA} x) {}
8043   //
8044   // which would otherwise incorrectly end up in the translation unit scope.
8045   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
8046   DeclsInPrototypeScope.clear();
8047 
8048   if (D.getDeclSpec().isNoreturnSpecified())
8049     NewFD->addAttr(
8050         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8051                                        Context, 0));
8052 
8053   // Functions returning a variably modified type violate C99 6.7.5.2p2
8054   // because all functions have linkage.
8055   if (!NewFD->isInvalidDecl() &&
8056       NewFD->getReturnType()->isVariablyModifiedType()) {
8057     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8058     NewFD->setInvalidDecl();
8059   }
8060 
8061   // Apply an implicit SectionAttr if #pragma code_seg is active.
8062   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8063       !NewFD->hasAttr<SectionAttr>()) {
8064     NewFD->addAttr(
8065         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8066                                     CodeSegStack.CurrentValue->getString(),
8067                                     CodeSegStack.CurrentPragmaLocation));
8068     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8069                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8070                          ASTContext::PSF_Read,
8071                      NewFD))
8072       NewFD->dropAttr<SectionAttr>();
8073   }
8074 
8075   // Handle attributes.
8076   ProcessDeclAttributes(S, NewFD, D);
8077 
8078   if (getLangOpts().CUDA)
8079     maybeAddCUDAHostDeviceAttrs(S, NewFD, Previous);
8080 
8081   if (getLangOpts().OpenCL) {
8082     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8083     // type declaration will generate a compilation error.
8084     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8085     if (AddressSpace == LangAS::opencl_local ||
8086         AddressSpace == LangAS::opencl_global ||
8087         AddressSpace == LangAS::opencl_constant) {
8088       Diag(NewFD->getLocation(),
8089            diag::err_opencl_return_value_with_address_space);
8090       NewFD->setInvalidDecl();
8091     }
8092   }
8093 
8094   if (!getLangOpts().CPlusPlus) {
8095     // Perform semantic checking on the function declaration.
8096     bool isExplicitSpecialization=false;
8097     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8098       CheckMain(NewFD, D.getDeclSpec());
8099 
8100     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8101       CheckMSVCRTEntryPoint(NewFD);
8102 
8103     if (!NewFD->isInvalidDecl())
8104       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8105                                                   isExplicitSpecialization));
8106     else if (!Previous.empty())
8107       // Recover gracefully from an invalid redeclaration.
8108       D.setRedeclaration(true);
8109     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8110             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8111            "previous declaration set still overloaded");
8112 
8113     // Diagnose no-prototype function declarations with calling conventions that
8114     // don't support variadic calls. Only do this in C and do it after merging
8115     // possibly prototyped redeclarations.
8116     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8117     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8118       CallingConv CC = FT->getExtInfo().getCC();
8119       if (!supportsVariadicCall(CC)) {
8120         // Windows system headers sometimes accidentally use stdcall without
8121         // (void) parameters, so we relax this to a warning.
8122         int DiagID =
8123             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8124         Diag(NewFD->getLocation(), DiagID)
8125             << FunctionType::getNameForCallConv(CC);
8126       }
8127     }
8128   } else {
8129     // C++11 [replacement.functions]p3:
8130     //  The program's definitions shall not be specified as inline.
8131     //
8132     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8133     //
8134     // Suppress the diagnostic if the function is __attribute__((used)), since
8135     // that forces an external definition to be emitted.
8136     if (D.getDeclSpec().isInlineSpecified() &&
8137         NewFD->isReplaceableGlobalAllocationFunction() &&
8138         !NewFD->hasAttr<UsedAttr>())
8139       Diag(D.getDeclSpec().getInlineSpecLoc(),
8140            diag::ext_operator_new_delete_declared_inline)
8141         << NewFD->getDeclName();
8142 
8143     // If the declarator is a template-id, translate the parser's template
8144     // argument list into our AST format.
8145     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8146       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8147       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8148       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8149       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8150                                          TemplateId->NumArgs);
8151       translateTemplateArguments(TemplateArgsPtr,
8152                                  TemplateArgs);
8153 
8154       HasExplicitTemplateArgs = true;
8155 
8156       if (NewFD->isInvalidDecl()) {
8157         HasExplicitTemplateArgs = false;
8158       } else if (FunctionTemplate) {
8159         // Function template with explicit template arguments.
8160         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8161           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8162 
8163         HasExplicitTemplateArgs = false;
8164       } else {
8165         assert((isFunctionTemplateSpecialization ||
8166                 D.getDeclSpec().isFriendSpecified()) &&
8167                "should have a 'template<>' for this decl");
8168         // "friend void foo<>(int);" is an implicit specialization decl.
8169         isFunctionTemplateSpecialization = true;
8170       }
8171     } else if (isFriend && isFunctionTemplateSpecialization) {
8172       // This combination is only possible in a recovery case;  the user
8173       // wrote something like:
8174       //   template <> friend void foo(int);
8175       // which we're recovering from as if the user had written:
8176       //   friend void foo<>(int);
8177       // Go ahead and fake up a template id.
8178       HasExplicitTemplateArgs = true;
8179       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8180       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8181     }
8182 
8183     // If it's a friend (and only if it's a friend), it's possible
8184     // that either the specialized function type or the specialized
8185     // template is dependent, and therefore matching will fail.  In
8186     // this case, don't check the specialization yet.
8187     bool InstantiationDependent = false;
8188     if (isFunctionTemplateSpecialization && isFriend &&
8189         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8190          TemplateSpecializationType::anyDependentTemplateArguments(
8191             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
8192             InstantiationDependent))) {
8193       assert(HasExplicitTemplateArgs &&
8194              "friend function specialization without template args");
8195       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8196                                                        Previous))
8197         NewFD->setInvalidDecl();
8198     } else if (isFunctionTemplateSpecialization) {
8199       if (CurContext->isDependentContext() && CurContext->isRecord()
8200           && !isFriend) {
8201         isDependentClassScopeExplicitSpecialization = true;
8202         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8203           diag::ext_function_specialization_in_class :
8204           diag::err_function_specialization_in_class)
8205           << NewFD->getDeclName();
8206       } else if (CheckFunctionTemplateSpecialization(NewFD,
8207                                   (HasExplicitTemplateArgs ? &TemplateArgs
8208                                                            : nullptr),
8209                                                      Previous))
8210         NewFD->setInvalidDecl();
8211 
8212       // C++ [dcl.stc]p1:
8213       //   A storage-class-specifier shall not be specified in an explicit
8214       //   specialization (14.7.3)
8215       FunctionTemplateSpecializationInfo *Info =
8216           NewFD->getTemplateSpecializationInfo();
8217       if (Info && SC != SC_None) {
8218         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8219           Diag(NewFD->getLocation(),
8220                diag::err_explicit_specialization_inconsistent_storage_class)
8221             << SC
8222             << FixItHint::CreateRemoval(
8223                                       D.getDeclSpec().getStorageClassSpecLoc());
8224 
8225         else
8226           Diag(NewFD->getLocation(),
8227                diag::ext_explicit_specialization_storage_class)
8228             << FixItHint::CreateRemoval(
8229                                       D.getDeclSpec().getStorageClassSpecLoc());
8230       }
8231     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8232       if (CheckMemberSpecialization(NewFD, Previous))
8233           NewFD->setInvalidDecl();
8234     }
8235 
8236     // Perform semantic checking on the function declaration.
8237     if (!isDependentClassScopeExplicitSpecialization) {
8238       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8239         CheckMain(NewFD, D.getDeclSpec());
8240 
8241       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8242         CheckMSVCRTEntryPoint(NewFD);
8243 
8244       if (!NewFD->isInvalidDecl())
8245         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8246                                                     isExplicitSpecialization));
8247       else if (!Previous.empty())
8248         // Recover gracefully from an invalid redeclaration.
8249         D.setRedeclaration(true);
8250     }
8251 
8252     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8253             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8254            "previous declaration set still overloaded");
8255 
8256     NamedDecl *PrincipalDecl = (FunctionTemplate
8257                                 ? cast<NamedDecl>(FunctionTemplate)
8258                                 : NewFD);
8259 
8260     if (isFriend && D.isRedeclaration()) {
8261       AccessSpecifier Access = AS_public;
8262       if (!NewFD->isInvalidDecl())
8263         Access = NewFD->getPreviousDecl()->getAccess();
8264 
8265       NewFD->setAccess(Access);
8266       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8267     }
8268 
8269     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8270         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8271       PrincipalDecl->setNonMemberOperator();
8272 
8273     // If we have a function template, check the template parameter
8274     // list. This will check and merge default template arguments.
8275     if (FunctionTemplate) {
8276       FunctionTemplateDecl *PrevTemplate =
8277                                      FunctionTemplate->getPreviousDecl();
8278       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8279                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8280                                     : nullptr,
8281                             D.getDeclSpec().isFriendSpecified()
8282                               ? (D.isFunctionDefinition()
8283                                    ? TPC_FriendFunctionTemplateDefinition
8284                                    : TPC_FriendFunctionTemplate)
8285                               : (D.getCXXScopeSpec().isSet() &&
8286                                  DC && DC->isRecord() &&
8287                                  DC->isDependentContext())
8288                                   ? TPC_ClassTemplateMember
8289                                   : TPC_FunctionTemplate);
8290     }
8291 
8292     if (NewFD->isInvalidDecl()) {
8293       // Ignore all the rest of this.
8294     } else if (!D.isRedeclaration()) {
8295       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8296                                        AddToScope };
8297       // Fake up an access specifier if it's supposed to be a class member.
8298       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8299         NewFD->setAccess(AS_public);
8300 
8301       // Qualified decls generally require a previous declaration.
8302       if (D.getCXXScopeSpec().isSet()) {
8303         // ...with the major exception of templated-scope or
8304         // dependent-scope friend declarations.
8305 
8306         // TODO: we currently also suppress this check in dependent
8307         // contexts because (1) the parameter depth will be off when
8308         // matching friend templates and (2) we might actually be
8309         // selecting a friend based on a dependent factor.  But there
8310         // are situations where these conditions don't apply and we
8311         // can actually do this check immediately.
8312         if (isFriend &&
8313             (TemplateParamLists.size() ||
8314              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8315              CurContext->isDependentContext())) {
8316           // ignore these
8317         } else {
8318           // The user tried to provide an out-of-line definition for a
8319           // function that is a member of a class or namespace, but there
8320           // was no such member function declared (C++ [class.mfct]p2,
8321           // C++ [namespace.memdef]p2). For example:
8322           //
8323           // class X {
8324           //   void f() const;
8325           // };
8326           //
8327           // void X::f() { } // ill-formed
8328           //
8329           // Complain about this problem, and attempt to suggest close
8330           // matches (e.g., those that differ only in cv-qualifiers and
8331           // whether the parameter types are references).
8332 
8333           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8334                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8335             AddToScope = ExtraArgs.AddToScope;
8336             return Result;
8337           }
8338         }
8339 
8340         // Unqualified local friend declarations are required to resolve
8341         // to something.
8342       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8343         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8344                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8345           AddToScope = ExtraArgs.AddToScope;
8346           return Result;
8347         }
8348       }
8349     } else if (!D.isFunctionDefinition() &&
8350                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8351                !isFriend && !isFunctionTemplateSpecialization &&
8352                !isExplicitSpecialization) {
8353       // An out-of-line member function declaration must also be a
8354       // definition (C++ [class.mfct]p2).
8355       // Note that this is not the case for explicit specializations of
8356       // function templates or member functions of class templates, per
8357       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8358       // extension for compatibility with old SWIG code which likes to
8359       // generate them.
8360       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8361         << D.getCXXScopeSpec().getRange();
8362     }
8363   }
8364 
8365   ProcessPragmaWeak(S, NewFD);
8366   checkAttributesAfterMerging(*this, *NewFD);
8367 
8368   AddKnownFunctionAttributes(NewFD);
8369 
8370   if (NewFD->hasAttr<OverloadableAttr>() &&
8371       !NewFD->getType()->getAs<FunctionProtoType>()) {
8372     Diag(NewFD->getLocation(),
8373          diag::err_attribute_overloadable_no_prototype)
8374       << NewFD;
8375 
8376     // Turn this into a variadic function with no parameters.
8377     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8378     FunctionProtoType::ExtProtoInfo EPI(
8379         Context.getDefaultCallingConvention(true, false));
8380     EPI.Variadic = true;
8381     EPI.ExtInfo = FT->getExtInfo();
8382 
8383     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8384     NewFD->setType(R);
8385   }
8386 
8387   // If there's a #pragma GCC visibility in scope, and this isn't a class
8388   // member, set the visibility of this function.
8389   if (!DC->isRecord() && NewFD->isExternallyVisible())
8390     AddPushedVisibilityAttribute(NewFD);
8391 
8392   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8393   // marking the function.
8394   AddCFAuditedAttribute(NewFD);
8395 
8396   // If this is a function definition, check if we have to apply optnone due to
8397   // a pragma.
8398   if(D.isFunctionDefinition())
8399     AddRangeBasedOptnone(NewFD);
8400 
8401   // If this is the first declaration of an extern C variable, update
8402   // the map of such variables.
8403   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8404       isIncompleteDeclExternC(*this, NewFD))
8405     RegisterLocallyScopedExternCDecl(NewFD, S);
8406 
8407   // Set this FunctionDecl's range up to the right paren.
8408   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8409 
8410   if (D.isRedeclaration() && !Previous.empty()) {
8411     checkDLLAttributeRedeclaration(
8412         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8413         isExplicitSpecialization || isFunctionTemplateSpecialization);
8414   }
8415 
8416   if (getLangOpts().CUDA) {
8417     IdentifierInfo *II = NewFD->getIdentifier();
8418     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8419         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8420       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8421         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8422 
8423       Context.setcudaConfigureCallDecl(NewFD);
8424     }
8425 
8426     // Variadic functions, other than a *declaration* of printf, are not allowed
8427     // in device-side CUDA code, unless someone passed
8428     // -fcuda-allow-variadic-functions.
8429     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8430         (NewFD->hasAttr<CUDADeviceAttr>() ||
8431          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8432         !(II && II->isStr("printf") && NewFD->isExternC() &&
8433           !D.isFunctionDefinition())) {
8434       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8435     }
8436   }
8437 
8438   if (getLangOpts().CPlusPlus) {
8439     if (FunctionTemplate) {
8440       if (NewFD->isInvalidDecl())
8441         FunctionTemplate->setInvalidDecl();
8442       return FunctionTemplate;
8443     }
8444   }
8445 
8446   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8447     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8448     if ((getLangOpts().OpenCLVersion >= 120)
8449         && (SC == SC_Static)) {
8450       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8451       D.setInvalidType();
8452     }
8453 
8454     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8455     if (!NewFD->getReturnType()->isVoidType()) {
8456       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8457       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8458           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8459                                 : FixItHint());
8460       D.setInvalidType();
8461     }
8462 
8463     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8464     for (auto Param : NewFD->params())
8465       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8466   }
8467   for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
8468        PE = NewFD->param_end(); PI != PE; ++PI) {
8469     ParmVarDecl *Param = *PI;
8470     QualType PT = Param->getType();
8471 
8472     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8473     // types.
8474     if (getLangOpts().OpenCLVersion >= 200) {
8475       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8476         QualType ElemTy = PipeTy->getElementType();
8477           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8478             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8479             D.setInvalidType();
8480           }
8481       }
8482     }
8483   }
8484 
8485   MarkUnusedFileScopedDecl(NewFD);
8486 
8487   // Here we have an function template explicit specialization at class scope.
8488   // The actually specialization will be postponed to template instatiation
8489   // time via the ClassScopeFunctionSpecializationDecl node.
8490   if (isDependentClassScopeExplicitSpecialization) {
8491     ClassScopeFunctionSpecializationDecl *NewSpec =
8492                          ClassScopeFunctionSpecializationDecl::Create(
8493                                 Context, CurContext, SourceLocation(),
8494                                 cast<CXXMethodDecl>(NewFD),
8495                                 HasExplicitTemplateArgs, TemplateArgs);
8496     CurContext->addDecl(NewSpec);
8497     AddToScope = false;
8498   }
8499 
8500   return NewFD;
8501 }
8502 
8503 /// \brief Perform semantic checking of a new function declaration.
8504 ///
8505 /// Performs semantic analysis of the new function declaration
8506 /// NewFD. This routine performs all semantic checking that does not
8507 /// require the actual declarator involved in the declaration, and is
8508 /// used both for the declaration of functions as they are parsed
8509 /// (called via ActOnDeclarator) and for the declaration of functions
8510 /// that have been instantiated via C++ template instantiation (called
8511 /// via InstantiateDecl).
8512 ///
8513 /// \param IsExplicitSpecialization whether this new function declaration is
8514 /// an explicit specialization of the previous declaration.
8515 ///
8516 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8517 ///
8518 /// \returns true if the function declaration is a redeclaration.
8519 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8520                                     LookupResult &Previous,
8521                                     bool IsExplicitSpecialization) {
8522   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8523          "Variably modified return types are not handled here");
8524 
8525   // Determine whether the type of this function should be merged with
8526   // a previous visible declaration. This never happens for functions in C++,
8527   // and always happens in C if the previous declaration was visible.
8528   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8529                                !Previous.isShadowed();
8530 
8531   bool Redeclaration = false;
8532   NamedDecl *OldDecl = nullptr;
8533 
8534   // Merge or overload the declaration with an existing declaration of
8535   // the same name, if appropriate.
8536   if (!Previous.empty()) {
8537     // Determine whether NewFD is an overload of PrevDecl or
8538     // a declaration that requires merging. If it's an overload,
8539     // there's no more work to do here; we'll just add the new
8540     // function to the scope.
8541     if (!AllowOverloadingOfFunction(Previous, Context)) {
8542       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8543       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8544         Redeclaration = true;
8545         OldDecl = Candidate;
8546       }
8547     } else {
8548       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8549                             /*NewIsUsingDecl*/ false)) {
8550       case Ovl_Match:
8551         Redeclaration = true;
8552         break;
8553 
8554       case Ovl_NonFunction:
8555         Redeclaration = true;
8556         break;
8557 
8558       case Ovl_Overload:
8559         Redeclaration = false;
8560         break;
8561       }
8562 
8563       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8564         // If a function name is overloadable in C, then every function
8565         // with that name must be marked "overloadable".
8566         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8567           << Redeclaration << NewFD;
8568         NamedDecl *OverloadedDecl = nullptr;
8569         if (Redeclaration)
8570           OverloadedDecl = OldDecl;
8571         else if (!Previous.empty())
8572           OverloadedDecl = Previous.getRepresentativeDecl();
8573         if (OverloadedDecl)
8574           Diag(OverloadedDecl->getLocation(),
8575                diag::note_attribute_overloadable_prev_overload);
8576         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8577       }
8578     }
8579   }
8580 
8581   // Check for a previous extern "C" declaration with this name.
8582   if (!Redeclaration &&
8583       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8584     if (!Previous.empty()) {
8585       // This is an extern "C" declaration with the same name as a previous
8586       // declaration, and thus redeclares that entity...
8587       Redeclaration = true;
8588       OldDecl = Previous.getFoundDecl();
8589       MergeTypeWithPrevious = false;
8590 
8591       // ... except in the presence of __attribute__((overloadable)).
8592       if (OldDecl->hasAttr<OverloadableAttr>()) {
8593         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8594           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8595             << Redeclaration << NewFD;
8596           Diag(Previous.getFoundDecl()->getLocation(),
8597                diag::note_attribute_overloadable_prev_overload);
8598           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8599         }
8600         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8601           Redeclaration = false;
8602           OldDecl = nullptr;
8603         }
8604       }
8605     }
8606   }
8607 
8608   // C++11 [dcl.constexpr]p8:
8609   //   A constexpr specifier for a non-static member function that is not
8610   //   a constructor declares that member function to be const.
8611   //
8612   // This needs to be delayed until we know whether this is an out-of-line
8613   // definition of a static member function.
8614   //
8615   // This rule is not present in C++1y, so we produce a backwards
8616   // compatibility warning whenever it happens in C++11.
8617   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8618   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8619       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8620       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8621     CXXMethodDecl *OldMD = nullptr;
8622     if (OldDecl)
8623       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8624     if (!OldMD || !OldMD->isStatic()) {
8625       const FunctionProtoType *FPT =
8626         MD->getType()->castAs<FunctionProtoType>();
8627       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8628       EPI.TypeQuals |= Qualifiers::Const;
8629       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8630                                           FPT->getParamTypes(), EPI));
8631 
8632       // Warn that we did this, if we're not performing template instantiation.
8633       // In that case, we'll have warned already when the template was defined.
8634       if (ActiveTemplateInstantiations.empty()) {
8635         SourceLocation AddConstLoc;
8636         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8637                 .IgnoreParens().getAs<FunctionTypeLoc>())
8638           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8639 
8640         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8641           << FixItHint::CreateInsertion(AddConstLoc, " const");
8642       }
8643     }
8644   }
8645 
8646   if (Redeclaration) {
8647     // NewFD and OldDecl represent declarations that need to be
8648     // merged.
8649     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8650       NewFD->setInvalidDecl();
8651       return Redeclaration;
8652     }
8653 
8654     Previous.clear();
8655     Previous.addDecl(OldDecl);
8656 
8657     if (FunctionTemplateDecl *OldTemplateDecl
8658                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8659       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8660       FunctionTemplateDecl *NewTemplateDecl
8661         = NewFD->getDescribedFunctionTemplate();
8662       assert(NewTemplateDecl && "Template/non-template mismatch");
8663       if (CXXMethodDecl *Method
8664             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8665         Method->setAccess(OldTemplateDecl->getAccess());
8666         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8667       }
8668 
8669       // If this is an explicit specialization of a member that is a function
8670       // template, mark it as a member specialization.
8671       if (IsExplicitSpecialization &&
8672           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8673         NewTemplateDecl->setMemberSpecialization();
8674         assert(OldTemplateDecl->isMemberSpecialization());
8675         // Explicit specializations of a member template do not inherit deleted
8676         // status from the parent member template that they are specializing.
8677         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
8678           FunctionDecl *const OldTemplatedDecl =
8679               OldTemplateDecl->getTemplatedDecl();
8680           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
8681           OldTemplatedDecl->setDeletedAsWritten(false);
8682         }
8683       }
8684 
8685     } else {
8686       // This needs to happen first so that 'inline' propagates.
8687       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8688 
8689       if (isa<CXXMethodDecl>(NewFD))
8690         NewFD->setAccess(OldDecl->getAccess());
8691     }
8692   }
8693 
8694   // Semantic checking for this function declaration (in isolation).
8695 
8696   if (getLangOpts().CPlusPlus) {
8697     // C++-specific checks.
8698     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8699       CheckConstructor(Constructor);
8700     } else if (CXXDestructorDecl *Destructor =
8701                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8702       CXXRecordDecl *Record = Destructor->getParent();
8703       QualType ClassType = Context.getTypeDeclType(Record);
8704 
8705       // FIXME: Shouldn't we be able to perform this check even when the class
8706       // type is dependent? Both gcc and edg can handle that.
8707       if (!ClassType->isDependentType()) {
8708         DeclarationName Name
8709           = Context.DeclarationNames.getCXXDestructorName(
8710                                         Context.getCanonicalType(ClassType));
8711         if (NewFD->getDeclName() != Name) {
8712           Diag(NewFD->getLocation(), diag::err_destructor_name);
8713           NewFD->setInvalidDecl();
8714           return Redeclaration;
8715         }
8716       }
8717     } else if (CXXConversionDecl *Conversion
8718                = dyn_cast<CXXConversionDecl>(NewFD)) {
8719       ActOnConversionDeclarator(Conversion);
8720     }
8721 
8722     // Find any virtual functions that this function overrides.
8723     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8724       if (!Method->isFunctionTemplateSpecialization() &&
8725           !Method->getDescribedFunctionTemplate() &&
8726           Method->isCanonicalDecl()) {
8727         if (AddOverriddenMethods(Method->getParent(), Method)) {
8728           // If the function was marked as "static", we have a problem.
8729           if (NewFD->getStorageClass() == SC_Static) {
8730             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8731           }
8732         }
8733       }
8734 
8735       if (Method->isStatic())
8736         checkThisInStaticMemberFunctionType(Method);
8737     }
8738 
8739     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8740     if (NewFD->isOverloadedOperator() &&
8741         CheckOverloadedOperatorDeclaration(NewFD)) {
8742       NewFD->setInvalidDecl();
8743       return Redeclaration;
8744     }
8745 
8746     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8747     if (NewFD->getLiteralIdentifier() &&
8748         CheckLiteralOperatorDeclaration(NewFD)) {
8749       NewFD->setInvalidDecl();
8750       return Redeclaration;
8751     }
8752 
8753     // In C++, check default arguments now that we have merged decls. Unless
8754     // the lexical context is the class, because in this case this is done
8755     // during delayed parsing anyway.
8756     if (!CurContext->isRecord())
8757       CheckCXXDefaultArguments(NewFD);
8758 
8759     // If this function declares a builtin function, check the type of this
8760     // declaration against the expected type for the builtin.
8761     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8762       ASTContext::GetBuiltinTypeError Error;
8763       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8764       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8765       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8766         // The type of this function differs from the type of the builtin,
8767         // so forget about the builtin entirely.
8768         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8769       }
8770     }
8771 
8772     // If this function is declared as being extern "C", then check to see if
8773     // the function returns a UDT (class, struct, or union type) that is not C
8774     // compatible, and if it does, warn the user.
8775     // But, issue any diagnostic on the first declaration only.
8776     if (Previous.empty() && NewFD->isExternC()) {
8777       QualType R = NewFD->getReturnType();
8778       if (R->isIncompleteType() && !R->isVoidType())
8779         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8780             << NewFD << R;
8781       else if (!R.isPODType(Context) && !R->isVoidType() &&
8782                !R->isObjCObjectPointerType())
8783         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8784     }
8785   }
8786   return Redeclaration;
8787 }
8788 
8789 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8790   // C++11 [basic.start.main]p3:
8791   //   A program that [...] declares main to be inline, static or
8792   //   constexpr is ill-formed.
8793   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8794   //   appear in a declaration of main.
8795   // static main is not an error under C99, but we should warn about it.
8796   // We accept _Noreturn main as an extension.
8797   if (FD->getStorageClass() == SC_Static)
8798     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8799          ? diag::err_static_main : diag::warn_static_main)
8800       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8801   if (FD->isInlineSpecified())
8802     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8803       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8804   if (DS.isNoreturnSpecified()) {
8805     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8806     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8807     Diag(NoreturnLoc, diag::ext_noreturn_main);
8808     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8809       << FixItHint::CreateRemoval(NoreturnRange);
8810   }
8811   if (FD->isConstexpr()) {
8812     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8813       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8814     FD->setConstexpr(false);
8815   }
8816 
8817   if (getLangOpts().OpenCL) {
8818     Diag(FD->getLocation(), diag::err_opencl_no_main)
8819         << FD->hasAttr<OpenCLKernelAttr>();
8820     FD->setInvalidDecl();
8821     return;
8822   }
8823 
8824   QualType T = FD->getType();
8825   assert(T->isFunctionType() && "function decl is not of function type");
8826   const FunctionType* FT = T->castAs<FunctionType>();
8827 
8828   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8829     // In C with GNU extensions we allow main() to have non-integer return
8830     // type, but we should warn about the extension, and we disable the
8831     // implicit-return-zero rule.
8832 
8833     // GCC in C mode accepts qualified 'int'.
8834     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8835       FD->setHasImplicitReturnZero(true);
8836     else {
8837       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8838       SourceRange RTRange = FD->getReturnTypeSourceRange();
8839       if (RTRange.isValid())
8840         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8841             << FixItHint::CreateReplacement(RTRange, "int");
8842     }
8843   } else {
8844     // In C and C++, main magically returns 0 if you fall off the end;
8845     // set the flag which tells us that.
8846     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8847 
8848     // All the standards say that main() should return 'int'.
8849     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8850       FD->setHasImplicitReturnZero(true);
8851     else {
8852       // Otherwise, this is just a flat-out error.
8853       SourceRange RTRange = FD->getReturnTypeSourceRange();
8854       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8855           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8856                                 : FixItHint());
8857       FD->setInvalidDecl(true);
8858     }
8859   }
8860 
8861   // Treat protoless main() as nullary.
8862   if (isa<FunctionNoProtoType>(FT)) return;
8863 
8864   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8865   unsigned nparams = FTP->getNumParams();
8866   assert(FD->getNumParams() == nparams);
8867 
8868   bool HasExtraParameters = (nparams > 3);
8869 
8870   if (FTP->isVariadic()) {
8871     Diag(FD->getLocation(), diag::ext_variadic_main);
8872     // FIXME: if we had information about the location of the ellipsis, we
8873     // could add a FixIt hint to remove it as a parameter.
8874   }
8875 
8876   // Darwin passes an undocumented fourth argument of type char**.  If
8877   // other platforms start sprouting these, the logic below will start
8878   // getting shifty.
8879   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8880     HasExtraParameters = false;
8881 
8882   if (HasExtraParameters) {
8883     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8884     FD->setInvalidDecl(true);
8885     nparams = 3;
8886   }
8887 
8888   // FIXME: a lot of the following diagnostics would be improved
8889   // if we had some location information about types.
8890 
8891   QualType CharPP =
8892     Context.getPointerType(Context.getPointerType(Context.CharTy));
8893   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8894 
8895   for (unsigned i = 0; i < nparams; ++i) {
8896     QualType AT = FTP->getParamType(i);
8897 
8898     bool mismatch = true;
8899 
8900     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8901       mismatch = false;
8902     else if (Expected[i] == CharPP) {
8903       // As an extension, the following forms are okay:
8904       //   char const **
8905       //   char const * const *
8906       //   char * const *
8907 
8908       QualifierCollector qs;
8909       const PointerType* PT;
8910       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8911           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8912           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8913                               Context.CharTy)) {
8914         qs.removeConst();
8915         mismatch = !qs.empty();
8916       }
8917     }
8918 
8919     if (mismatch) {
8920       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8921       // TODO: suggest replacing given type with expected type
8922       FD->setInvalidDecl(true);
8923     }
8924   }
8925 
8926   if (nparams == 1 && !FD->isInvalidDecl()) {
8927     Diag(FD->getLocation(), diag::warn_main_one_arg);
8928   }
8929 
8930   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8931     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8932     FD->setInvalidDecl();
8933   }
8934 }
8935 
8936 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8937   QualType T = FD->getType();
8938   assert(T->isFunctionType() && "function decl is not of function type");
8939   const FunctionType *FT = T->castAs<FunctionType>();
8940 
8941   // Set an implicit return of 'zero' if the function can return some integral,
8942   // enumeration, pointer or nullptr type.
8943   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8944       FT->getReturnType()->isAnyPointerType() ||
8945       FT->getReturnType()->isNullPtrType())
8946     // DllMain is exempt because a return value of zero means it failed.
8947     if (FD->getName() != "DllMain")
8948       FD->setHasImplicitReturnZero(true);
8949 
8950   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8951     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8952     FD->setInvalidDecl();
8953   }
8954 }
8955 
8956 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8957   // FIXME: Need strict checking.  In C89, we need to check for
8958   // any assignment, increment, decrement, function-calls, or
8959   // commas outside of a sizeof.  In C99, it's the same list,
8960   // except that the aforementioned are allowed in unevaluated
8961   // expressions.  Everything else falls under the
8962   // "may accept other forms of constant expressions" exception.
8963   // (We never end up here for C++, so the constant expression
8964   // rules there don't matter.)
8965   const Expr *Culprit;
8966   if (Init->isConstantInitializer(Context, false, &Culprit))
8967     return false;
8968   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8969     << Culprit->getSourceRange();
8970   return true;
8971 }
8972 
8973 namespace {
8974   // Visits an initialization expression to see if OrigDecl is evaluated in
8975   // its own initialization and throws a warning if it does.
8976   class SelfReferenceChecker
8977       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8978     Sema &S;
8979     Decl *OrigDecl;
8980     bool isRecordType;
8981     bool isPODType;
8982     bool isReferenceType;
8983 
8984     bool isInitList;
8985     llvm::SmallVector<unsigned, 4> InitFieldIndex;
8986 
8987   public:
8988     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8989 
8990     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8991                                                     S(S), OrigDecl(OrigDecl) {
8992       isPODType = false;
8993       isRecordType = false;
8994       isReferenceType = false;
8995       isInitList = false;
8996       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8997         isPODType = VD->getType().isPODType(S.Context);
8998         isRecordType = VD->getType()->isRecordType();
8999         isReferenceType = VD->getType()->isReferenceType();
9000       }
9001     }
9002 
9003     // For most expressions, just call the visitor.  For initializer lists,
9004     // track the index of the field being initialized since fields are
9005     // initialized in order allowing use of previously initialized fields.
9006     void CheckExpr(Expr *E) {
9007       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9008       if (!InitList) {
9009         Visit(E);
9010         return;
9011       }
9012 
9013       // Track and increment the index here.
9014       isInitList = true;
9015       InitFieldIndex.push_back(0);
9016       for (auto Child : InitList->children()) {
9017         CheckExpr(cast<Expr>(Child));
9018         ++InitFieldIndex.back();
9019       }
9020       InitFieldIndex.pop_back();
9021     }
9022 
9023     // Returns true if MemberExpr is checked and no futher checking is needed.
9024     // Returns false if additional checking is required.
9025     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9026       llvm::SmallVector<FieldDecl*, 4> Fields;
9027       Expr *Base = E;
9028       bool ReferenceField = false;
9029 
9030       // Get the field memebers used.
9031       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9032         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9033         if (!FD)
9034           return false;
9035         Fields.push_back(FD);
9036         if (FD->getType()->isReferenceType())
9037           ReferenceField = true;
9038         Base = ME->getBase()->IgnoreParenImpCasts();
9039       }
9040 
9041       // Keep checking only if the base Decl is the same.
9042       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9043       if (!DRE || DRE->getDecl() != OrigDecl)
9044         return false;
9045 
9046       // A reference field can be bound to an unininitialized field.
9047       if (CheckReference && !ReferenceField)
9048         return true;
9049 
9050       // Convert FieldDecls to their index number.
9051       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9052       for (const FieldDecl *I : llvm::reverse(Fields))
9053         UsedFieldIndex.push_back(I->getFieldIndex());
9054 
9055       // See if a warning is needed by checking the first difference in index
9056       // numbers.  If field being used has index less than the field being
9057       // initialized, then the use is safe.
9058       for (auto UsedIter = UsedFieldIndex.begin(),
9059                 UsedEnd = UsedFieldIndex.end(),
9060                 OrigIter = InitFieldIndex.begin(),
9061                 OrigEnd = InitFieldIndex.end();
9062            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9063         if (*UsedIter < *OrigIter)
9064           return true;
9065         if (*UsedIter > *OrigIter)
9066           break;
9067       }
9068 
9069       // TODO: Add a different warning which will print the field names.
9070       HandleDeclRefExpr(DRE);
9071       return true;
9072     }
9073 
9074     // For most expressions, the cast is directly above the DeclRefExpr.
9075     // For conditional operators, the cast can be outside the conditional
9076     // operator if both expressions are DeclRefExpr's.
9077     void HandleValue(Expr *E) {
9078       E = E->IgnoreParens();
9079       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9080         HandleDeclRefExpr(DRE);
9081         return;
9082       }
9083 
9084       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9085         Visit(CO->getCond());
9086         HandleValue(CO->getTrueExpr());
9087         HandleValue(CO->getFalseExpr());
9088         return;
9089       }
9090 
9091       if (BinaryConditionalOperator *BCO =
9092               dyn_cast<BinaryConditionalOperator>(E)) {
9093         Visit(BCO->getCond());
9094         HandleValue(BCO->getFalseExpr());
9095         return;
9096       }
9097 
9098       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9099         HandleValue(OVE->getSourceExpr());
9100         return;
9101       }
9102 
9103       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9104         if (BO->getOpcode() == BO_Comma) {
9105           Visit(BO->getLHS());
9106           HandleValue(BO->getRHS());
9107           return;
9108         }
9109       }
9110 
9111       if (isa<MemberExpr>(E)) {
9112         if (isInitList) {
9113           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9114                                       false /*CheckReference*/))
9115             return;
9116         }
9117 
9118         Expr *Base = E->IgnoreParenImpCasts();
9119         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9120           // Check for static member variables and don't warn on them.
9121           if (!isa<FieldDecl>(ME->getMemberDecl()))
9122             return;
9123           Base = ME->getBase()->IgnoreParenImpCasts();
9124         }
9125         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9126           HandleDeclRefExpr(DRE);
9127         return;
9128       }
9129 
9130       Visit(E);
9131     }
9132 
9133     // Reference types not handled in HandleValue are handled here since all
9134     // uses of references are bad, not just r-value uses.
9135     void VisitDeclRefExpr(DeclRefExpr *E) {
9136       if (isReferenceType)
9137         HandleDeclRefExpr(E);
9138     }
9139 
9140     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9141       if (E->getCastKind() == CK_LValueToRValue) {
9142         HandleValue(E->getSubExpr());
9143         return;
9144       }
9145 
9146       Inherited::VisitImplicitCastExpr(E);
9147     }
9148 
9149     void VisitMemberExpr(MemberExpr *E) {
9150       if (isInitList) {
9151         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9152           return;
9153       }
9154 
9155       // Don't warn on arrays since they can be treated as pointers.
9156       if (E->getType()->canDecayToPointerType()) return;
9157 
9158       // Warn when a non-static method call is followed by non-static member
9159       // field accesses, which is followed by a DeclRefExpr.
9160       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9161       bool Warn = (MD && !MD->isStatic());
9162       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9163       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9164         if (!isa<FieldDecl>(ME->getMemberDecl()))
9165           Warn = false;
9166         Base = ME->getBase()->IgnoreParenImpCasts();
9167       }
9168 
9169       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9170         if (Warn)
9171           HandleDeclRefExpr(DRE);
9172         return;
9173       }
9174 
9175       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9176       // Visit that expression.
9177       Visit(Base);
9178     }
9179 
9180     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9181       Expr *Callee = E->getCallee();
9182 
9183       if (isa<UnresolvedLookupExpr>(Callee))
9184         return Inherited::VisitCXXOperatorCallExpr(E);
9185 
9186       Visit(Callee);
9187       for (auto Arg: E->arguments())
9188         HandleValue(Arg->IgnoreParenImpCasts());
9189     }
9190 
9191     void VisitUnaryOperator(UnaryOperator *E) {
9192       // For POD record types, addresses of its own members are well-defined.
9193       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9194           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9195         if (!isPODType)
9196           HandleValue(E->getSubExpr());
9197         return;
9198       }
9199 
9200       if (E->isIncrementDecrementOp()) {
9201         HandleValue(E->getSubExpr());
9202         return;
9203       }
9204 
9205       Inherited::VisitUnaryOperator(E);
9206     }
9207 
9208     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9209 
9210     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9211       if (E->getConstructor()->isCopyConstructor()) {
9212         Expr *ArgExpr = E->getArg(0);
9213         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9214           if (ILE->getNumInits() == 1)
9215             ArgExpr = ILE->getInit(0);
9216         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9217           if (ICE->getCastKind() == CK_NoOp)
9218             ArgExpr = ICE->getSubExpr();
9219         HandleValue(ArgExpr);
9220         return;
9221       }
9222       Inherited::VisitCXXConstructExpr(E);
9223     }
9224 
9225     void VisitCallExpr(CallExpr *E) {
9226       // Treat std::move as a use.
9227       if (E->getNumArgs() == 1) {
9228         if (FunctionDecl *FD = E->getDirectCallee()) {
9229           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9230               FD->getIdentifier()->isStr("move")) {
9231             HandleValue(E->getArg(0));
9232             return;
9233           }
9234         }
9235       }
9236 
9237       Inherited::VisitCallExpr(E);
9238     }
9239 
9240     void VisitBinaryOperator(BinaryOperator *E) {
9241       if (E->isCompoundAssignmentOp()) {
9242         HandleValue(E->getLHS());
9243         Visit(E->getRHS());
9244         return;
9245       }
9246 
9247       Inherited::VisitBinaryOperator(E);
9248     }
9249 
9250     // A custom visitor for BinaryConditionalOperator is needed because the
9251     // regular visitor would check the condition and true expression separately
9252     // but both point to the same place giving duplicate diagnostics.
9253     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9254       Visit(E->getCond());
9255       Visit(E->getFalseExpr());
9256     }
9257 
9258     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9259       Decl* ReferenceDecl = DRE->getDecl();
9260       if (OrigDecl != ReferenceDecl) return;
9261       unsigned diag;
9262       if (isReferenceType) {
9263         diag = diag::warn_uninit_self_reference_in_reference_init;
9264       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9265         diag = diag::warn_static_self_reference_in_init;
9266       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9267                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9268                  DRE->getDecl()->getType()->isRecordType()) {
9269         diag = diag::warn_uninit_self_reference_in_init;
9270       } else {
9271         // Local variables will be handled by the CFG analysis.
9272         return;
9273       }
9274 
9275       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9276                             S.PDiag(diag)
9277                               << DRE->getNameInfo().getName()
9278                               << OrigDecl->getLocation()
9279                               << DRE->getSourceRange());
9280     }
9281   };
9282 
9283   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9284   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9285                                  bool DirectInit) {
9286     // Parameters arguments are occassionially constructed with itself,
9287     // for instance, in recursive functions.  Skip them.
9288     if (isa<ParmVarDecl>(OrigDecl))
9289       return;
9290 
9291     E = E->IgnoreParens();
9292 
9293     // Skip checking T a = a where T is not a record or reference type.
9294     // Doing so is a way to silence uninitialized warnings.
9295     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9296       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9297         if (ICE->getCastKind() == CK_LValueToRValue)
9298           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9299             if (DRE->getDecl() == OrigDecl)
9300               return;
9301 
9302     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9303   }
9304 } // end anonymous namespace
9305 
9306 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9307                                             DeclarationName Name, QualType Type,
9308                                             TypeSourceInfo *TSI,
9309                                             SourceRange Range, bool DirectInit,
9310                                             Expr *Init) {
9311   bool IsInitCapture = !VDecl;
9312   assert((!VDecl || !VDecl->isInitCapture()) &&
9313          "init captures are expected to be deduced prior to initialization");
9314 
9315   ArrayRef<Expr *> DeduceInits = Init;
9316   if (DirectInit) {
9317     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9318       DeduceInits = PL->exprs();
9319     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9320       DeduceInits = IL->inits();
9321   }
9322 
9323   // Deduction only works if we have exactly one source expression.
9324   if (DeduceInits.empty()) {
9325     // It isn't possible to write this directly, but it is possible to
9326     // end up in this situation with "auto x(some_pack...);"
9327     Diag(Init->getLocStart(), IsInitCapture
9328                                   ? diag::err_init_capture_no_expression
9329                                   : diag::err_auto_var_init_no_expression)
9330         << Name << Type << Range;
9331     return QualType();
9332   }
9333 
9334   if (DeduceInits.size() > 1) {
9335     Diag(DeduceInits[1]->getLocStart(),
9336          IsInitCapture ? diag::err_init_capture_multiple_expressions
9337                        : diag::err_auto_var_init_multiple_expressions)
9338         << Name << Type << Range;
9339     return QualType();
9340   }
9341 
9342   Expr *DeduceInit = DeduceInits[0];
9343   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9344     Diag(Init->getLocStart(), IsInitCapture
9345                                   ? diag::err_init_capture_paren_braces
9346                                   : diag::err_auto_var_init_paren_braces)
9347         << isa<InitListExpr>(Init) << Name << Type << Range;
9348     return QualType();
9349   }
9350 
9351   // Expressions default to 'id' when we're in a debugger.
9352   bool DefaultedAnyToId = false;
9353   if (getLangOpts().DebuggerCastResultToId &&
9354       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9355     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9356     if (Result.isInvalid()) {
9357       return QualType();
9358     }
9359     Init = Result.get();
9360     DefaultedAnyToId = true;
9361   }
9362 
9363   QualType DeducedType;
9364   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9365     if (!IsInitCapture)
9366       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9367     else if (isa<InitListExpr>(Init))
9368       Diag(Range.getBegin(),
9369            diag::err_init_capture_deduction_failure_from_init_list)
9370           << Name
9371           << (DeduceInit->getType().isNull() ? TSI->getType()
9372                                              : DeduceInit->getType())
9373           << DeduceInit->getSourceRange();
9374     else
9375       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9376           << Name << TSI->getType()
9377           << (DeduceInit->getType().isNull() ? TSI->getType()
9378                                              : DeduceInit->getType())
9379           << DeduceInit->getSourceRange();
9380   }
9381 
9382   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9383   // 'id' instead of a specific object type prevents most of our usual
9384   // checks.
9385   // We only want to warn outside of template instantiations, though:
9386   // inside a template, the 'id' could have come from a parameter.
9387   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9388       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9389     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9390     Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9391   }
9392 
9393   return DeducedType;
9394 }
9395 
9396 /// AddInitializerToDecl - Adds the initializer Init to the
9397 /// declaration dcl. If DirectInit is true, this is C++ direct
9398 /// initialization rather than copy initialization.
9399 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9400                                 bool DirectInit, bool TypeMayContainAuto) {
9401   // If there is no declaration, there was an error parsing it.  Just ignore
9402   // the initializer.
9403   if (!RealDecl || RealDecl->isInvalidDecl()) {
9404     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9405     return;
9406   }
9407 
9408   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9409     // Pure-specifiers are handled in ActOnPureSpecifier.
9410     Diag(Method->getLocation(), diag::err_member_function_initialization)
9411       << Method->getDeclName() << Init->getSourceRange();
9412     Method->setInvalidDecl();
9413     return;
9414   }
9415 
9416   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9417   if (!VDecl) {
9418     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9419     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9420     RealDecl->setInvalidDecl();
9421     return;
9422   }
9423 
9424   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9425   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9426     // Attempt typo correction early so that the type of the init expression can
9427     // be deduced based on the chosen correction if the original init contains a
9428     // TypoExpr.
9429     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9430     if (!Res.isUsable()) {
9431       RealDecl->setInvalidDecl();
9432       return;
9433     }
9434     Init = Res.get();
9435 
9436     QualType DeducedType = deduceVarTypeFromInitializer(
9437         VDecl, VDecl->getDeclName(), VDecl->getType(),
9438         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9439     if (DeducedType.isNull()) {
9440       RealDecl->setInvalidDecl();
9441       return;
9442     }
9443 
9444     VDecl->setType(DeducedType);
9445     assert(VDecl->isLinkageValid());
9446 
9447     // In ARC, infer lifetime.
9448     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9449       VDecl->setInvalidDecl();
9450 
9451     // If this is a redeclaration, check that the type we just deduced matches
9452     // the previously declared type.
9453     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9454       // We never need to merge the type, because we cannot form an incomplete
9455       // array of auto, nor deduce such a type.
9456       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9457     }
9458 
9459     // Check the deduced type is valid for a variable declaration.
9460     CheckVariableDeclarationType(VDecl);
9461     if (VDecl->isInvalidDecl())
9462       return;
9463   }
9464 
9465   // dllimport cannot be used on variable definitions.
9466   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9467     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9468     VDecl->setInvalidDecl();
9469     return;
9470   }
9471 
9472   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9473     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9474     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9475     VDecl->setInvalidDecl();
9476     return;
9477   }
9478 
9479   if (!VDecl->getType()->isDependentType()) {
9480     // A definition must end up with a complete type, which means it must be
9481     // complete with the restriction that an array type might be completed by
9482     // the initializer; note that later code assumes this restriction.
9483     QualType BaseDeclType = VDecl->getType();
9484     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9485       BaseDeclType = Array->getElementType();
9486     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9487                             diag::err_typecheck_decl_incomplete_type)) {
9488       RealDecl->setInvalidDecl();
9489       return;
9490     }
9491 
9492     // The variable can not have an abstract class type.
9493     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9494                                diag::err_abstract_type_in_decl,
9495                                AbstractVariableType))
9496       VDecl->setInvalidDecl();
9497   }
9498 
9499   VarDecl *Def;
9500   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9501     NamedDecl *Hidden = nullptr;
9502     if (!hasVisibleDefinition(Def, &Hidden) &&
9503         (VDecl->getFormalLinkage() == InternalLinkage ||
9504          VDecl->getDescribedVarTemplate() ||
9505          VDecl->getNumTemplateParameterLists() ||
9506          VDecl->getDeclContext()->isDependentContext())) {
9507       // The previous definition is hidden, and multiple definitions are
9508       // permitted (in separate TUs). Form another definition of it.
9509     } else {
9510       Diag(VDecl->getLocation(), diag::err_redefinition)
9511         << VDecl->getDeclName();
9512       Diag(Def->getLocation(), diag::note_previous_definition);
9513       VDecl->setInvalidDecl();
9514       return;
9515     }
9516   }
9517 
9518   if (getLangOpts().CPlusPlus) {
9519     // C++ [class.static.data]p4
9520     //   If a static data member is of const integral or const
9521     //   enumeration type, its declaration in the class definition can
9522     //   specify a constant-initializer which shall be an integral
9523     //   constant expression (5.19). In that case, the member can appear
9524     //   in integral constant expressions. The member shall still be
9525     //   defined in a namespace scope if it is used in the program and the
9526     //   namespace scope definition shall not contain an initializer.
9527     //
9528     // We already performed a redefinition check above, but for static
9529     // data members we also need to check whether there was an in-class
9530     // declaration with an initializer.
9531     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9532       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9533           << VDecl->getDeclName();
9534       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9535            diag::note_previous_initializer)
9536           << 0;
9537       return;
9538     }
9539 
9540     if (VDecl->hasLocalStorage())
9541       getCurFunction()->setHasBranchProtectedScope();
9542 
9543     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9544       VDecl->setInvalidDecl();
9545       return;
9546     }
9547   }
9548 
9549   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9550   // a kernel function cannot be initialized."
9551   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9552     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9553     VDecl->setInvalidDecl();
9554     return;
9555   }
9556 
9557   // Get the decls type and save a reference for later, since
9558   // CheckInitializerTypes may change it.
9559   QualType DclT = VDecl->getType(), SavT = DclT;
9560 
9561   // Expressions default to 'id' when we're in a debugger
9562   // and we are assigning it to a variable of Objective-C pointer type.
9563   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9564       Init->getType() == Context.UnknownAnyTy) {
9565     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9566     if (Result.isInvalid()) {
9567       VDecl->setInvalidDecl();
9568       return;
9569     }
9570     Init = Result.get();
9571   }
9572 
9573   // Perform the initialization.
9574   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9575   if (!VDecl->isInvalidDecl()) {
9576     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9577     InitializationKind Kind =
9578         DirectInit
9579             ? CXXDirectInit
9580                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9581                                                      Init->getLocStart(),
9582                                                      Init->getLocEnd())
9583                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9584             : InitializationKind::CreateCopy(VDecl->getLocation(),
9585                                              Init->getLocStart());
9586 
9587     MultiExprArg Args = Init;
9588     if (CXXDirectInit)
9589       Args = MultiExprArg(CXXDirectInit->getExprs(),
9590                           CXXDirectInit->getNumExprs());
9591 
9592     // Try to correct any TypoExprs in the initialization arguments.
9593     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9594       ExprResult Res = CorrectDelayedTyposInExpr(
9595           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9596             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9597             return Init.Failed() ? ExprError() : E;
9598           });
9599       if (Res.isInvalid()) {
9600         VDecl->setInvalidDecl();
9601       } else if (Res.get() != Args[Idx]) {
9602         Args[Idx] = Res.get();
9603       }
9604     }
9605     if (VDecl->isInvalidDecl())
9606       return;
9607 
9608     InitializationSequence InitSeq(*this, Entity, Kind, Args,
9609                                    /*TopLevelOfInitList=*/false,
9610                                    /*TreatUnavailableAsInvalid=*/false);
9611     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9612     if (Result.isInvalid()) {
9613       VDecl->setInvalidDecl();
9614       return;
9615     }
9616 
9617     Init = Result.getAs<Expr>();
9618   }
9619 
9620   // Check for self-references within variable initializers.
9621   // Variables declared within a function/method body (except for references)
9622   // are handled by a dataflow analysis.
9623   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9624       VDecl->getType()->isReferenceType()) {
9625     CheckSelfReference(*this, RealDecl, Init, DirectInit);
9626   }
9627 
9628   // If the type changed, it means we had an incomplete type that was
9629   // completed by the initializer. For example:
9630   //   int ary[] = { 1, 3, 5 };
9631   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9632   if (!VDecl->isInvalidDecl() && (DclT != SavT))
9633     VDecl->setType(DclT);
9634 
9635   if (!VDecl->isInvalidDecl()) {
9636     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9637 
9638     if (VDecl->hasAttr<BlocksAttr>())
9639       checkRetainCycles(VDecl, Init);
9640 
9641     // It is safe to assign a weak reference into a strong variable.
9642     // Although this code can still have problems:
9643     //   id x = self.weakProp;
9644     //   id y = self.weakProp;
9645     // we do not warn to warn spuriously when 'x' and 'y' are on separate
9646     // paths through the function. This should be revisited if
9647     // -Wrepeated-use-of-weak is made flow-sensitive.
9648     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9649         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9650                          Init->getLocStart()))
9651       getCurFunction()->markSafeWeakUse(Init);
9652   }
9653 
9654   // The initialization is usually a full-expression.
9655   //
9656   // FIXME: If this is a braced initialization of an aggregate, it is not
9657   // an expression, and each individual field initializer is a separate
9658   // full-expression. For instance, in:
9659   //
9660   //   struct Temp { ~Temp(); };
9661   //   struct S { S(Temp); };
9662   //   struct T { S a, b; } t = { Temp(), Temp() }
9663   //
9664   // we should destroy the first Temp before constructing the second.
9665   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9666                                           false,
9667                                           VDecl->isConstexpr());
9668   if (Result.isInvalid()) {
9669     VDecl->setInvalidDecl();
9670     return;
9671   }
9672   Init = Result.get();
9673 
9674   // Attach the initializer to the decl.
9675   VDecl->setInit(Init);
9676 
9677   if (VDecl->isLocalVarDecl()) {
9678     // C99 6.7.8p4: All the expressions in an initializer for an object that has
9679     // static storage duration shall be constant expressions or string literals.
9680     // C++ does not have this restriction.
9681     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9682       const Expr *Culprit;
9683       if (VDecl->getStorageClass() == SC_Static)
9684         CheckForConstantInitializer(Init, DclT);
9685       // C89 is stricter than C99 for non-static aggregate types.
9686       // C89 6.5.7p3: All the expressions [...] in an initializer list
9687       // for an object that has aggregate or union type shall be
9688       // constant expressions.
9689       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9690                isa<InitListExpr>(Init) &&
9691                !Init->isConstantInitializer(Context, false, &Culprit))
9692         Diag(Culprit->getExprLoc(),
9693              diag::ext_aggregate_init_not_constant)
9694           << Culprit->getSourceRange();
9695     }
9696   } else if (VDecl->isStaticDataMember() &&
9697              VDecl->getLexicalDeclContext()->isRecord()) {
9698     // This is an in-class initialization for a static data member, e.g.,
9699     //
9700     // struct S {
9701     //   static const int value = 17;
9702     // };
9703 
9704     // C++ [class.mem]p4:
9705     //   A member-declarator can contain a constant-initializer only
9706     //   if it declares a static member (9.4) of const integral or
9707     //   const enumeration type, see 9.4.2.
9708     //
9709     // C++11 [class.static.data]p3:
9710     //   If a non-volatile const static data member is of integral or
9711     //   enumeration type, its declaration in the class definition can
9712     //   specify a brace-or-equal-initializer in which every initalizer-clause
9713     //   that is an assignment-expression is a constant expression. A static
9714     //   data member of literal type can be declared in the class definition
9715     //   with the constexpr specifier; if so, its declaration shall specify a
9716     //   brace-or-equal-initializer in which every initializer-clause that is
9717     //   an assignment-expression is a constant expression.
9718 
9719     // Do nothing on dependent types.
9720     if (DclT->isDependentType()) {
9721 
9722     // Allow any 'static constexpr' members, whether or not they are of literal
9723     // type. We separately check that every constexpr variable is of literal
9724     // type.
9725     } else if (VDecl->isConstexpr()) {
9726 
9727     // Require constness.
9728     } else if (!DclT.isConstQualified()) {
9729       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9730         << Init->getSourceRange();
9731       VDecl->setInvalidDecl();
9732 
9733     // We allow integer constant expressions in all cases.
9734     } else if (DclT->isIntegralOrEnumerationType()) {
9735       // Check whether the expression is a constant expression.
9736       SourceLocation Loc;
9737       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9738         // In C++11, a non-constexpr const static data member with an
9739         // in-class initializer cannot be volatile.
9740         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9741       else if (Init->isValueDependent())
9742         ; // Nothing to check.
9743       else if (Init->isIntegerConstantExpr(Context, &Loc))
9744         ; // Ok, it's an ICE!
9745       else if (Init->isEvaluatable(Context)) {
9746         // If we can constant fold the initializer through heroics, accept it,
9747         // but report this as a use of an extension for -pedantic.
9748         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9749           << Init->getSourceRange();
9750       } else {
9751         // Otherwise, this is some crazy unknown case.  Report the issue at the
9752         // location provided by the isIntegerConstantExpr failed check.
9753         Diag(Loc, diag::err_in_class_initializer_non_constant)
9754           << Init->getSourceRange();
9755         VDecl->setInvalidDecl();
9756       }
9757 
9758     // We allow foldable floating-point constants as an extension.
9759     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9760       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9761       // it anyway and provide a fixit to add the 'constexpr'.
9762       if (getLangOpts().CPlusPlus11) {
9763         Diag(VDecl->getLocation(),
9764              diag::ext_in_class_initializer_float_type_cxx11)
9765             << DclT << Init->getSourceRange();
9766         Diag(VDecl->getLocStart(),
9767              diag::note_in_class_initializer_float_type_cxx11)
9768             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9769       } else {
9770         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9771           << DclT << Init->getSourceRange();
9772 
9773         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9774           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9775             << Init->getSourceRange();
9776           VDecl->setInvalidDecl();
9777         }
9778       }
9779 
9780     // Suggest adding 'constexpr' in C++11 for literal types.
9781     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9782       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9783         << DclT << Init->getSourceRange()
9784         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9785       VDecl->setConstexpr(true);
9786 
9787     } else {
9788       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9789         << DclT << Init->getSourceRange();
9790       VDecl->setInvalidDecl();
9791     }
9792   } else if (VDecl->isFileVarDecl()) {
9793     if (VDecl->getStorageClass() == SC_Extern &&
9794         (!getLangOpts().CPlusPlus ||
9795          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9796            VDecl->isExternC())) &&
9797         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9798       Diag(VDecl->getLocation(), diag::warn_extern_init);
9799 
9800     // C99 6.7.8p4. All file scoped initializers need to be constant.
9801     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9802       CheckForConstantInitializer(Init, DclT);
9803   }
9804 
9805   // We will represent direct-initialization similarly to copy-initialization:
9806   //    int x(1);  -as-> int x = 1;
9807   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9808   //
9809   // Clients that want to distinguish between the two forms, can check for
9810   // direct initializer using VarDecl::getInitStyle().
9811   // A major benefit is that clients that don't particularly care about which
9812   // exactly form was it (like the CodeGen) can handle both cases without
9813   // special case code.
9814 
9815   // C++ 8.5p11:
9816   // The form of initialization (using parentheses or '=') is generally
9817   // insignificant, but does matter when the entity being initialized has a
9818   // class type.
9819   if (CXXDirectInit) {
9820     assert(DirectInit && "Call-style initializer must be direct init.");
9821     VDecl->setInitStyle(VarDecl::CallInit);
9822   } else if (DirectInit) {
9823     // This must be list-initialization. No other way is direct-initialization.
9824     VDecl->setInitStyle(VarDecl::ListInit);
9825   }
9826 
9827   CheckCompleteVariableDeclaration(VDecl);
9828 }
9829 
9830 /// ActOnInitializerError - Given that there was an error parsing an
9831 /// initializer for the given declaration, try to return to some form
9832 /// of sanity.
9833 void Sema::ActOnInitializerError(Decl *D) {
9834   // Our main concern here is re-establishing invariants like "a
9835   // variable's type is either dependent or complete".
9836   if (!D || D->isInvalidDecl()) return;
9837 
9838   VarDecl *VD = dyn_cast<VarDecl>(D);
9839   if (!VD) return;
9840 
9841   // Auto types are meaningless if we can't make sense of the initializer.
9842   if (ParsingInitForAutoVars.count(D)) {
9843     D->setInvalidDecl();
9844     return;
9845   }
9846 
9847   QualType Ty = VD->getType();
9848   if (Ty->isDependentType()) return;
9849 
9850   // Require a complete type.
9851   if (RequireCompleteType(VD->getLocation(),
9852                           Context.getBaseElementType(Ty),
9853                           diag::err_typecheck_decl_incomplete_type)) {
9854     VD->setInvalidDecl();
9855     return;
9856   }
9857 
9858   // Require a non-abstract type.
9859   if (RequireNonAbstractType(VD->getLocation(), Ty,
9860                              diag::err_abstract_type_in_decl,
9861                              AbstractVariableType)) {
9862     VD->setInvalidDecl();
9863     return;
9864   }
9865 
9866   // Don't bother complaining about constructors or destructors,
9867   // though.
9868 }
9869 
9870 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9871                                   bool TypeMayContainAuto) {
9872   // If there is no declaration, there was an error parsing it. Just ignore it.
9873   if (!RealDecl)
9874     return;
9875 
9876   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9877     QualType Type = Var->getType();
9878 
9879     // C++11 [dcl.spec.auto]p3
9880     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9881       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9882         << Var->getDeclName() << Type;
9883       Var->setInvalidDecl();
9884       return;
9885     }
9886 
9887     // C++11 [class.static.data]p3: A static data member can be declared with
9888     // the constexpr specifier; if so, its declaration shall specify
9889     // a brace-or-equal-initializer.
9890     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9891     // the definition of a variable [...] or the declaration of a static data
9892     // member.
9893     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9894       if (Var->isStaticDataMember())
9895         Diag(Var->getLocation(),
9896              diag::err_constexpr_static_mem_var_requires_init)
9897           << Var->getDeclName();
9898       else
9899         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9900       Var->setInvalidDecl();
9901       return;
9902     }
9903 
9904     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
9905     // definition having the concept specifier is called a variable concept. A
9906     // concept definition refers to [...] a variable concept and its initializer.
9907     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
9908       if (VTD->isConcept()) {
9909         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
9910         Var->setInvalidDecl();
9911         return;
9912       }
9913     }
9914 
9915     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9916     // be initialized.
9917     if (!Var->isInvalidDecl() &&
9918         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9919         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9920       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9921       Var->setInvalidDecl();
9922       return;
9923     }
9924 
9925     switch (Var->isThisDeclarationADefinition()) {
9926     case VarDecl::Definition:
9927       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9928         break;
9929 
9930       // We have an out-of-line definition of a static data member
9931       // that has an in-class initializer, so we type-check this like
9932       // a declaration.
9933       //
9934       // Fall through
9935 
9936     case VarDecl::DeclarationOnly:
9937       // It's only a declaration.
9938 
9939       // Block scope. C99 6.7p7: If an identifier for an object is
9940       // declared with no linkage (C99 6.2.2p6), the type for the
9941       // object shall be complete.
9942       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9943           !Var->hasLinkage() && !Var->isInvalidDecl() &&
9944           RequireCompleteType(Var->getLocation(), Type,
9945                               diag::err_typecheck_decl_incomplete_type))
9946         Var->setInvalidDecl();
9947 
9948       // Make sure that the type is not abstract.
9949       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9950           RequireNonAbstractType(Var->getLocation(), Type,
9951                                  diag::err_abstract_type_in_decl,
9952                                  AbstractVariableType))
9953         Var->setInvalidDecl();
9954       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9955           Var->getStorageClass() == SC_PrivateExtern) {
9956         Diag(Var->getLocation(), diag::warn_private_extern);
9957         Diag(Var->getLocation(), diag::note_private_extern);
9958       }
9959 
9960       return;
9961 
9962     case VarDecl::TentativeDefinition:
9963       // File scope. C99 6.9.2p2: A declaration of an identifier for an
9964       // object that has file scope without an initializer, and without a
9965       // storage-class specifier or with the storage-class specifier "static",
9966       // constitutes a tentative definition. Note: A tentative definition with
9967       // external linkage is valid (C99 6.2.2p5).
9968       if (!Var->isInvalidDecl()) {
9969         if (const IncompleteArrayType *ArrayT
9970                                     = Context.getAsIncompleteArrayType(Type)) {
9971           if (RequireCompleteType(Var->getLocation(),
9972                                   ArrayT->getElementType(),
9973                                   diag::err_illegal_decl_array_incomplete_type))
9974             Var->setInvalidDecl();
9975         } else if (Var->getStorageClass() == SC_Static) {
9976           // C99 6.9.2p3: If the declaration of an identifier for an object is
9977           // a tentative definition and has internal linkage (C99 6.2.2p3), the
9978           // declared type shall not be an incomplete type.
9979           // NOTE: code such as the following
9980           //     static struct s;
9981           //     struct s { int a; };
9982           // is accepted by gcc. Hence here we issue a warning instead of
9983           // an error and we do not invalidate the static declaration.
9984           // NOTE: to avoid multiple warnings, only check the first declaration.
9985           if (Var->isFirstDecl())
9986             RequireCompleteType(Var->getLocation(), Type,
9987                                 diag::ext_typecheck_decl_incomplete_type);
9988         }
9989       }
9990 
9991       // Record the tentative definition; we're done.
9992       if (!Var->isInvalidDecl())
9993         TentativeDefinitions.push_back(Var);
9994       return;
9995     }
9996 
9997     // Provide a specific diagnostic for uninitialized variable
9998     // definitions with incomplete array type.
9999     if (Type->isIncompleteArrayType()) {
10000       Diag(Var->getLocation(),
10001            diag::err_typecheck_incomplete_array_needs_initializer);
10002       Var->setInvalidDecl();
10003       return;
10004     }
10005 
10006     // Provide a specific diagnostic for uninitialized variable
10007     // definitions with reference type.
10008     if (Type->isReferenceType()) {
10009       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10010         << Var->getDeclName()
10011         << SourceRange(Var->getLocation(), Var->getLocation());
10012       Var->setInvalidDecl();
10013       return;
10014     }
10015 
10016     // Do not attempt to type-check the default initializer for a
10017     // variable with dependent type.
10018     if (Type->isDependentType())
10019       return;
10020 
10021     if (Var->isInvalidDecl())
10022       return;
10023 
10024     if (!Var->hasAttr<AliasAttr>()) {
10025       if (RequireCompleteType(Var->getLocation(),
10026                               Context.getBaseElementType(Type),
10027                               diag::err_typecheck_decl_incomplete_type)) {
10028         Var->setInvalidDecl();
10029         return;
10030       }
10031     } else {
10032       return;
10033     }
10034 
10035     // The variable can not have an abstract class type.
10036     if (RequireNonAbstractType(Var->getLocation(), Type,
10037                                diag::err_abstract_type_in_decl,
10038                                AbstractVariableType)) {
10039       Var->setInvalidDecl();
10040       return;
10041     }
10042 
10043     // Check for jumps past the implicit initializer.  C++0x
10044     // clarifies that this applies to a "variable with automatic
10045     // storage duration", not a "local variable".
10046     // C++11 [stmt.dcl]p3
10047     //   A program that jumps from a point where a variable with automatic
10048     //   storage duration is not in scope to a point where it is in scope is
10049     //   ill-formed unless the variable has scalar type, class type with a
10050     //   trivial default constructor and a trivial destructor, a cv-qualified
10051     //   version of one of these types, or an array of one of the preceding
10052     //   types and is declared without an initializer.
10053     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10054       if (const RecordType *Record
10055             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10056         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10057         // Mark the function for further checking even if the looser rules of
10058         // C++11 do not require such checks, so that we can diagnose
10059         // incompatibilities with C++98.
10060         if (!CXXRecord->isPOD())
10061           getCurFunction()->setHasBranchProtectedScope();
10062       }
10063     }
10064 
10065     // C++03 [dcl.init]p9:
10066     //   If no initializer is specified for an object, and the
10067     //   object is of (possibly cv-qualified) non-POD class type (or
10068     //   array thereof), the object shall be default-initialized; if
10069     //   the object is of const-qualified type, the underlying class
10070     //   type shall have a user-declared default
10071     //   constructor. Otherwise, if no initializer is specified for
10072     //   a non- static object, the object and its subobjects, if
10073     //   any, have an indeterminate initial value); if the object
10074     //   or any of its subobjects are of const-qualified type, the
10075     //   program is ill-formed.
10076     // C++0x [dcl.init]p11:
10077     //   If no initializer is specified for an object, the object is
10078     //   default-initialized; [...].
10079     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10080     InitializationKind Kind
10081       = InitializationKind::CreateDefault(Var->getLocation());
10082 
10083     InitializationSequence InitSeq(*this, Entity, Kind, None);
10084     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10085     if (Init.isInvalid())
10086       Var->setInvalidDecl();
10087     else if (Init.get()) {
10088       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10089       // This is important for template substitution.
10090       Var->setInitStyle(VarDecl::CallInit);
10091     }
10092 
10093     CheckCompleteVariableDeclaration(Var);
10094   }
10095 }
10096 
10097 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10098   // If there is no declaration, there was an error parsing it. Ignore it.
10099   if (!D)
10100     return;
10101 
10102   VarDecl *VD = dyn_cast<VarDecl>(D);
10103   if (!VD) {
10104     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10105     D->setInvalidDecl();
10106     return;
10107   }
10108 
10109   VD->setCXXForRangeDecl(true);
10110 
10111   // for-range-declaration cannot be given a storage class specifier.
10112   int Error = -1;
10113   switch (VD->getStorageClass()) {
10114   case SC_None:
10115     break;
10116   case SC_Extern:
10117     Error = 0;
10118     break;
10119   case SC_Static:
10120     Error = 1;
10121     break;
10122   case SC_PrivateExtern:
10123     Error = 2;
10124     break;
10125   case SC_Auto:
10126     Error = 3;
10127     break;
10128   case SC_Register:
10129     Error = 4;
10130     break;
10131   }
10132   if (Error != -1) {
10133     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10134       << VD->getDeclName() << Error;
10135     D->setInvalidDecl();
10136   }
10137 }
10138 
10139 StmtResult
10140 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10141                                  IdentifierInfo *Ident,
10142                                  ParsedAttributes &Attrs,
10143                                  SourceLocation AttrEnd) {
10144   // C++1y [stmt.iter]p1:
10145   //   A range-based for statement of the form
10146   //      for ( for-range-identifier : for-range-initializer ) statement
10147   //   is equivalent to
10148   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10149   DeclSpec DS(Attrs.getPool().getFactory());
10150 
10151   const char *PrevSpec;
10152   unsigned DiagID;
10153   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10154                      getPrintingPolicy());
10155 
10156   Declarator D(DS, Declarator::ForContext);
10157   D.SetIdentifier(Ident, IdentLoc);
10158   D.takeAttributes(Attrs, AttrEnd);
10159 
10160   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10161   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10162                 EmptyAttrs, IdentLoc);
10163   Decl *Var = ActOnDeclarator(S, D);
10164   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10165   FinalizeDeclaration(Var);
10166   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10167                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10168 }
10169 
10170 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10171   if (var->isInvalidDecl()) return;
10172 
10173   if (getLangOpts().OpenCL) {
10174     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10175     // initialiser
10176     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10177         !var->hasInit()) {
10178       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10179           << 1 /*Init*/;
10180       var->setInvalidDecl();
10181       return;
10182     }
10183   }
10184 
10185   // In Objective-C, don't allow jumps past the implicit initialization of a
10186   // local retaining variable.
10187   if (getLangOpts().ObjC1 &&
10188       var->hasLocalStorage()) {
10189     switch (var->getType().getObjCLifetime()) {
10190     case Qualifiers::OCL_None:
10191     case Qualifiers::OCL_ExplicitNone:
10192     case Qualifiers::OCL_Autoreleasing:
10193       break;
10194 
10195     case Qualifiers::OCL_Weak:
10196     case Qualifiers::OCL_Strong:
10197       getCurFunction()->setHasBranchProtectedScope();
10198       break;
10199     }
10200   }
10201 
10202   // Warn about externally-visible variables being defined without a
10203   // prior declaration.  We only want to do this for global
10204   // declarations, but we also specifically need to avoid doing it for
10205   // class members because the linkage of an anonymous class can
10206   // change if it's later given a typedef name.
10207   if (var->isThisDeclarationADefinition() &&
10208       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10209       var->isExternallyVisible() && var->hasLinkage() &&
10210       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10211                                   var->getLocation())) {
10212     // Find a previous declaration that's not a definition.
10213     VarDecl *prev = var->getPreviousDecl();
10214     while (prev && prev->isThisDeclarationADefinition())
10215       prev = prev->getPreviousDecl();
10216 
10217     if (!prev)
10218       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10219   }
10220 
10221   if (var->getTLSKind() == VarDecl::TLS_Static) {
10222     const Expr *Culprit;
10223     if (var->getType().isDestructedType()) {
10224       // GNU C++98 edits for __thread, [basic.start.term]p3:
10225       //   The type of an object with thread storage duration shall not
10226       //   have a non-trivial destructor.
10227       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10228       if (getLangOpts().CPlusPlus11)
10229         Diag(var->getLocation(), diag::note_use_thread_local);
10230     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
10231                !var->getInit()->isConstantInitializer(
10232                    Context, var->getType()->isReferenceType(), &Culprit)) {
10233       // GNU C++98 edits for __thread, [basic.start.init]p4:
10234       //   An object of thread storage duration shall not require dynamic
10235       //   initialization.
10236       // FIXME: Need strict checking here.
10237       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
10238         << Culprit->getSourceRange();
10239       if (getLangOpts().CPlusPlus11)
10240         Diag(var->getLocation(), diag::note_use_thread_local);
10241     }
10242   }
10243 
10244   // Apply section attributes and pragmas to global variables.
10245   bool GlobalStorage = var->hasGlobalStorage();
10246   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10247       ActiveTemplateInstantiations.empty()) {
10248     PragmaStack<StringLiteral *> *Stack = nullptr;
10249     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10250     if (var->getType().isConstQualified())
10251       Stack = &ConstSegStack;
10252     else if (!var->getInit()) {
10253       Stack = &BSSSegStack;
10254       SectionFlags |= ASTContext::PSF_Write;
10255     } else {
10256       Stack = &DataSegStack;
10257       SectionFlags |= ASTContext::PSF_Write;
10258     }
10259     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10260       var->addAttr(SectionAttr::CreateImplicit(
10261           Context, SectionAttr::Declspec_allocate,
10262           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10263     }
10264     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10265       if (UnifySection(SA->getName(), SectionFlags, var))
10266         var->dropAttr<SectionAttr>();
10267 
10268     // Apply the init_seg attribute if this has an initializer.  If the
10269     // initializer turns out to not be dynamic, we'll end up ignoring this
10270     // attribute.
10271     if (CurInitSeg && var->getInit())
10272       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10273                                                CurInitSegLoc));
10274   }
10275 
10276   // All the following checks are C++ only.
10277   if (!getLangOpts().CPlusPlus) return;
10278 
10279   QualType type = var->getType();
10280   if (type->isDependentType()) return;
10281 
10282   // __block variables might require us to capture a copy-initializer.
10283   if (var->hasAttr<BlocksAttr>()) {
10284     // It's currently invalid to ever have a __block variable with an
10285     // array type; should we diagnose that here?
10286 
10287     // Regardless, we don't want to ignore array nesting when
10288     // constructing this copy.
10289     if (type->isStructureOrClassType()) {
10290       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10291       SourceLocation poi = var->getLocation();
10292       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10293       ExprResult result
10294         = PerformMoveOrCopyInitialization(
10295             InitializedEntity::InitializeBlock(poi, type, false),
10296             var, var->getType(), varRef, /*AllowNRVO=*/true);
10297       if (!result.isInvalid()) {
10298         result = MaybeCreateExprWithCleanups(result);
10299         Expr *init = result.getAs<Expr>();
10300         Context.setBlockVarCopyInits(var, init);
10301       }
10302     }
10303   }
10304 
10305   Expr *Init = var->getInit();
10306   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10307   QualType baseType = Context.getBaseElementType(type);
10308 
10309   if (!var->getDeclContext()->isDependentContext() &&
10310       Init && !Init->isValueDependent()) {
10311     if (IsGlobal && !var->isConstexpr() &&
10312         !getDiagnostics().isIgnored(diag::warn_global_constructor,
10313                                     var->getLocation())) {
10314       // Warn about globals which don't have a constant initializer.  Don't
10315       // warn about globals with a non-trivial destructor because we already
10316       // warned about them.
10317       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10318       if (!(RD && !RD->hasTrivialDestructor()) &&
10319           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10320         Diag(var->getLocation(), diag::warn_global_constructor)
10321           << Init->getSourceRange();
10322     }
10323 
10324     if (var->isConstexpr()) {
10325       SmallVector<PartialDiagnosticAt, 8> Notes;
10326       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10327         SourceLocation DiagLoc = var->getLocation();
10328         // If the note doesn't add any useful information other than a source
10329         // location, fold it into the primary diagnostic.
10330         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10331               diag::note_invalid_subexpr_in_const_expr) {
10332           DiagLoc = Notes[0].first;
10333           Notes.clear();
10334         }
10335         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10336           << var << Init->getSourceRange();
10337         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10338           Diag(Notes[I].first, Notes[I].second);
10339       }
10340     } else if (var->isUsableInConstantExpressions(Context)) {
10341       // Check whether the initializer of a const variable of integral or
10342       // enumeration type is an ICE now, since we can't tell whether it was
10343       // initialized by a constant expression if we check later.
10344       var->checkInitIsICE();
10345     }
10346   }
10347 
10348   // Require the destructor.
10349   if (const RecordType *recordType = baseType->getAs<RecordType>())
10350     FinalizeVarWithDestructor(var, recordType);
10351 }
10352 
10353 /// \brief Determines if a variable's alignment is dependent.
10354 static bool hasDependentAlignment(VarDecl *VD) {
10355   if (VD->getType()->isDependentType())
10356     return true;
10357   for (auto *I : VD->specific_attrs<AlignedAttr>())
10358     if (I->isAlignmentDependent())
10359       return true;
10360   return false;
10361 }
10362 
10363 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10364 /// any semantic actions necessary after any initializer has been attached.
10365 void
10366 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10367   // Note that we are no longer parsing the initializer for this declaration.
10368   ParsingInitForAutoVars.erase(ThisDecl);
10369 
10370   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10371   if (!VD)
10372     return;
10373 
10374   checkAttributesAfterMerging(*this, *VD);
10375 
10376   // Perform TLS alignment check here after attributes attached to the variable
10377   // which may affect the alignment have been processed. Only perform the check
10378   // if the target has a maximum TLS alignment (zero means no constraints).
10379   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10380     // Protect the check so that it's not performed on dependent types and
10381     // dependent alignments (we can't determine the alignment in that case).
10382     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10383       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10384       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10385         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10386           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10387           << (unsigned)MaxAlignChars.getQuantity();
10388       }
10389     }
10390   }
10391 
10392   // Static locals inherit dll attributes from their function.
10393   if (VD->isStaticLocal()) {
10394     if (FunctionDecl *FD =
10395             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10396       if (Attr *A = getDLLAttr(FD)) {
10397         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10398         NewAttr->setInherited(true);
10399         VD->addAttr(NewAttr);
10400       }
10401     }
10402   }
10403 
10404   // Perform check for initializers of device-side global variables.
10405   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10406   // 7.5). CUDA also allows constant initializers for __constant__ and
10407   // __device__ variables.
10408   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
10409     const Expr *Init = VD->getInit();
10410     const bool IsGlobal = VD->hasGlobalStorage() && !VD->isStaticLocal();
10411     if (Init && IsGlobal &&
10412         (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10413          VD->hasAttr<CUDASharedAttr>())) {
10414       bool AllowedInit = false;
10415       if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10416         AllowedInit =
10417             isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10418       // We'll allow constant initializers even if it's a non-empty
10419       // constructor according to CUDA rules. This deviates from NVCC,
10420       // but allows us to handle things like constexpr constructors.
10421       if (!AllowedInit &&
10422           (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10423         AllowedInit = VD->getInit()->isConstantInitializer(
10424             Context, VD->getType()->isReferenceType());
10425 
10426       if (!AllowedInit) {
10427         Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10428                                     ? diag::err_shared_var_init
10429                                     : diag::err_dynamic_var_init)
10430             << Init->getSourceRange();
10431         VD->setInvalidDecl();
10432       }
10433     }
10434   }
10435 
10436   // Grab the dllimport or dllexport attribute off of the VarDecl.
10437   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10438 
10439   // Imported static data members cannot be defined out-of-line.
10440   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10441     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10442         VD->isThisDeclarationADefinition()) {
10443       // We allow definitions of dllimport class template static data members
10444       // with a warning.
10445       CXXRecordDecl *Context =
10446         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10447       bool IsClassTemplateMember =
10448           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10449           Context->getDescribedClassTemplate();
10450 
10451       Diag(VD->getLocation(),
10452            IsClassTemplateMember
10453                ? diag::warn_attribute_dllimport_static_field_definition
10454                : diag::err_attribute_dllimport_static_field_definition);
10455       Diag(IA->getLocation(), diag::note_attribute);
10456       if (!IsClassTemplateMember)
10457         VD->setInvalidDecl();
10458     }
10459   }
10460 
10461   // dllimport/dllexport variables cannot be thread local, their TLS index
10462   // isn't exported with the variable.
10463   if (DLLAttr && VD->getTLSKind()) {
10464     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10465     if (F && getDLLAttr(F)) {
10466       assert(VD->isStaticLocal());
10467       // But if this is a static local in a dlimport/dllexport function, the
10468       // function will never be inlined, which means the var would never be
10469       // imported, so having it marked import/export is safe.
10470     } else {
10471       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10472                                                                     << DLLAttr;
10473       VD->setInvalidDecl();
10474     }
10475   }
10476 
10477   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10478     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10479       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10480       VD->dropAttr<UsedAttr>();
10481     }
10482   }
10483 
10484   const DeclContext *DC = VD->getDeclContext();
10485   // If there's a #pragma GCC visibility in scope, and this isn't a class
10486   // member, set the visibility of this variable.
10487   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10488     AddPushedVisibilityAttribute(VD);
10489 
10490   // FIXME: Warn on unused templates.
10491   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10492       !isa<VarTemplatePartialSpecializationDecl>(VD))
10493     MarkUnusedFileScopedDecl(VD);
10494 
10495   // Now we have parsed the initializer and can update the table of magic
10496   // tag values.
10497   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10498       !VD->getType()->isIntegralOrEnumerationType())
10499     return;
10500 
10501   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10502     const Expr *MagicValueExpr = VD->getInit();
10503     if (!MagicValueExpr) {
10504       continue;
10505     }
10506     llvm::APSInt MagicValueInt;
10507     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10508       Diag(I->getRange().getBegin(),
10509            diag::err_type_tag_for_datatype_not_ice)
10510         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10511       continue;
10512     }
10513     if (MagicValueInt.getActiveBits() > 64) {
10514       Diag(I->getRange().getBegin(),
10515            diag::err_type_tag_for_datatype_too_large)
10516         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10517       continue;
10518     }
10519     uint64_t MagicValue = MagicValueInt.getZExtValue();
10520     RegisterTypeTagForDatatype(I->getArgumentKind(),
10521                                MagicValue,
10522                                I->getMatchingCType(),
10523                                I->getLayoutCompatible(),
10524                                I->getMustBeNull());
10525   }
10526 }
10527 
10528 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10529                                                    ArrayRef<Decl *> Group) {
10530   SmallVector<Decl*, 8> Decls;
10531 
10532   if (DS.isTypeSpecOwned())
10533     Decls.push_back(DS.getRepAsDecl());
10534 
10535   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10536   for (unsigned i = 0, e = Group.size(); i != e; ++i)
10537     if (Decl *D = Group[i]) {
10538       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10539         if (!FirstDeclaratorInGroup)
10540           FirstDeclaratorInGroup = DD;
10541       Decls.push_back(D);
10542     }
10543 
10544   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10545     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10546       handleTagNumbering(Tag, S);
10547       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10548           getLangOpts().CPlusPlus)
10549         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10550     }
10551   }
10552 
10553   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10554 }
10555 
10556 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10557 /// group, performing any necessary semantic checking.
10558 Sema::DeclGroupPtrTy
10559 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10560                            bool TypeMayContainAuto) {
10561   // C++0x [dcl.spec.auto]p7:
10562   //   If the type deduced for the template parameter U is not the same in each
10563   //   deduction, the program is ill-formed.
10564   // FIXME: When initializer-list support is added, a distinction is needed
10565   // between the deduced type U and the deduced type which 'auto' stands for.
10566   //   auto a = 0, b = { 1, 2, 3 };
10567   // is legal because the deduced type U is 'int' in both cases.
10568   if (TypeMayContainAuto && Group.size() > 1) {
10569     QualType Deduced;
10570     CanQualType DeducedCanon;
10571     VarDecl *DeducedDecl = nullptr;
10572     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10573       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10574         AutoType *AT = D->getType()->getContainedAutoType();
10575         // Don't reissue diagnostics when instantiating a template.
10576         if (AT && D->isInvalidDecl())
10577           break;
10578         QualType U = AT ? AT->getDeducedType() : QualType();
10579         if (!U.isNull()) {
10580           CanQualType UCanon = Context.getCanonicalType(U);
10581           if (Deduced.isNull()) {
10582             Deduced = U;
10583             DeducedCanon = UCanon;
10584             DeducedDecl = D;
10585           } else if (DeducedCanon != UCanon) {
10586             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10587                  diag::err_auto_different_deductions)
10588               << (unsigned)AT->getKeyword()
10589               << Deduced << DeducedDecl->getDeclName()
10590               << U << D->getDeclName()
10591               << DeducedDecl->getInit()->getSourceRange()
10592               << D->getInit()->getSourceRange();
10593             D->setInvalidDecl();
10594             break;
10595           }
10596         }
10597       }
10598     }
10599   }
10600 
10601   ActOnDocumentableDecls(Group);
10602 
10603   return DeclGroupPtrTy::make(
10604       DeclGroupRef::Create(Context, Group.data(), Group.size()));
10605 }
10606 
10607 void Sema::ActOnDocumentableDecl(Decl *D) {
10608   ActOnDocumentableDecls(D);
10609 }
10610 
10611 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10612   // Don't parse the comment if Doxygen diagnostics are ignored.
10613   if (Group.empty() || !Group[0])
10614     return;
10615 
10616   if (Diags.isIgnored(diag::warn_doc_param_not_found,
10617                       Group[0]->getLocation()) &&
10618       Diags.isIgnored(diag::warn_unknown_comment_command_name,
10619                       Group[0]->getLocation()))
10620     return;
10621 
10622   if (Group.size() >= 2) {
10623     // This is a decl group.  Normally it will contain only declarations
10624     // produced from declarator list.  But in case we have any definitions or
10625     // additional declaration references:
10626     //   'typedef struct S {} S;'
10627     //   'typedef struct S *S;'
10628     //   'struct S *pS;'
10629     // FinalizeDeclaratorGroup adds these as separate declarations.
10630     Decl *MaybeTagDecl = Group[0];
10631     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10632       Group = Group.slice(1);
10633     }
10634   }
10635 
10636   // See if there are any new comments that are not attached to a decl.
10637   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10638   if (!Comments.empty() &&
10639       !Comments.back()->isAttached()) {
10640     // There is at least one comment that not attached to a decl.
10641     // Maybe it should be attached to one of these decls?
10642     //
10643     // Note that this way we pick up not only comments that precede the
10644     // declaration, but also comments that *follow* the declaration -- thanks to
10645     // the lookahead in the lexer: we've consumed the semicolon and looked
10646     // ahead through comments.
10647     for (unsigned i = 0, e = Group.size(); i != e; ++i)
10648       Context.getCommentForDecl(Group[i], &PP);
10649   }
10650 }
10651 
10652 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10653 /// to introduce parameters into function prototype scope.
10654 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10655   const DeclSpec &DS = D.getDeclSpec();
10656 
10657   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10658 
10659   // C++03 [dcl.stc]p2 also permits 'auto'.
10660   StorageClass SC = SC_None;
10661   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10662     SC = SC_Register;
10663   } else if (getLangOpts().CPlusPlus &&
10664              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10665     SC = SC_Auto;
10666   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10667     Diag(DS.getStorageClassSpecLoc(),
10668          diag::err_invalid_storage_class_in_func_decl);
10669     D.getMutableDeclSpec().ClearStorageClassSpecs();
10670   }
10671 
10672   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10673     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10674       << DeclSpec::getSpecifierName(TSCS);
10675   if (DS.isConstexprSpecified())
10676     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10677       << 0;
10678   if (DS.isConceptSpecified())
10679     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10680 
10681   DiagnoseFunctionSpecifiers(DS);
10682 
10683   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10684   QualType parmDeclType = TInfo->getType();
10685 
10686   if (getLangOpts().CPlusPlus) {
10687     // Check that there are no default arguments inside the type of this
10688     // parameter.
10689     CheckExtraCXXDefaultArguments(D);
10690 
10691     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10692     if (D.getCXXScopeSpec().isSet()) {
10693       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10694         << D.getCXXScopeSpec().getRange();
10695       D.getCXXScopeSpec().clear();
10696     }
10697   }
10698 
10699   // Ensure we have a valid name
10700   IdentifierInfo *II = nullptr;
10701   if (D.hasName()) {
10702     II = D.getIdentifier();
10703     if (!II) {
10704       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10705         << GetNameForDeclarator(D).getName();
10706       D.setInvalidType(true);
10707     }
10708   }
10709 
10710   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10711   if (II) {
10712     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10713                    ForRedeclaration);
10714     LookupName(R, S);
10715     if (R.isSingleResult()) {
10716       NamedDecl *PrevDecl = R.getFoundDecl();
10717       if (PrevDecl->isTemplateParameter()) {
10718         // Maybe we will complain about the shadowed template parameter.
10719         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10720         // Just pretend that we didn't see the previous declaration.
10721         PrevDecl = nullptr;
10722       } else if (S->isDeclScope(PrevDecl)) {
10723         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10724         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10725 
10726         // Recover by removing the name
10727         II = nullptr;
10728         D.SetIdentifier(nullptr, D.getIdentifierLoc());
10729         D.setInvalidType(true);
10730       }
10731     }
10732   }
10733 
10734   // Temporarily put parameter variables in the translation unit, not
10735   // the enclosing context.  This prevents them from accidentally
10736   // looking like class members in C++.
10737   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10738                                     D.getLocStart(),
10739                                     D.getIdentifierLoc(), II,
10740                                     parmDeclType, TInfo,
10741                                     SC);
10742 
10743   if (D.isInvalidType())
10744     New->setInvalidDecl();
10745 
10746   assert(S->isFunctionPrototypeScope());
10747   assert(S->getFunctionPrototypeDepth() >= 1);
10748   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10749                     S->getNextFunctionPrototypeIndex());
10750 
10751   // Add the parameter declaration into this scope.
10752   S->AddDecl(New);
10753   if (II)
10754     IdResolver.AddDecl(New);
10755 
10756   ProcessDeclAttributes(S, New, D);
10757 
10758   if (D.getDeclSpec().isModulePrivateSpecified())
10759     Diag(New->getLocation(), diag::err_module_private_local)
10760       << 1 << New->getDeclName()
10761       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10762       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10763 
10764   if (New->hasAttr<BlocksAttr>()) {
10765     Diag(New->getLocation(), diag::err_block_on_nonlocal);
10766   }
10767   return New;
10768 }
10769 
10770 /// \brief Synthesizes a variable for a parameter arising from a
10771 /// typedef.
10772 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10773                                               SourceLocation Loc,
10774                                               QualType T) {
10775   /* FIXME: setting StartLoc == Loc.
10776      Would it be worth to modify callers so as to provide proper source
10777      location for the unnamed parameters, embedding the parameter's type? */
10778   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10779                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
10780                                            SC_None, nullptr);
10781   Param->setImplicit();
10782   return Param;
10783 }
10784 
10785 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
10786                                     ParmVarDecl * const *ParamEnd) {
10787   // Don't diagnose unused-parameter errors in template instantiations; we
10788   // will already have done so in the template itself.
10789   if (!ActiveTemplateInstantiations.empty())
10790     return;
10791 
10792   for (; Param != ParamEnd; ++Param) {
10793     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10794         !(*Param)->hasAttr<UnusedAttr>()) {
10795       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10796         << (*Param)->getDeclName();
10797     }
10798   }
10799 }
10800 
10801 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
10802                                                   ParmVarDecl * const *ParamEnd,
10803                                                   QualType ReturnTy,
10804                                                   NamedDecl *D) {
10805   if (LangOpts.NumLargeByValueCopy == 0) // No check.
10806     return;
10807 
10808   // Warn if the return value is pass-by-value and larger than the specified
10809   // threshold.
10810   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10811     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10812     if (Size > LangOpts.NumLargeByValueCopy)
10813       Diag(D->getLocation(), diag::warn_return_value_size)
10814           << D->getDeclName() << Size;
10815   }
10816 
10817   // Warn if any parameter is pass-by-value and larger than the specified
10818   // threshold.
10819   for (; Param != ParamEnd; ++Param) {
10820     QualType T = (*Param)->getType();
10821     if (T->isDependentType() || !T.isPODType(Context))
10822       continue;
10823     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10824     if (Size > LangOpts.NumLargeByValueCopy)
10825       Diag((*Param)->getLocation(), diag::warn_parameter_size)
10826           << (*Param)->getDeclName() << Size;
10827   }
10828 }
10829 
10830 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10831                                   SourceLocation NameLoc, IdentifierInfo *Name,
10832                                   QualType T, TypeSourceInfo *TSInfo,
10833                                   StorageClass SC) {
10834   // In ARC, infer a lifetime qualifier for appropriate parameter types.
10835   if (getLangOpts().ObjCAutoRefCount &&
10836       T.getObjCLifetime() == Qualifiers::OCL_None &&
10837       T->isObjCLifetimeType()) {
10838 
10839     Qualifiers::ObjCLifetime lifetime;
10840 
10841     // Special cases for arrays:
10842     //   - if it's const, use __unsafe_unretained
10843     //   - otherwise, it's an error
10844     if (T->isArrayType()) {
10845       if (!T.isConstQualified()) {
10846         DelayedDiagnostics.add(
10847             sema::DelayedDiagnostic::makeForbiddenType(
10848             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10849       }
10850       lifetime = Qualifiers::OCL_ExplicitNone;
10851     } else {
10852       lifetime = T->getObjCARCImplicitLifetime();
10853     }
10854     T = Context.getLifetimeQualifiedType(T, lifetime);
10855   }
10856 
10857   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10858                                          Context.getAdjustedParameterType(T),
10859                                          TSInfo, SC, nullptr);
10860 
10861   // Parameters can not be abstract class types.
10862   // For record types, this is done by the AbstractClassUsageDiagnoser once
10863   // the class has been completely parsed.
10864   if (!CurContext->isRecord() &&
10865       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10866                              AbstractParamType))
10867     New->setInvalidDecl();
10868 
10869   // Parameter declarators cannot be interface types. All ObjC objects are
10870   // passed by reference.
10871   if (T->isObjCObjectType()) {
10872     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10873     Diag(NameLoc,
10874          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10875       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10876     T = Context.getObjCObjectPointerType(T);
10877     New->setType(T);
10878   }
10879 
10880   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10881   // duration shall not be qualified by an address-space qualifier."
10882   // Since all parameters have automatic store duration, they can not have
10883   // an address space.
10884   if (T.getAddressSpace() != 0) {
10885     // OpenCL allows function arguments declared to be an array of a type
10886     // to be qualified with an address space.
10887     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10888       Diag(NameLoc, diag::err_arg_with_address_space);
10889       New->setInvalidDecl();
10890     }
10891   }
10892 
10893   // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
10894   // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
10895   if (getLangOpts().OpenCL && T->isPointerType()) {
10896     const QualType PTy = T->getPointeeType();
10897     if (PTy->isImageType() || PTy->isSamplerT() || PTy->isPipeType()) {
10898       Diag(NameLoc, diag::err_opencl_pointer_to_type) << PTy;
10899       New->setInvalidDecl();
10900     }
10901   }
10902 
10903   return New;
10904 }
10905 
10906 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10907                                            SourceLocation LocAfterDecls) {
10908   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10909 
10910   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10911   // for a K&R function.
10912   if (!FTI.hasPrototype) {
10913     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10914       --i;
10915       if (FTI.Params[i].Param == nullptr) {
10916         SmallString<256> Code;
10917         llvm::raw_svector_ostream(Code)
10918             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10919         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10920             << FTI.Params[i].Ident
10921             << FixItHint::CreateInsertion(LocAfterDecls, Code);
10922 
10923         // Implicitly declare the argument as type 'int' for lack of a better
10924         // type.
10925         AttributeFactory attrs;
10926         DeclSpec DS(attrs);
10927         const char* PrevSpec; // unused
10928         unsigned DiagID; // unused
10929         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10930                            DiagID, Context.getPrintingPolicy());
10931         // Use the identifier location for the type source range.
10932         DS.SetRangeStart(FTI.Params[i].IdentLoc);
10933         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10934         Declarator ParamD(DS, Declarator::KNRTypeListContext);
10935         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10936         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10937       }
10938     }
10939   }
10940 }
10941 
10942 Decl *
10943 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
10944                               MultiTemplateParamsArg TemplateParameterLists,
10945                               SkipBodyInfo *SkipBody) {
10946   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10947   assert(D.isFunctionDeclarator() && "Not a function declarator!");
10948   Scope *ParentScope = FnBodyScope->getParent();
10949 
10950   D.setFunctionDefinitionKind(FDK_Definition);
10951   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
10952   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
10953 }
10954 
10955 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
10956   Consumer.HandleInlineFunctionDefinition(D);
10957 }
10958 
10959 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10960                              const FunctionDecl*& PossibleZeroParamPrototype) {
10961   // Don't warn about invalid declarations.
10962   if (FD->isInvalidDecl())
10963     return false;
10964 
10965   // Or declarations that aren't global.
10966   if (!FD->isGlobal())
10967     return false;
10968 
10969   // Don't warn about C++ member functions.
10970   if (isa<CXXMethodDecl>(FD))
10971     return false;
10972 
10973   // Don't warn about 'main'.
10974   if (FD->isMain())
10975     return false;
10976 
10977   // Don't warn about inline functions.
10978   if (FD->isInlined())
10979     return false;
10980 
10981   // Don't warn about function templates.
10982   if (FD->getDescribedFunctionTemplate())
10983     return false;
10984 
10985   // Don't warn about function template specializations.
10986   if (FD->isFunctionTemplateSpecialization())
10987     return false;
10988 
10989   // Don't warn for OpenCL kernels.
10990   if (FD->hasAttr<OpenCLKernelAttr>())
10991     return false;
10992 
10993   // Don't warn on explicitly deleted functions.
10994   if (FD->isDeleted())
10995     return false;
10996 
10997   bool MissingPrototype = true;
10998   for (const FunctionDecl *Prev = FD->getPreviousDecl();
10999        Prev; Prev = Prev->getPreviousDecl()) {
11000     // Ignore any declarations that occur in function or method
11001     // scope, because they aren't visible from the header.
11002     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11003       continue;
11004 
11005     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11006     if (FD->getNumParams() == 0)
11007       PossibleZeroParamPrototype = Prev;
11008     break;
11009   }
11010 
11011   return MissingPrototype;
11012 }
11013 
11014 void
11015 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11016                                    const FunctionDecl *EffectiveDefinition,
11017                                    SkipBodyInfo *SkipBody) {
11018   // Don't complain if we're in GNU89 mode and the previous definition
11019   // was an extern inline function.
11020   const FunctionDecl *Definition = EffectiveDefinition;
11021   if (!Definition)
11022     if (!FD->isDefined(Definition))
11023       return;
11024 
11025   if (canRedefineFunction(Definition, getLangOpts()))
11026     return;
11027 
11028   // If we don't have a visible definition of the function, and it's inline or
11029   // a template, skip the new definition.
11030   if (SkipBody && !hasVisibleDefinition(Definition) &&
11031       (Definition->getFormalLinkage() == InternalLinkage ||
11032        Definition->isInlined() ||
11033        Definition->getDescribedFunctionTemplate() ||
11034        Definition->getNumTemplateParameterLists())) {
11035     SkipBody->ShouldSkip = true;
11036     if (auto *TD = Definition->getDescribedFunctionTemplate())
11037       makeMergedDefinitionVisible(TD, FD->getLocation());
11038     else
11039       makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11040                                   FD->getLocation());
11041     return;
11042   }
11043 
11044   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11045       Definition->getStorageClass() == SC_Extern)
11046     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11047         << FD->getDeclName() << getLangOpts().CPlusPlus;
11048   else
11049     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11050 
11051   Diag(Definition->getLocation(), diag::note_previous_definition);
11052   FD->setInvalidDecl();
11053 }
11054 
11055 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11056                                    Sema &S) {
11057   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11058 
11059   LambdaScopeInfo *LSI = S.PushLambdaScope();
11060   LSI->CallOperator = CallOperator;
11061   LSI->Lambda = LambdaClass;
11062   LSI->ReturnType = CallOperator->getReturnType();
11063   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11064 
11065   if (LCD == LCD_None)
11066     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11067   else if (LCD == LCD_ByCopy)
11068     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11069   else if (LCD == LCD_ByRef)
11070     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11071   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11072 
11073   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11074   LSI->Mutable = !CallOperator->isConst();
11075 
11076   // Add the captures to the LSI so they can be noted as already
11077   // captured within tryCaptureVar.
11078   auto I = LambdaClass->field_begin();
11079   for (const auto &C : LambdaClass->captures()) {
11080     if (C.capturesVariable()) {
11081       VarDecl *VD = C.getCapturedVar();
11082       if (VD->isInitCapture())
11083         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11084       QualType CaptureType = VD->getType();
11085       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11086       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11087           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11088           /*EllipsisLoc*/C.isPackExpansion()
11089                          ? C.getEllipsisLoc() : SourceLocation(),
11090           CaptureType, /*Expr*/ nullptr);
11091 
11092     } else if (C.capturesThis()) {
11093       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11094                               S.getCurrentThisType(), /*Expr*/ nullptr,
11095                               C.getCaptureKind() == LCK_StarThis);
11096     } else {
11097       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11098     }
11099     ++I;
11100   }
11101 }
11102 
11103 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11104                                     SkipBodyInfo *SkipBody) {
11105   // Clear the last template instantiation error context.
11106   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11107 
11108   if (!D)
11109     return D;
11110   FunctionDecl *FD = nullptr;
11111 
11112   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11113     FD = FunTmpl->getTemplatedDecl();
11114   else
11115     FD = cast<FunctionDecl>(D);
11116 
11117   // See if this is a redefinition.
11118   if (!FD->isLateTemplateParsed()) {
11119     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11120 
11121     // If we're skipping the body, we're done. Don't enter the scope.
11122     if (SkipBody && SkipBody->ShouldSkip)
11123       return D;
11124   }
11125 
11126   // If we are instantiating a generic lambda call operator, push
11127   // a LambdaScopeInfo onto the function stack.  But use the information
11128   // that's already been calculated (ActOnLambdaExpr) to prime the current
11129   // LambdaScopeInfo.
11130   // When the template operator is being specialized, the LambdaScopeInfo,
11131   // has to be properly restored so that tryCaptureVariable doesn't try
11132   // and capture any new variables. In addition when calculating potential
11133   // captures during transformation of nested lambdas, it is necessary to
11134   // have the LSI properly restored.
11135   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11136     assert(ActiveTemplateInstantiations.size() &&
11137       "There should be an active template instantiation on the stack "
11138       "when instantiating a generic lambda!");
11139     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11140   }
11141   else
11142     // Enter a new function scope
11143     PushFunctionScope();
11144 
11145   // Builtin functions cannot be defined.
11146   if (unsigned BuiltinID = FD->getBuiltinID()) {
11147     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11148         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11149       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11150       FD->setInvalidDecl();
11151     }
11152   }
11153 
11154   // The return type of a function definition must be complete
11155   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11156   QualType ResultType = FD->getReturnType();
11157   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11158       !FD->isInvalidDecl() &&
11159       RequireCompleteType(FD->getLocation(), ResultType,
11160                           diag::err_func_def_incomplete_result))
11161     FD->setInvalidDecl();
11162 
11163   if (FnBodyScope)
11164     PushDeclContext(FnBodyScope, FD);
11165 
11166   // Check the validity of our function parameters
11167   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
11168                            /*CheckParameterNames=*/true);
11169 
11170   // Introduce our parameters into the function scope
11171   for (auto Param : FD->params()) {
11172     Param->setOwningFunction(FD);
11173 
11174     // If this has an identifier, add it to the scope stack.
11175     if (Param->getIdentifier() && FnBodyScope) {
11176       CheckShadow(FnBodyScope, Param);
11177 
11178       PushOnScopeChains(Param, FnBodyScope);
11179     }
11180   }
11181 
11182   // If we had any tags defined in the function prototype,
11183   // introduce them into the function scope.
11184   if (FnBodyScope) {
11185     for (ArrayRef<NamedDecl *>::iterator
11186              I = FD->getDeclsInPrototypeScope().begin(),
11187              E = FD->getDeclsInPrototypeScope().end();
11188          I != E; ++I) {
11189       NamedDecl *D = *I;
11190 
11191       // Some of these decls (like enums) may have been pinned to the
11192       // translation unit for lack of a real context earlier. If so, remove
11193       // from the translation unit and reattach to the current context.
11194       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
11195         // Is the decl actually in the context?
11196         if (Context.getTranslationUnitDecl()->containsDecl(D))
11197           Context.getTranslationUnitDecl()->removeDecl(D);
11198         // Either way, reassign the lexical decl context to our FunctionDecl.
11199         D->setLexicalDeclContext(CurContext);
11200       }
11201 
11202       // If the decl has a non-null name, make accessible in the current scope.
11203       if (!D->getName().empty())
11204         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
11205 
11206       // Similarly, dive into enums and fish their constants out, making them
11207       // accessible in this scope.
11208       if (auto *ED = dyn_cast<EnumDecl>(D)) {
11209         for (auto *EI : ED->enumerators())
11210           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11211       }
11212     }
11213   }
11214 
11215   // Ensure that the function's exception specification is instantiated.
11216   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11217     ResolveExceptionSpec(D->getLocation(), FPT);
11218 
11219   // dllimport cannot be applied to non-inline function definitions.
11220   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11221       !FD->isTemplateInstantiation()) {
11222     assert(!FD->hasAttr<DLLExportAttr>());
11223     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11224     FD->setInvalidDecl();
11225     return D;
11226   }
11227   // We want to attach documentation to original Decl (which might be
11228   // a function template).
11229   ActOnDocumentableDecl(D);
11230   if (getCurLexicalContext()->isObjCContainer() &&
11231       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11232       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11233     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11234 
11235   return D;
11236 }
11237 
11238 /// \brief Given the set of return statements within a function body,
11239 /// compute the variables that are subject to the named return value
11240 /// optimization.
11241 ///
11242 /// Each of the variables that is subject to the named return value
11243 /// optimization will be marked as NRVO variables in the AST, and any
11244 /// return statement that has a marked NRVO variable as its NRVO candidate can
11245 /// use the named return value optimization.
11246 ///
11247 /// This function applies a very simplistic algorithm for NRVO: if every return
11248 /// statement in the scope of a variable has the same NRVO candidate, that
11249 /// candidate is an NRVO variable.
11250 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11251   ReturnStmt **Returns = Scope->Returns.data();
11252 
11253   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11254     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11255       if (!NRVOCandidate->isNRVOVariable())
11256         Returns[I]->setNRVOCandidate(nullptr);
11257     }
11258   }
11259 }
11260 
11261 bool Sema::canDelayFunctionBody(const Declarator &D) {
11262   // We can't delay parsing the body of a constexpr function template (yet).
11263   if (D.getDeclSpec().isConstexprSpecified())
11264     return false;
11265 
11266   // We can't delay parsing the body of a function template with a deduced
11267   // return type (yet).
11268   if (D.getDeclSpec().containsPlaceholderType()) {
11269     // If the placeholder introduces a non-deduced trailing return type,
11270     // we can still delay parsing it.
11271     if (D.getNumTypeObjects()) {
11272       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11273       if (Outer.Kind == DeclaratorChunk::Function &&
11274           Outer.Fun.hasTrailingReturnType()) {
11275         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11276         return Ty.isNull() || !Ty->isUndeducedType();
11277       }
11278     }
11279     return false;
11280   }
11281 
11282   return true;
11283 }
11284 
11285 bool Sema::canSkipFunctionBody(Decl *D) {
11286   // We cannot skip the body of a function (or function template) which is
11287   // constexpr, since we may need to evaluate its body in order to parse the
11288   // rest of the file.
11289   // We cannot skip the body of a function with an undeduced return type,
11290   // because any callers of that function need to know the type.
11291   if (const FunctionDecl *FD = D->getAsFunction())
11292     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11293       return false;
11294   return Consumer.shouldSkipFunctionBody(D);
11295 }
11296 
11297 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11298   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11299     FD->setHasSkippedBody();
11300   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11301     MD->setHasSkippedBody();
11302   return ActOnFinishFunctionBody(Decl, nullptr);
11303 }
11304 
11305 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11306   return ActOnFinishFunctionBody(D, BodyArg, false);
11307 }
11308 
11309 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11310                                     bool IsInstantiation) {
11311   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11312 
11313   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11314   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11315 
11316   if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
11317     CheckCompletedCoroutineBody(FD, Body);
11318 
11319   if (FD) {
11320     FD->setBody(Body);
11321 
11322     if (getLangOpts().CPlusPlus14) {
11323       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11324           FD->getReturnType()->isUndeducedType()) {
11325         // If the function has a deduced result type but contains no 'return'
11326         // statements, the result type as written must be exactly 'auto', and
11327         // the deduced result type is 'void'.
11328         if (!FD->getReturnType()->getAs<AutoType>()) {
11329           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11330               << FD->getReturnType();
11331           FD->setInvalidDecl();
11332         } else {
11333           // Substitute 'void' for the 'auto' in the type.
11334           TypeLoc ResultType = getReturnTypeLoc(FD);
11335           Context.adjustDeducedFunctionResultType(
11336               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11337         }
11338       }
11339     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11340       // In C++11, we don't use 'auto' deduction rules for lambda call
11341       // operators because we don't support return type deduction.
11342       auto *LSI = getCurLambda();
11343       if (LSI->HasImplicitReturnType) {
11344         deduceClosureReturnType(*LSI);
11345 
11346         // C++11 [expr.prim.lambda]p4:
11347         //   [...] if there are no return statements in the compound-statement
11348         //   [the deduced type is] the type void
11349         QualType RetType =
11350             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11351 
11352         // Update the return type to the deduced type.
11353         const FunctionProtoType *Proto =
11354             FD->getType()->getAs<FunctionProtoType>();
11355         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11356                                             Proto->getExtProtoInfo()));
11357       }
11358     }
11359 
11360     // The only way to be included in UndefinedButUsed is if there is an
11361     // ODR use before the definition. Avoid the expensive map lookup if this
11362     // is the first declaration.
11363     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11364       if (!FD->isExternallyVisible())
11365         UndefinedButUsed.erase(FD);
11366       else if (FD->isInlined() &&
11367                !LangOpts.GNUInline &&
11368                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11369         UndefinedButUsed.erase(FD);
11370     }
11371 
11372     // If the function implicitly returns zero (like 'main') or is naked,
11373     // don't complain about missing return statements.
11374     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11375       WP.disableCheckFallThrough();
11376 
11377     // MSVC permits the use of pure specifier (=0) on function definition,
11378     // defined at class scope, warn about this non-standard construct.
11379     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11380       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11381 
11382     if (!FD->isInvalidDecl()) {
11383       // Don't diagnose unused parameters of defaulted or deleted functions.
11384       if (!FD->isDeleted() && !FD->isDefaulted())
11385         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
11386       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
11387                                              FD->getReturnType(), FD);
11388 
11389       // If this is a structor, we need a vtable.
11390       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11391         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11392       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11393         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11394 
11395       // Try to apply the named return value optimization. We have to check
11396       // if we can do this here because lambdas keep return statements around
11397       // to deduce an implicit return type.
11398       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11399           !FD->isDependentContext())
11400         computeNRVO(Body, getCurFunction());
11401     }
11402 
11403     // GNU warning -Wmissing-prototypes:
11404     //   Warn if a global function is defined without a previous
11405     //   prototype declaration. This warning is issued even if the
11406     //   definition itself provides a prototype. The aim is to detect
11407     //   global functions that fail to be declared in header files.
11408     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11409     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11410       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11411 
11412       if (PossibleZeroParamPrototype) {
11413         // We found a declaration that is not a prototype,
11414         // but that could be a zero-parameter prototype
11415         if (TypeSourceInfo *TI =
11416                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11417           TypeLoc TL = TI->getTypeLoc();
11418           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11419             Diag(PossibleZeroParamPrototype->getLocation(),
11420                  diag::note_declaration_not_a_prototype)
11421                 << PossibleZeroParamPrototype
11422                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11423         }
11424       }
11425     }
11426 
11427     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11428       const CXXMethodDecl *KeyFunction;
11429       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11430           MD->isVirtual() &&
11431           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11432           MD == KeyFunction->getCanonicalDecl()) {
11433         // Update the key-function state if necessary for this ABI.
11434         if (FD->isInlined() &&
11435             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11436           Context.setNonKeyFunction(MD);
11437 
11438           // If the newly-chosen key function is already defined, then we
11439           // need to mark the vtable as used retroactively.
11440           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11441           const FunctionDecl *Definition;
11442           if (KeyFunction && KeyFunction->isDefined(Definition))
11443             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11444         } else {
11445           // We just defined they key function; mark the vtable as used.
11446           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11447         }
11448       }
11449     }
11450 
11451     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11452            "Function parsing confused");
11453   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11454     assert(MD == getCurMethodDecl() && "Method parsing confused");
11455     MD->setBody(Body);
11456     if (!MD->isInvalidDecl()) {
11457       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
11458       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
11459                                              MD->getReturnType(), MD);
11460 
11461       if (Body)
11462         computeNRVO(Body, getCurFunction());
11463     }
11464     if (getCurFunction()->ObjCShouldCallSuper) {
11465       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11466         << MD->getSelector().getAsString();
11467       getCurFunction()->ObjCShouldCallSuper = false;
11468     }
11469     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11470       const ObjCMethodDecl *InitMethod = nullptr;
11471       bool isDesignated =
11472           MD->isDesignatedInitializerForTheInterface(&InitMethod);
11473       assert(isDesignated && InitMethod);
11474       (void)isDesignated;
11475 
11476       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11477         auto IFace = MD->getClassInterface();
11478         if (!IFace)
11479           return false;
11480         auto SuperD = IFace->getSuperClass();
11481         if (!SuperD)
11482           return false;
11483         return SuperD->getIdentifier() ==
11484             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11485       };
11486       // Don't issue this warning for unavailable inits or direct subclasses
11487       // of NSObject.
11488       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11489         Diag(MD->getLocation(),
11490              diag::warn_objc_designated_init_missing_super_call);
11491         Diag(InitMethod->getLocation(),
11492              diag::note_objc_designated_init_marked_here);
11493       }
11494       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11495     }
11496     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11497       // Don't issue this warning for unavaialable inits.
11498       if (!MD->isUnavailable())
11499         Diag(MD->getLocation(),
11500              diag::warn_objc_secondary_init_missing_init_call);
11501       getCurFunction()->ObjCWarnForNoInitDelegation = false;
11502     }
11503   } else {
11504     return nullptr;
11505   }
11506 
11507   assert(!getCurFunction()->ObjCShouldCallSuper &&
11508          "This should only be set for ObjC methods, which should have been "
11509          "handled in the block above.");
11510 
11511   // Verify and clean out per-function state.
11512   if (Body && (!FD || !FD->isDefaulted())) {
11513     // C++ constructors that have function-try-blocks can't have return
11514     // statements in the handlers of that block. (C++ [except.handle]p14)
11515     // Verify this.
11516     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11517       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11518 
11519     // Verify that gotos and switch cases don't jump into scopes illegally.
11520     if (getCurFunction()->NeedsScopeChecking() &&
11521         !PP.isCodeCompletionEnabled())
11522       DiagnoseInvalidJumps(Body);
11523 
11524     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11525       if (!Destructor->getParent()->isDependentType())
11526         CheckDestructor(Destructor);
11527 
11528       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11529                                              Destructor->getParent());
11530     }
11531 
11532     // If any errors have occurred, clear out any temporaries that may have
11533     // been leftover. This ensures that these temporaries won't be picked up for
11534     // deletion in some later function.
11535     if (getDiagnostics().hasErrorOccurred() ||
11536         getDiagnostics().getSuppressAllDiagnostics()) {
11537       DiscardCleanupsInEvaluationContext();
11538     }
11539     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11540         !isa<FunctionTemplateDecl>(dcl)) {
11541       // Since the body is valid, issue any analysis-based warnings that are
11542       // enabled.
11543       ActivePolicy = &WP;
11544     }
11545 
11546     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11547         (!CheckConstexprFunctionDecl(FD) ||
11548          !CheckConstexprFunctionBody(FD, Body)))
11549       FD->setInvalidDecl();
11550 
11551     if (FD && FD->hasAttr<NakedAttr>()) {
11552       for (const Stmt *S : Body->children()) {
11553         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11554           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11555           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11556           FD->setInvalidDecl();
11557           break;
11558         }
11559       }
11560     }
11561 
11562     assert(ExprCleanupObjects.size() ==
11563                ExprEvalContexts.back().NumCleanupObjects &&
11564            "Leftover temporaries in function");
11565     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
11566     assert(MaybeODRUseExprs.empty() &&
11567            "Leftover expressions for odr-use checking");
11568   }
11569 
11570   if (!IsInstantiation)
11571     PopDeclContext();
11572 
11573   PopFunctionScopeInfo(ActivePolicy, dcl);
11574   // If any errors have occurred, clear out any temporaries that may have
11575   // been leftover. This ensures that these temporaries won't be picked up for
11576   // deletion in some later function.
11577   if (getDiagnostics().hasErrorOccurred()) {
11578     DiscardCleanupsInEvaluationContext();
11579   }
11580 
11581   return dcl;
11582 }
11583 
11584 /// When we finish delayed parsing of an attribute, we must attach it to the
11585 /// relevant Decl.
11586 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11587                                        ParsedAttributes &Attrs) {
11588   // Always attach attributes to the underlying decl.
11589   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11590     D = TD->getTemplatedDecl();
11591   ProcessDeclAttributeList(S, D, Attrs.getList());
11592 
11593   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11594     if (Method->isStatic())
11595       checkThisInStaticMemberFunctionAttributes(Method);
11596 }
11597 
11598 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11599 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11600 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11601                                           IdentifierInfo &II, Scope *S) {
11602   // Before we produce a declaration for an implicitly defined
11603   // function, see whether there was a locally-scoped declaration of
11604   // this name as a function or variable. If so, use that
11605   // (non-visible) declaration, and complain about it.
11606   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11607     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11608     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11609     return ExternCPrev;
11610   }
11611 
11612   // Extension in C99.  Legal in C90, but warn about it.
11613   unsigned diag_id;
11614   if (II.getName().startswith("__builtin_"))
11615     diag_id = diag::warn_builtin_unknown;
11616   else if (getLangOpts().C99)
11617     diag_id = diag::ext_implicit_function_decl;
11618   else
11619     diag_id = diag::warn_implicit_function_decl;
11620   Diag(Loc, diag_id) << &II;
11621 
11622   // Because typo correction is expensive, only do it if the implicit
11623   // function declaration is going to be treated as an error.
11624   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11625     TypoCorrection Corrected;
11626     if (S &&
11627         (Corrected = CorrectTypo(
11628              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11629              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11630       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11631                    /*ErrorRecovery*/false);
11632   }
11633 
11634   // Set a Declarator for the implicit definition: int foo();
11635   const char *Dummy;
11636   AttributeFactory attrFactory;
11637   DeclSpec DS(attrFactory);
11638   unsigned DiagID;
11639   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11640                                   Context.getPrintingPolicy());
11641   (void)Error; // Silence warning.
11642   assert(!Error && "Error setting up implicit decl!");
11643   SourceLocation NoLoc;
11644   Declarator D(DS, Declarator::BlockContext);
11645   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11646                                              /*IsAmbiguous=*/false,
11647                                              /*LParenLoc=*/NoLoc,
11648                                              /*Params=*/nullptr,
11649                                              /*NumParams=*/0,
11650                                              /*EllipsisLoc=*/NoLoc,
11651                                              /*RParenLoc=*/NoLoc,
11652                                              /*TypeQuals=*/0,
11653                                              /*RefQualifierIsLvalueRef=*/true,
11654                                              /*RefQualifierLoc=*/NoLoc,
11655                                              /*ConstQualifierLoc=*/NoLoc,
11656                                              /*VolatileQualifierLoc=*/NoLoc,
11657                                              /*RestrictQualifierLoc=*/NoLoc,
11658                                              /*MutableLoc=*/NoLoc,
11659                                              EST_None,
11660                                              /*ESpecRange=*/SourceRange(),
11661                                              /*Exceptions=*/nullptr,
11662                                              /*ExceptionRanges=*/nullptr,
11663                                              /*NumExceptions=*/0,
11664                                              /*NoexceptExpr=*/nullptr,
11665                                              /*ExceptionSpecTokens=*/nullptr,
11666                                              Loc, Loc, D),
11667                 DS.getAttributes(),
11668                 SourceLocation());
11669   D.SetIdentifier(&II, Loc);
11670 
11671   // Insert this function into translation-unit scope.
11672 
11673   DeclContext *PrevDC = CurContext;
11674   CurContext = Context.getTranslationUnitDecl();
11675 
11676   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11677   FD->setImplicit();
11678 
11679   CurContext = PrevDC;
11680 
11681   AddKnownFunctionAttributes(FD);
11682 
11683   return FD;
11684 }
11685 
11686 /// \brief Adds any function attributes that we know a priori based on
11687 /// the declaration of this function.
11688 ///
11689 /// These attributes can apply both to implicitly-declared builtins
11690 /// (like __builtin___printf_chk) or to library-declared functions
11691 /// like NSLog or printf.
11692 ///
11693 /// We need to check for duplicate attributes both here and where user-written
11694 /// attributes are applied to declarations.
11695 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11696   if (FD->isInvalidDecl())
11697     return;
11698 
11699   // If this is a built-in function, map its builtin attributes to
11700   // actual attributes.
11701   if (unsigned BuiltinID = FD->getBuiltinID()) {
11702     // Handle printf-formatting attributes.
11703     unsigned FormatIdx;
11704     bool HasVAListArg;
11705     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11706       if (!FD->hasAttr<FormatAttr>()) {
11707         const char *fmt = "printf";
11708         unsigned int NumParams = FD->getNumParams();
11709         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11710             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11711           fmt = "NSString";
11712         FD->addAttr(FormatAttr::CreateImplicit(Context,
11713                                                &Context.Idents.get(fmt),
11714                                                FormatIdx+1,
11715                                                HasVAListArg ? 0 : FormatIdx+2,
11716                                                FD->getLocation()));
11717       }
11718     }
11719     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11720                                              HasVAListArg)) {
11721      if (!FD->hasAttr<FormatAttr>())
11722        FD->addAttr(FormatAttr::CreateImplicit(Context,
11723                                               &Context.Idents.get("scanf"),
11724                                               FormatIdx+1,
11725                                               HasVAListArg ? 0 : FormatIdx+2,
11726                                               FD->getLocation()));
11727     }
11728 
11729     // Mark const if we don't care about errno and that is the only
11730     // thing preventing the function from being const. This allows
11731     // IRgen to use LLVM intrinsics for such functions.
11732     if (!getLangOpts().MathErrno &&
11733         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11734       if (!FD->hasAttr<ConstAttr>())
11735         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11736     }
11737 
11738     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11739         !FD->hasAttr<ReturnsTwiceAttr>())
11740       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11741                                          FD->getLocation()));
11742     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11743       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11744     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11745       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11746     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11747         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11748       // Add the appropriate attribute, depending on the CUDA compilation mode
11749       // and which target the builtin belongs to. For example, during host
11750       // compilation, aux builtins are __device__, while the rest are __host__.
11751       if (getLangOpts().CUDAIsDevice !=
11752           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11753         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11754       else
11755         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11756     }
11757   }
11758 
11759   // If C++ exceptions are enabled but we are told extern "C" functions cannot
11760   // throw, add an implicit nothrow attribute to any extern "C" function we come
11761   // across.
11762   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
11763       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
11764     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
11765     if (!FPT || FPT->getExceptionSpecType() == EST_None)
11766       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11767   }
11768 
11769   IdentifierInfo *Name = FD->getIdentifier();
11770   if (!Name)
11771     return;
11772   if ((!getLangOpts().CPlusPlus &&
11773        FD->getDeclContext()->isTranslationUnit()) ||
11774       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11775        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11776        LinkageSpecDecl::lang_c)) {
11777     // Okay: this could be a libc/libm/Objective-C function we know
11778     // about.
11779   } else
11780     return;
11781 
11782   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11783     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11784     // target-specific builtins, perhaps?
11785     if (!FD->hasAttr<FormatAttr>())
11786       FD->addAttr(FormatAttr::CreateImplicit(Context,
11787                                              &Context.Idents.get("printf"), 2,
11788                                              Name->isStr("vasprintf") ? 0 : 3,
11789                                              FD->getLocation()));
11790   }
11791 
11792   if (Name->isStr("__CFStringMakeConstantString")) {
11793     // We already have a __builtin___CFStringMakeConstantString,
11794     // but builds that use -fno-constant-cfstrings don't go through that.
11795     if (!FD->hasAttr<FormatArgAttr>())
11796       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11797                                                 FD->getLocation()));
11798   }
11799 }
11800 
11801 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11802                                     TypeSourceInfo *TInfo) {
11803   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11804   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11805 
11806   if (!TInfo) {
11807     assert(D.isInvalidType() && "no declarator info for valid type");
11808     TInfo = Context.getTrivialTypeSourceInfo(T);
11809   }
11810 
11811   // Scope manipulation handled by caller.
11812   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11813                                            D.getLocStart(),
11814                                            D.getIdentifierLoc(),
11815                                            D.getIdentifier(),
11816                                            TInfo);
11817 
11818   // Bail out immediately if we have an invalid declaration.
11819   if (D.isInvalidType()) {
11820     NewTD->setInvalidDecl();
11821     return NewTD;
11822   }
11823 
11824   if (D.getDeclSpec().isModulePrivateSpecified()) {
11825     if (CurContext->isFunctionOrMethod())
11826       Diag(NewTD->getLocation(), diag::err_module_private_local)
11827         << 2 << NewTD->getDeclName()
11828         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11829         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11830     else
11831       NewTD->setModulePrivate();
11832   }
11833 
11834   // C++ [dcl.typedef]p8:
11835   //   If the typedef declaration defines an unnamed class (or
11836   //   enum), the first typedef-name declared by the declaration
11837   //   to be that class type (or enum type) is used to denote the
11838   //   class type (or enum type) for linkage purposes only.
11839   // We need to check whether the type was declared in the declaration.
11840   switch (D.getDeclSpec().getTypeSpecType()) {
11841   case TST_enum:
11842   case TST_struct:
11843   case TST_interface:
11844   case TST_union:
11845   case TST_class: {
11846     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11847     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11848     break;
11849   }
11850 
11851   default:
11852     break;
11853   }
11854 
11855   return NewTD;
11856 }
11857 
11858 /// \brief Check that this is a valid underlying type for an enum declaration.
11859 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11860   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11861   QualType T = TI->getType();
11862 
11863   if (T->isDependentType())
11864     return false;
11865 
11866   if (const BuiltinType *BT = T->getAs<BuiltinType>())
11867     if (BT->isInteger())
11868       return false;
11869 
11870   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11871   return true;
11872 }
11873 
11874 /// Check whether this is a valid redeclaration of a previous enumeration.
11875 /// \return true if the redeclaration was invalid.
11876 bool Sema::CheckEnumRedeclaration(
11877     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
11878     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
11879   bool IsFixed = !EnumUnderlyingTy.isNull();
11880 
11881   if (IsScoped != Prev->isScoped()) {
11882     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11883       << Prev->isScoped();
11884     Diag(Prev->getLocation(), diag::note_previous_declaration);
11885     return true;
11886   }
11887 
11888   if (IsFixed && Prev->isFixed()) {
11889     if (!EnumUnderlyingTy->isDependentType() &&
11890         !Prev->getIntegerType()->isDependentType() &&
11891         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11892                                         Prev->getIntegerType())) {
11893       // TODO: Highlight the underlying type of the redeclaration.
11894       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11895         << EnumUnderlyingTy << Prev->getIntegerType();
11896       Diag(Prev->getLocation(), diag::note_previous_declaration)
11897           << Prev->getIntegerTypeRange();
11898       return true;
11899     }
11900   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
11901     ;
11902   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
11903     ;
11904   } else if (IsFixed != Prev->isFixed()) {
11905     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11906       << Prev->isFixed();
11907     Diag(Prev->getLocation(), diag::note_previous_declaration);
11908     return true;
11909   }
11910 
11911   return false;
11912 }
11913 
11914 /// \brief Get diagnostic %select index for tag kind for
11915 /// redeclaration diagnostic message.
11916 /// WARNING: Indexes apply to particular diagnostics only!
11917 ///
11918 /// \returns diagnostic %select index.
11919 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
11920   switch (Tag) {
11921   case TTK_Struct: return 0;
11922   case TTK_Interface: return 1;
11923   case TTK_Class:  return 2;
11924   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11925   }
11926 }
11927 
11928 /// \brief Determine if tag kind is a class-key compatible with
11929 /// class for redeclaration (class, struct, or __interface).
11930 ///
11931 /// \returns true iff the tag kind is compatible.
11932 static bool isClassCompatTagKind(TagTypeKind Tag)
11933 {
11934   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11935 }
11936 
11937 /// \brief Determine whether a tag with a given kind is acceptable
11938 /// as a redeclaration of the given tag declaration.
11939 ///
11940 /// \returns true if the new tag kind is acceptable, false otherwise.
11941 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11942                                         TagTypeKind NewTag, bool isDefinition,
11943                                         SourceLocation NewTagLoc,
11944                                         const IdentifierInfo *Name) {
11945   // C++ [dcl.type.elab]p3:
11946   //   The class-key or enum keyword present in the
11947   //   elaborated-type-specifier shall agree in kind with the
11948   //   declaration to which the name in the elaborated-type-specifier
11949   //   refers. This rule also applies to the form of
11950   //   elaborated-type-specifier that declares a class-name or
11951   //   friend class since it can be construed as referring to the
11952   //   definition of the class. Thus, in any
11953   //   elaborated-type-specifier, the enum keyword shall be used to
11954   //   refer to an enumeration (7.2), the union class-key shall be
11955   //   used to refer to a union (clause 9), and either the class or
11956   //   struct class-key shall be used to refer to a class (clause 9)
11957   //   declared using the class or struct class-key.
11958   TagTypeKind OldTag = Previous->getTagKind();
11959   if (!isDefinition || !isClassCompatTagKind(NewTag))
11960     if (OldTag == NewTag)
11961       return true;
11962 
11963   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11964     // Warn about the struct/class tag mismatch.
11965     bool isTemplate = false;
11966     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11967       isTemplate = Record->getDescribedClassTemplate();
11968 
11969     if (!ActiveTemplateInstantiations.empty()) {
11970       // In a template instantiation, do not offer fix-its for tag mismatches
11971       // since they usually mess up the template instead of fixing the problem.
11972       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11973         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11974         << getRedeclDiagFromTagKind(OldTag);
11975       return true;
11976     }
11977 
11978     if (isDefinition) {
11979       // On definitions, check previous tags and issue a fix-it for each
11980       // one that doesn't match the current tag.
11981       if (Previous->getDefinition()) {
11982         // Don't suggest fix-its for redefinitions.
11983         return true;
11984       }
11985 
11986       bool previousMismatch = false;
11987       for (auto I : Previous->redecls()) {
11988         if (I->getTagKind() != NewTag) {
11989           if (!previousMismatch) {
11990             previousMismatch = true;
11991             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11992               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11993               << getRedeclDiagFromTagKind(I->getTagKind());
11994           }
11995           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11996             << getRedeclDiagFromTagKind(NewTag)
11997             << FixItHint::CreateReplacement(I->getInnerLocStart(),
11998                  TypeWithKeyword::getTagTypeKindName(NewTag));
11999         }
12000       }
12001       return true;
12002     }
12003 
12004     // Check for a previous definition.  If current tag and definition
12005     // are same type, do nothing.  If no definition, but disagree with
12006     // with previous tag type, give a warning, but no fix-it.
12007     const TagDecl *Redecl = Previous->getDefinition() ?
12008                             Previous->getDefinition() : Previous;
12009     if (Redecl->getTagKind() == NewTag) {
12010       return true;
12011     }
12012 
12013     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12014       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12015       << getRedeclDiagFromTagKind(OldTag);
12016     Diag(Redecl->getLocation(), diag::note_previous_use);
12017 
12018     // If there is a previous definition, suggest a fix-it.
12019     if (Previous->getDefinition()) {
12020         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12021           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12022           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12023                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12024     }
12025 
12026     return true;
12027   }
12028   return false;
12029 }
12030 
12031 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12032 /// from an outer enclosing namespace or file scope inside a friend declaration.
12033 /// This should provide the commented out code in the following snippet:
12034 ///   namespace N {
12035 ///     struct X;
12036 ///     namespace M {
12037 ///       struct Y { friend struct /*N::*/ X; };
12038 ///     }
12039 ///   }
12040 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12041                                          SourceLocation NameLoc) {
12042   // While the decl is in a namespace, do repeated lookup of that name and see
12043   // if we get the same namespace back.  If we do not, continue until
12044   // translation unit scope, at which point we have a fully qualified NNS.
12045   SmallVector<IdentifierInfo *, 4> Namespaces;
12046   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12047   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12048     // This tag should be declared in a namespace, which can only be enclosed by
12049     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12050     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12051     if (!Namespace || Namespace->isAnonymousNamespace())
12052       return FixItHint();
12053     IdentifierInfo *II = Namespace->getIdentifier();
12054     Namespaces.push_back(II);
12055     NamedDecl *Lookup = SemaRef.LookupSingleName(
12056         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12057     if (Lookup == Namespace)
12058       break;
12059   }
12060 
12061   // Once we have all the namespaces, reverse them to go outermost first, and
12062   // build an NNS.
12063   SmallString<64> Insertion;
12064   llvm::raw_svector_ostream OS(Insertion);
12065   if (DC->isTranslationUnit())
12066     OS << "::";
12067   std::reverse(Namespaces.begin(), Namespaces.end());
12068   for (auto *II : Namespaces)
12069     OS << II->getName() << "::";
12070   return FixItHint::CreateInsertion(NameLoc, Insertion);
12071 }
12072 
12073 /// \brief Determine whether a tag originally declared in context \p OldDC can
12074 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12075 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12076 /// using-declaration).
12077 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12078                                          DeclContext *NewDC) {
12079   OldDC = OldDC->getRedeclContext();
12080   NewDC = NewDC->getRedeclContext();
12081 
12082   if (OldDC->Equals(NewDC))
12083     return true;
12084 
12085   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12086   // encloses the other).
12087   if (S.getLangOpts().MSVCCompat &&
12088       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12089     return true;
12090 
12091   return false;
12092 }
12093 
12094 /// Find the DeclContext in which a tag is implicitly declared if we see an
12095 /// elaborated type specifier in the specified context, and lookup finds
12096 /// nothing.
12097 static DeclContext *getTagInjectionContext(DeclContext *DC) {
12098   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
12099     DC = DC->getParent();
12100   return DC;
12101 }
12102 
12103 /// Find the Scope in which a tag is implicitly declared if we see an
12104 /// elaborated type specifier in the specified context, and lookup finds
12105 /// nothing.
12106 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
12107   while (S->isClassScope() ||
12108          (LangOpts.CPlusPlus &&
12109           S->isFunctionPrototypeScope()) ||
12110          ((S->getFlags() & Scope::DeclScope) == 0) ||
12111          (S->getEntity() && S->getEntity()->isTransparentContext()))
12112     S = S->getParent();
12113   return S;
12114 }
12115 
12116 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12117 /// former case, Name will be non-null.  In the later case, Name will be null.
12118 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12119 /// reference/declaration/definition of a tag.
12120 ///
12121 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12122 /// trailing-type-specifier) other than one in an alias-declaration.
12123 ///
12124 /// \param SkipBody If non-null, will be set to indicate if the caller should
12125 /// skip the definition of this tag and treat it as if it were a declaration.
12126 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12127                      SourceLocation KWLoc, CXXScopeSpec &SS,
12128                      IdentifierInfo *Name, SourceLocation NameLoc,
12129                      AttributeList *Attr, AccessSpecifier AS,
12130                      SourceLocation ModulePrivateLoc,
12131                      MultiTemplateParamsArg TemplateParameterLists,
12132                      bool &OwnedDecl, bool &IsDependent,
12133                      SourceLocation ScopedEnumKWLoc,
12134                      bool ScopedEnumUsesClassTag,
12135                      TypeResult UnderlyingType,
12136                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12137   // If this is not a definition, it must have a name.
12138   IdentifierInfo *OrigName = Name;
12139   assert((Name != nullptr || TUK == TUK_Definition) &&
12140          "Nameless record must be a definition!");
12141   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12142 
12143   OwnedDecl = false;
12144   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12145   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12146 
12147   // FIXME: Check explicit specializations more carefully.
12148   bool isExplicitSpecialization = false;
12149   bool Invalid = false;
12150 
12151   // We only need to do this matching if we have template parameters
12152   // or a scope specifier, which also conveniently avoids this work
12153   // for non-C++ cases.
12154   if (TemplateParameterLists.size() > 0 ||
12155       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12156     if (TemplateParameterList *TemplateParams =
12157             MatchTemplateParametersToScopeSpecifier(
12158                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12159                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12160       if (Kind == TTK_Enum) {
12161         Diag(KWLoc, diag::err_enum_template);
12162         return nullptr;
12163       }
12164 
12165       if (TemplateParams->size() > 0) {
12166         // This is a declaration or definition of a class template (which may
12167         // be a member of another template).
12168 
12169         if (Invalid)
12170           return nullptr;
12171 
12172         OwnedDecl = false;
12173         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12174                                                SS, Name, NameLoc, Attr,
12175                                                TemplateParams, AS,
12176                                                ModulePrivateLoc,
12177                                                /*FriendLoc*/SourceLocation(),
12178                                                TemplateParameterLists.size()-1,
12179                                                TemplateParameterLists.data(),
12180                                                SkipBody);
12181         return Result.get();
12182       } else {
12183         // The "template<>" header is extraneous.
12184         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12185           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12186         isExplicitSpecialization = true;
12187       }
12188     }
12189   }
12190 
12191   // Figure out the underlying type if this a enum declaration. We need to do
12192   // this early, because it's needed to detect if this is an incompatible
12193   // redeclaration.
12194   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12195   bool EnumUnderlyingIsImplicit = false;
12196 
12197   if (Kind == TTK_Enum) {
12198     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12199       // No underlying type explicitly specified, or we failed to parse the
12200       // type, default to int.
12201       EnumUnderlying = Context.IntTy.getTypePtr();
12202     else if (UnderlyingType.get()) {
12203       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12204       // integral type; any cv-qualification is ignored.
12205       TypeSourceInfo *TI = nullptr;
12206       GetTypeFromParser(UnderlyingType.get(), &TI);
12207       EnumUnderlying = TI;
12208 
12209       if (CheckEnumUnderlyingType(TI))
12210         // Recover by falling back to int.
12211         EnumUnderlying = Context.IntTy.getTypePtr();
12212 
12213       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12214                                           UPPC_FixedUnderlyingType))
12215         EnumUnderlying = Context.IntTy.getTypePtr();
12216 
12217     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12218       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12219         // Microsoft enums are always of int type.
12220         EnumUnderlying = Context.IntTy.getTypePtr();
12221         EnumUnderlyingIsImplicit = true;
12222       }
12223     }
12224   }
12225 
12226   DeclContext *SearchDC = CurContext;
12227   DeclContext *DC = CurContext;
12228   bool isStdBadAlloc = false;
12229 
12230   RedeclarationKind Redecl = ForRedeclaration;
12231   if (TUK == TUK_Friend || TUK == TUK_Reference)
12232     Redecl = NotForRedeclaration;
12233 
12234   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12235   if (Name && SS.isNotEmpty()) {
12236     // We have a nested-name tag ('struct foo::bar').
12237 
12238     // Check for invalid 'foo::'.
12239     if (SS.isInvalid()) {
12240       Name = nullptr;
12241       goto CreateNewDecl;
12242     }
12243 
12244     // If this is a friend or a reference to a class in a dependent
12245     // context, don't try to make a decl for it.
12246     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12247       DC = computeDeclContext(SS, false);
12248       if (!DC) {
12249         IsDependent = true;
12250         return nullptr;
12251       }
12252     } else {
12253       DC = computeDeclContext(SS, true);
12254       if (!DC) {
12255         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12256           << SS.getRange();
12257         return nullptr;
12258       }
12259     }
12260 
12261     if (RequireCompleteDeclContext(SS, DC))
12262       return nullptr;
12263 
12264     SearchDC = DC;
12265     // Look-up name inside 'foo::'.
12266     LookupQualifiedName(Previous, DC);
12267 
12268     if (Previous.isAmbiguous())
12269       return nullptr;
12270 
12271     if (Previous.empty()) {
12272       // Name lookup did not find anything. However, if the
12273       // nested-name-specifier refers to the current instantiation,
12274       // and that current instantiation has any dependent base
12275       // classes, we might find something at instantiation time: treat
12276       // this as a dependent elaborated-type-specifier.
12277       // But this only makes any sense for reference-like lookups.
12278       if (Previous.wasNotFoundInCurrentInstantiation() &&
12279           (TUK == TUK_Reference || TUK == TUK_Friend)) {
12280         IsDependent = true;
12281         return nullptr;
12282       }
12283 
12284       // A tag 'foo::bar' must already exist.
12285       Diag(NameLoc, diag::err_not_tag_in_scope)
12286         << Kind << Name << DC << SS.getRange();
12287       Name = nullptr;
12288       Invalid = true;
12289       goto CreateNewDecl;
12290     }
12291   } else if (Name) {
12292     // C++14 [class.mem]p14:
12293     //   If T is the name of a class, then each of the following shall have a
12294     //   name different from T:
12295     //    -- every member of class T that is itself a type
12296     if (TUK != TUK_Reference && TUK != TUK_Friend &&
12297         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12298       return nullptr;
12299 
12300     // If this is a named struct, check to see if there was a previous forward
12301     // declaration or definition.
12302     // FIXME: We're looking into outer scopes here, even when we
12303     // shouldn't be. Doing so can result in ambiguities that we
12304     // shouldn't be diagnosing.
12305     LookupName(Previous, S);
12306 
12307     // When declaring or defining a tag, ignore ambiguities introduced
12308     // by types using'ed into this scope.
12309     if (Previous.isAmbiguous() &&
12310         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12311       LookupResult::Filter F = Previous.makeFilter();
12312       while (F.hasNext()) {
12313         NamedDecl *ND = F.next();
12314         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
12315           F.erase();
12316       }
12317       F.done();
12318     }
12319 
12320     // C++11 [namespace.memdef]p3:
12321     //   If the name in a friend declaration is neither qualified nor
12322     //   a template-id and the declaration is a function or an
12323     //   elaborated-type-specifier, the lookup to determine whether
12324     //   the entity has been previously declared shall not consider
12325     //   any scopes outside the innermost enclosing namespace.
12326     //
12327     // MSVC doesn't implement the above rule for types, so a friend tag
12328     // declaration may be a redeclaration of a type declared in an enclosing
12329     // scope.  They do implement this rule for friend functions.
12330     //
12331     // Does it matter that this should be by scope instead of by
12332     // semantic context?
12333     if (!Previous.empty() && TUK == TUK_Friend) {
12334       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12335       LookupResult::Filter F = Previous.makeFilter();
12336       bool FriendSawTagOutsideEnclosingNamespace = false;
12337       while (F.hasNext()) {
12338         NamedDecl *ND = F.next();
12339         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12340         if (DC->isFileContext() &&
12341             !EnclosingNS->Encloses(ND->getDeclContext())) {
12342           if (getLangOpts().MSVCCompat)
12343             FriendSawTagOutsideEnclosingNamespace = true;
12344           else
12345             F.erase();
12346         }
12347       }
12348       F.done();
12349 
12350       // Diagnose this MSVC extension in the easy case where lookup would have
12351       // unambiguously found something outside the enclosing namespace.
12352       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12353         NamedDecl *ND = Previous.getFoundDecl();
12354         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12355             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12356       }
12357     }
12358 
12359     // Note:  there used to be some attempt at recovery here.
12360     if (Previous.isAmbiguous())
12361       return nullptr;
12362 
12363     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12364       // FIXME: This makes sure that we ignore the contexts associated
12365       // with C structs, unions, and enums when looking for a matching
12366       // tag declaration or definition. See the similar lookup tweak
12367       // in Sema::LookupName; is there a better way to deal with this?
12368       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12369         SearchDC = SearchDC->getParent();
12370     }
12371   }
12372 
12373   if (Previous.isSingleResult() &&
12374       Previous.getFoundDecl()->isTemplateParameter()) {
12375     // Maybe we will complain about the shadowed template parameter.
12376     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12377     // Just pretend that we didn't see the previous declaration.
12378     Previous.clear();
12379   }
12380 
12381   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12382       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12383     // This is a declaration of or a reference to "std::bad_alloc".
12384     isStdBadAlloc = true;
12385 
12386     if (Previous.empty() && StdBadAlloc) {
12387       // std::bad_alloc has been implicitly declared (but made invisible to
12388       // name lookup). Fill in this implicit declaration as the previous
12389       // declaration, so that the declarations get chained appropriately.
12390       Previous.addDecl(getStdBadAlloc());
12391     }
12392   }
12393 
12394   // If we didn't find a previous declaration, and this is a reference
12395   // (or friend reference), move to the correct scope.  In C++, we
12396   // also need to do a redeclaration lookup there, just in case
12397   // there's a shadow friend decl.
12398   if (Name && Previous.empty() &&
12399       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12400     if (Invalid) goto CreateNewDecl;
12401     assert(SS.isEmpty());
12402 
12403     if (TUK == TUK_Reference) {
12404       // C++ [basic.scope.pdecl]p5:
12405       //   -- for an elaborated-type-specifier of the form
12406       //
12407       //          class-key identifier
12408       //
12409       //      if the elaborated-type-specifier is used in the
12410       //      decl-specifier-seq or parameter-declaration-clause of a
12411       //      function defined in namespace scope, the identifier is
12412       //      declared as a class-name in the namespace that contains
12413       //      the declaration; otherwise, except as a friend
12414       //      declaration, the identifier is declared in the smallest
12415       //      non-class, non-function-prototype scope that contains the
12416       //      declaration.
12417       //
12418       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12419       // C structs and unions.
12420       //
12421       // It is an error in C++ to declare (rather than define) an enum
12422       // type, including via an elaborated type specifier.  We'll
12423       // diagnose that later; for now, declare the enum in the same
12424       // scope as we would have picked for any other tag type.
12425       //
12426       // GNU C also supports this behavior as part of its incomplete
12427       // enum types extension, while GNU C++ does not.
12428       //
12429       // Find the context where we'll be declaring the tag.
12430       // FIXME: We would like to maintain the current DeclContext as the
12431       // lexical context,
12432       SearchDC = getTagInjectionContext(SearchDC);
12433 
12434       // Find the scope where we'll be declaring the tag.
12435       S = getTagInjectionScope(S, getLangOpts());
12436     } else {
12437       assert(TUK == TUK_Friend);
12438       // C++ [namespace.memdef]p3:
12439       //   If a friend declaration in a non-local class first declares a
12440       //   class or function, the friend class or function is a member of
12441       //   the innermost enclosing namespace.
12442       SearchDC = SearchDC->getEnclosingNamespaceContext();
12443     }
12444 
12445     // In C++, we need to do a redeclaration lookup to properly
12446     // diagnose some problems.
12447     // FIXME: redeclaration lookup is also used (with and without C++) to find a
12448     // hidden declaration so that we don't get ambiguity errors when using a
12449     // type declared by an elaborated-type-specifier.  In C that is not correct
12450     // and we should instead merge compatible types found by lookup.
12451     if (getLangOpts().CPlusPlus) {
12452       Previous.setRedeclarationKind(ForRedeclaration);
12453       LookupQualifiedName(Previous, SearchDC);
12454     } else {
12455       Previous.setRedeclarationKind(ForRedeclaration);
12456       LookupName(Previous, S);
12457     }
12458   }
12459 
12460   // If we have a known previous declaration to use, then use it.
12461   if (Previous.empty() && SkipBody && SkipBody->Previous)
12462     Previous.addDecl(SkipBody->Previous);
12463 
12464   if (!Previous.empty()) {
12465     NamedDecl *PrevDecl = Previous.getFoundDecl();
12466     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12467 
12468     // It's okay to have a tag decl in the same scope as a typedef
12469     // which hides a tag decl in the same scope.  Finding this
12470     // insanity with a redeclaration lookup can only actually happen
12471     // in C++.
12472     //
12473     // This is also okay for elaborated-type-specifiers, which is
12474     // technically forbidden by the current standard but which is
12475     // okay according to the likely resolution of an open issue;
12476     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12477     if (getLangOpts().CPlusPlus) {
12478       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12479         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12480           TagDecl *Tag = TT->getDecl();
12481           if (Tag->getDeclName() == Name &&
12482               Tag->getDeclContext()->getRedeclContext()
12483                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
12484             PrevDecl = Tag;
12485             Previous.clear();
12486             Previous.addDecl(Tag);
12487             Previous.resolveKind();
12488           }
12489         }
12490       }
12491     }
12492 
12493     // If this is a redeclaration of a using shadow declaration, it must
12494     // declare a tag in the same context. In MSVC mode, we allow a
12495     // redefinition if either context is within the other.
12496     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12497       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12498       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12499           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12500           !(OldTag && isAcceptableTagRedeclContext(
12501                           *this, OldTag->getDeclContext(), SearchDC))) {
12502         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12503         Diag(Shadow->getTargetDecl()->getLocation(),
12504              diag::note_using_decl_target);
12505         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12506             << 0;
12507         // Recover by ignoring the old declaration.
12508         Previous.clear();
12509         goto CreateNewDecl;
12510       }
12511     }
12512 
12513     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12514       // If this is a use of a previous tag, or if the tag is already declared
12515       // in the same scope (so that the definition/declaration completes or
12516       // rementions the tag), reuse the decl.
12517       if (TUK == TUK_Reference || TUK == TUK_Friend ||
12518           isDeclInScope(DirectPrevDecl, SearchDC, S,
12519                         SS.isNotEmpty() || isExplicitSpecialization)) {
12520         // Make sure that this wasn't declared as an enum and now used as a
12521         // struct or something similar.
12522         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12523                                           TUK == TUK_Definition, KWLoc,
12524                                           Name)) {
12525           bool SafeToContinue
12526             = (PrevTagDecl->getTagKind() != TTK_Enum &&
12527                Kind != TTK_Enum);
12528           if (SafeToContinue)
12529             Diag(KWLoc, diag::err_use_with_wrong_tag)
12530               << Name
12531               << FixItHint::CreateReplacement(SourceRange(KWLoc),
12532                                               PrevTagDecl->getKindName());
12533           else
12534             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12535           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12536 
12537           if (SafeToContinue)
12538             Kind = PrevTagDecl->getTagKind();
12539           else {
12540             // Recover by making this an anonymous redefinition.
12541             Name = nullptr;
12542             Previous.clear();
12543             Invalid = true;
12544           }
12545         }
12546 
12547         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12548           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12549 
12550           // If this is an elaborated-type-specifier for a scoped enumeration,
12551           // the 'class' keyword is not necessary and not permitted.
12552           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12553             if (ScopedEnum)
12554               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12555                 << PrevEnum->isScoped()
12556                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12557             return PrevTagDecl;
12558           }
12559 
12560           QualType EnumUnderlyingTy;
12561           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12562             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12563           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12564             EnumUnderlyingTy = QualType(T, 0);
12565 
12566           // All conflicts with previous declarations are recovered by
12567           // returning the previous declaration, unless this is a definition,
12568           // in which case we want the caller to bail out.
12569           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12570                                      ScopedEnum, EnumUnderlyingTy,
12571                                      EnumUnderlyingIsImplicit, PrevEnum))
12572             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12573         }
12574 
12575         // C++11 [class.mem]p1:
12576         //   A member shall not be declared twice in the member-specification,
12577         //   except that a nested class or member class template can be declared
12578         //   and then later defined.
12579         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12580             S->isDeclScope(PrevDecl)) {
12581           Diag(NameLoc, diag::ext_member_redeclared);
12582           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12583         }
12584 
12585         if (!Invalid) {
12586           // If this is a use, just return the declaration we found, unless
12587           // we have attributes.
12588           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12589             if (Attr) {
12590               // FIXME: Diagnose these attributes. For now, we create a new
12591               // declaration to hold them.
12592             } else if (TUK == TUK_Reference &&
12593                        (PrevTagDecl->getFriendObjectKind() ==
12594                             Decl::FOK_Undeclared ||
12595                         PP.getModuleContainingLocation(
12596                             PrevDecl->getLocation()) !=
12597                             PP.getModuleContainingLocation(KWLoc)) &&
12598                        SS.isEmpty()) {
12599               // This declaration is a reference to an existing entity, but
12600               // has different visibility from that entity: it either makes
12601               // a friend visible or it makes a type visible in a new module.
12602               // In either case, create a new declaration. We only do this if
12603               // the declaration would have meant the same thing if no prior
12604               // declaration were found, that is, if it was found in the same
12605               // scope where we would have injected a declaration.
12606               if (!getTagInjectionContext(CurContext)->getRedeclContext()
12607                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
12608                 return PrevTagDecl;
12609               // This is in the injected scope, create a new declaration in
12610               // that scope.
12611               S = getTagInjectionScope(S, getLangOpts());
12612             } else {
12613               return PrevTagDecl;
12614             }
12615           }
12616 
12617           // Diagnose attempts to redefine a tag.
12618           if (TUK == TUK_Definition) {
12619             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12620               // If we're defining a specialization and the previous definition
12621               // is from an implicit instantiation, don't emit an error
12622               // here; we'll catch this in the general case below.
12623               bool IsExplicitSpecializationAfterInstantiation = false;
12624               if (isExplicitSpecialization) {
12625                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12626                   IsExplicitSpecializationAfterInstantiation =
12627                     RD->getTemplateSpecializationKind() !=
12628                     TSK_ExplicitSpecialization;
12629                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12630                   IsExplicitSpecializationAfterInstantiation =
12631                     ED->getTemplateSpecializationKind() !=
12632                     TSK_ExplicitSpecialization;
12633               }
12634 
12635               NamedDecl *Hidden = nullptr;
12636               if (SkipBody && getLangOpts().CPlusPlus &&
12637                   !hasVisibleDefinition(Def, &Hidden)) {
12638                 // There is a definition of this tag, but it is not visible. We
12639                 // explicitly make use of C++'s one definition rule here, and
12640                 // assume that this definition is identical to the hidden one
12641                 // we already have. Make the existing definition visible and
12642                 // use it in place of this one.
12643                 SkipBody->ShouldSkip = true;
12644                 makeMergedDefinitionVisible(Hidden, KWLoc);
12645                 return Def;
12646               } else if (!IsExplicitSpecializationAfterInstantiation) {
12647                 // A redeclaration in function prototype scope in C isn't
12648                 // visible elsewhere, so merely issue a warning.
12649                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12650                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12651                 else
12652                   Diag(NameLoc, diag::err_redefinition) << Name;
12653                 Diag(Def->getLocation(), diag::note_previous_definition);
12654                 // If this is a redefinition, recover by making this
12655                 // struct be anonymous, which will make any later
12656                 // references get the previous definition.
12657                 Name = nullptr;
12658                 Previous.clear();
12659                 Invalid = true;
12660               }
12661             } else {
12662               // If the type is currently being defined, complain
12663               // about a nested redefinition.
12664               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12665               if (TD->isBeingDefined()) {
12666                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12667                 Diag(PrevTagDecl->getLocation(),
12668                      diag::note_previous_definition);
12669                 Name = nullptr;
12670                 Previous.clear();
12671                 Invalid = true;
12672               }
12673             }
12674 
12675             // Okay, this is definition of a previously declared or referenced
12676             // tag. We're going to create a new Decl for it.
12677           }
12678 
12679           // Okay, we're going to make a redeclaration.  If this is some kind
12680           // of reference, make sure we build the redeclaration in the same DC
12681           // as the original, and ignore the current access specifier.
12682           if (TUK == TUK_Friend || TUK == TUK_Reference) {
12683             SearchDC = PrevTagDecl->getDeclContext();
12684             AS = AS_none;
12685           }
12686         }
12687         // If we get here we have (another) forward declaration or we
12688         // have a definition.  Just create a new decl.
12689 
12690       } else {
12691         // If we get here, this is a definition of a new tag type in a nested
12692         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12693         // new decl/type.  We set PrevDecl to NULL so that the entities
12694         // have distinct types.
12695         Previous.clear();
12696       }
12697       // If we get here, we're going to create a new Decl. If PrevDecl
12698       // is non-NULL, it's a definition of the tag declared by
12699       // PrevDecl. If it's NULL, we have a new definition.
12700 
12701     // Otherwise, PrevDecl is not a tag, but was found with tag
12702     // lookup.  This is only actually possible in C++, where a few
12703     // things like templates still live in the tag namespace.
12704     } else {
12705       // Use a better diagnostic if an elaborated-type-specifier
12706       // found the wrong kind of type on the first
12707       // (non-redeclaration) lookup.
12708       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12709           !Previous.isForRedeclaration()) {
12710         unsigned Kind = 0;
12711         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12712         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12713         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12714         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12715         Diag(PrevDecl->getLocation(), diag::note_declared_at);
12716         Invalid = true;
12717 
12718       // Otherwise, only diagnose if the declaration is in scope.
12719       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12720                                 SS.isNotEmpty() || isExplicitSpecialization)) {
12721         // do nothing
12722 
12723       // Diagnose implicit declarations introduced by elaborated types.
12724       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12725         unsigned Kind = 0;
12726         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12727         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12728         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12729         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12730         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12731         Invalid = true;
12732 
12733       // Otherwise it's a declaration.  Call out a particularly common
12734       // case here.
12735       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12736         unsigned Kind = 0;
12737         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12738         Diag(NameLoc, diag::err_tag_definition_of_typedef)
12739           << Name << Kind << TND->getUnderlyingType();
12740         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12741         Invalid = true;
12742 
12743       // Otherwise, diagnose.
12744       } else {
12745         // The tag name clashes with something else in the target scope,
12746         // issue an error and recover by making this tag be anonymous.
12747         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12748         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12749         Name = nullptr;
12750         Invalid = true;
12751       }
12752 
12753       // The existing declaration isn't relevant to us; we're in a
12754       // new scope, so clear out the previous declaration.
12755       Previous.clear();
12756     }
12757   }
12758 
12759 CreateNewDecl:
12760 
12761   TagDecl *PrevDecl = nullptr;
12762   if (Previous.isSingleResult())
12763     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12764 
12765   // If there is an identifier, use the location of the identifier as the
12766   // location of the decl, otherwise use the location of the struct/union
12767   // keyword.
12768   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12769 
12770   // Otherwise, create a new declaration. If there is a previous
12771   // declaration of the same entity, the two will be linked via
12772   // PrevDecl.
12773   TagDecl *New;
12774 
12775   bool IsForwardReference = false;
12776   if (Kind == TTK_Enum) {
12777     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12778     // enum X { A, B, C } D;    D should chain to X.
12779     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12780                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12781                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12782     // If this is an undefined enum, warn.
12783     if (TUK != TUK_Definition && !Invalid) {
12784       TagDecl *Def;
12785       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12786           cast<EnumDecl>(New)->isFixed()) {
12787         // C++0x: 7.2p2: opaque-enum-declaration.
12788         // Conflicts are diagnosed above. Do nothing.
12789       }
12790       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12791         Diag(Loc, diag::ext_forward_ref_enum_def)
12792           << New;
12793         Diag(Def->getLocation(), diag::note_previous_definition);
12794       } else {
12795         unsigned DiagID = diag::ext_forward_ref_enum;
12796         if (getLangOpts().MSVCCompat)
12797           DiagID = diag::ext_ms_forward_ref_enum;
12798         else if (getLangOpts().CPlusPlus)
12799           DiagID = diag::err_forward_ref_enum;
12800         Diag(Loc, DiagID);
12801 
12802         // If this is a forward-declared reference to an enumeration, make a
12803         // note of it; we won't actually be introducing the declaration into
12804         // the declaration context.
12805         if (TUK == TUK_Reference)
12806           IsForwardReference = true;
12807       }
12808     }
12809 
12810     if (EnumUnderlying) {
12811       EnumDecl *ED = cast<EnumDecl>(New);
12812       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12813         ED->setIntegerTypeSourceInfo(TI);
12814       else
12815         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12816       ED->setPromotionType(ED->getIntegerType());
12817     }
12818   } else {
12819     // struct/union/class
12820 
12821     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12822     // struct X { int A; } D;    D should chain to X.
12823     if (getLangOpts().CPlusPlus) {
12824       // FIXME: Look for a way to use RecordDecl for simple structs.
12825       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12826                                   cast_or_null<CXXRecordDecl>(PrevDecl));
12827 
12828       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12829         StdBadAlloc = cast<CXXRecordDecl>(New);
12830     } else
12831       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12832                                cast_or_null<RecordDecl>(PrevDecl));
12833   }
12834 
12835   // C++11 [dcl.type]p3:
12836   //   A type-specifier-seq shall not define a class or enumeration [...].
12837   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12838     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12839       << Context.getTagDeclType(New);
12840     Invalid = true;
12841   }
12842 
12843   // Maybe add qualifier info.
12844   if (SS.isNotEmpty()) {
12845     if (SS.isSet()) {
12846       // If this is either a declaration or a definition, check the
12847       // nested-name-specifier against the current context. We don't do this
12848       // for explicit specializations, because they have similar checking
12849       // (with more specific diagnostics) in the call to
12850       // CheckMemberSpecialization, below.
12851       if (!isExplicitSpecialization &&
12852           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12853           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12854         Invalid = true;
12855 
12856       New->setQualifierInfo(SS.getWithLocInContext(Context));
12857       if (TemplateParameterLists.size() > 0) {
12858         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12859       }
12860     }
12861     else
12862       Invalid = true;
12863   }
12864 
12865   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12866     // Add alignment attributes if necessary; these attributes are checked when
12867     // the ASTContext lays out the structure.
12868     //
12869     // It is important for implementing the correct semantics that this
12870     // happen here (in act on tag decl). The #pragma pack stack is
12871     // maintained as a result of parser callbacks which can occur at
12872     // many points during the parsing of a struct declaration (because
12873     // the #pragma tokens are effectively skipped over during the
12874     // parsing of the struct).
12875     if (TUK == TUK_Definition) {
12876       AddAlignmentAttributesForRecord(RD);
12877       AddMsStructLayoutForRecord(RD);
12878     }
12879   }
12880 
12881   if (ModulePrivateLoc.isValid()) {
12882     if (isExplicitSpecialization)
12883       Diag(New->getLocation(), diag::err_module_private_specialization)
12884         << 2
12885         << FixItHint::CreateRemoval(ModulePrivateLoc);
12886     // __module_private__ does not apply to local classes. However, we only
12887     // diagnose this as an error when the declaration specifiers are
12888     // freestanding. Here, we just ignore the __module_private__.
12889     else if (!SearchDC->isFunctionOrMethod())
12890       New->setModulePrivate();
12891   }
12892 
12893   // If this is a specialization of a member class (of a class template),
12894   // check the specialization.
12895   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12896     Invalid = true;
12897 
12898   // If we're declaring or defining a tag in function prototype scope in C,
12899   // note that this type can only be used within the function and add it to
12900   // the list of decls to inject into the function definition scope.
12901   if ((Name || Kind == TTK_Enum) &&
12902       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12903     if (getLangOpts().CPlusPlus) {
12904       // C++ [dcl.fct]p6:
12905       //   Types shall not be defined in return or parameter types.
12906       if (TUK == TUK_Definition && !IsTypeSpecifier) {
12907         Diag(Loc, diag::err_type_defined_in_param_type)
12908             << Name;
12909         Invalid = true;
12910       }
12911     } else if (!PrevDecl) {
12912       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
12913     }
12914     DeclsInPrototypeScope.push_back(New);
12915   }
12916 
12917   if (Invalid)
12918     New->setInvalidDecl();
12919 
12920   if (Attr)
12921     ProcessDeclAttributeList(S, New, Attr);
12922 
12923   // Set the lexical context. If the tag has a C++ scope specifier, the
12924   // lexical context will be different from the semantic context.
12925   New->setLexicalDeclContext(CurContext);
12926 
12927   // Mark this as a friend decl if applicable.
12928   // In Microsoft mode, a friend declaration also acts as a forward
12929   // declaration so we always pass true to setObjectOfFriendDecl to make
12930   // the tag name visible.
12931   if (TUK == TUK_Friend)
12932     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
12933 
12934   // Set the access specifier.
12935   if (!Invalid && SearchDC->isRecord())
12936     SetMemberAccessSpecifier(New, PrevDecl, AS);
12937 
12938   if (TUK == TUK_Definition)
12939     New->startDefinition();
12940 
12941   // If this has an identifier, add it to the scope stack.
12942   if (TUK == TUK_Friend) {
12943     // We might be replacing an existing declaration in the lookup tables;
12944     // if so, borrow its access specifier.
12945     if (PrevDecl)
12946       New->setAccess(PrevDecl->getAccess());
12947 
12948     DeclContext *DC = New->getDeclContext()->getRedeclContext();
12949     DC->makeDeclVisibleInContext(New);
12950     if (Name) // can be null along some error paths
12951       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12952         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
12953   } else if (Name) {
12954     S = getNonFieldDeclScope(S);
12955     PushOnScopeChains(New, S, !IsForwardReference);
12956     if (IsForwardReference)
12957       SearchDC->makeDeclVisibleInContext(New);
12958   } else {
12959     CurContext->addDecl(New);
12960   }
12961 
12962   // If this is the C FILE type, notify the AST context.
12963   if (IdentifierInfo *II = New->getIdentifier())
12964     if (!New->isInvalidDecl() &&
12965         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
12966         II->isStr("FILE"))
12967       Context.setFILEDecl(New);
12968 
12969   if (PrevDecl)
12970     mergeDeclAttributes(New, PrevDecl);
12971 
12972   // If there's a #pragma GCC visibility in scope, set the visibility of this
12973   // record.
12974   AddPushedVisibilityAttribute(New);
12975 
12976   OwnedDecl = true;
12977   // In C++, don't return an invalid declaration. We can't recover well from
12978   // the cases where we make the type anonymous.
12979   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
12980 }
12981 
12982 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
12983   AdjustDeclIfTemplate(TagD);
12984   TagDecl *Tag = cast<TagDecl>(TagD);
12985 
12986   // Enter the tag context.
12987   PushDeclContext(S, Tag);
12988 
12989   ActOnDocumentableDecl(TagD);
12990 
12991   // If there's a #pragma GCC visibility in scope, set the visibility of this
12992   // record.
12993   AddPushedVisibilityAttribute(Tag);
12994 }
12995 
12996 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
12997   assert(isa<ObjCContainerDecl>(IDecl) &&
12998          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
12999   DeclContext *OCD = cast<DeclContext>(IDecl);
13000   assert(getContainingDC(OCD) == CurContext &&
13001       "The next DeclContext should be lexically contained in the current one.");
13002   CurContext = OCD;
13003   return IDecl;
13004 }
13005 
13006 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13007                                            SourceLocation FinalLoc,
13008                                            bool IsFinalSpelledSealed,
13009                                            SourceLocation LBraceLoc) {
13010   AdjustDeclIfTemplate(TagD);
13011   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13012 
13013   FieldCollector->StartClass();
13014 
13015   if (!Record->getIdentifier())
13016     return;
13017 
13018   if (FinalLoc.isValid())
13019     Record->addAttr(new (Context)
13020                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13021 
13022   // C++ [class]p2:
13023   //   [...] The class-name is also inserted into the scope of the
13024   //   class itself; this is known as the injected-class-name. For
13025   //   purposes of access checking, the injected-class-name is treated
13026   //   as if it were a public member name.
13027   CXXRecordDecl *InjectedClassName
13028     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13029                             Record->getLocStart(), Record->getLocation(),
13030                             Record->getIdentifier(),
13031                             /*PrevDecl=*/nullptr,
13032                             /*DelayTypeCreation=*/true);
13033   Context.getTypeDeclType(InjectedClassName, Record);
13034   InjectedClassName->setImplicit();
13035   InjectedClassName->setAccess(AS_public);
13036   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13037       InjectedClassName->setDescribedClassTemplate(Template);
13038   PushOnScopeChains(InjectedClassName, S);
13039   assert(InjectedClassName->isInjectedClassName() &&
13040          "Broken injected-class-name");
13041 }
13042 
13043 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13044                                     SourceLocation RBraceLoc) {
13045   AdjustDeclIfTemplate(TagD);
13046   TagDecl *Tag = cast<TagDecl>(TagD);
13047   Tag->setRBraceLoc(RBraceLoc);
13048 
13049   // Make sure we "complete" the definition even it is invalid.
13050   if (Tag->isBeingDefined()) {
13051     assert(Tag->isInvalidDecl() && "We should already have completed it");
13052     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13053       RD->completeDefinition();
13054   }
13055 
13056   if (isa<CXXRecordDecl>(Tag))
13057     FieldCollector->FinishClass();
13058 
13059   // Exit this scope of this tag's definition.
13060   PopDeclContext();
13061 
13062   if (getCurLexicalContext()->isObjCContainer() &&
13063       Tag->getDeclContext()->isFileContext())
13064     Tag->setTopLevelDeclInObjCContainer();
13065 
13066   // Notify the consumer that we've defined a tag.
13067   if (!Tag->isInvalidDecl())
13068     Consumer.HandleTagDeclDefinition(Tag);
13069 }
13070 
13071 void Sema::ActOnObjCContainerFinishDefinition() {
13072   // Exit this scope of this interface definition.
13073   PopDeclContext();
13074 }
13075 
13076 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13077   assert(DC == CurContext && "Mismatch of container contexts");
13078   OriginalLexicalContext = DC;
13079   ActOnObjCContainerFinishDefinition();
13080 }
13081 
13082 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13083   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13084   OriginalLexicalContext = nullptr;
13085 }
13086 
13087 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13088   AdjustDeclIfTemplate(TagD);
13089   TagDecl *Tag = cast<TagDecl>(TagD);
13090   Tag->setInvalidDecl();
13091 
13092   // Make sure we "complete" the definition even it is invalid.
13093   if (Tag->isBeingDefined()) {
13094     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13095       RD->completeDefinition();
13096   }
13097 
13098   // We're undoing ActOnTagStartDefinition here, not
13099   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13100   // the FieldCollector.
13101 
13102   PopDeclContext();
13103 }
13104 
13105 // Note that FieldName may be null for anonymous bitfields.
13106 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13107                                 IdentifierInfo *FieldName,
13108                                 QualType FieldTy, bool IsMsStruct,
13109                                 Expr *BitWidth, bool *ZeroWidth) {
13110   // Default to true; that shouldn't confuse checks for emptiness
13111   if (ZeroWidth)
13112     *ZeroWidth = true;
13113 
13114   // C99 6.7.2.1p4 - verify the field type.
13115   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13116   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13117     // Handle incomplete types with specific error.
13118     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13119       return ExprError();
13120     if (FieldName)
13121       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13122         << FieldName << FieldTy << BitWidth->getSourceRange();
13123     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13124       << FieldTy << BitWidth->getSourceRange();
13125   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13126                                              UPPC_BitFieldWidth))
13127     return ExprError();
13128 
13129   // If the bit-width is type- or value-dependent, don't try to check
13130   // it now.
13131   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13132     return BitWidth;
13133 
13134   llvm::APSInt Value;
13135   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13136   if (ICE.isInvalid())
13137     return ICE;
13138   BitWidth = ICE.get();
13139 
13140   if (Value != 0 && ZeroWidth)
13141     *ZeroWidth = false;
13142 
13143   // Zero-width bitfield is ok for anonymous field.
13144   if (Value == 0 && FieldName)
13145     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13146 
13147   if (Value.isSigned() && Value.isNegative()) {
13148     if (FieldName)
13149       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13150                << FieldName << Value.toString(10);
13151     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13152       << Value.toString(10);
13153   }
13154 
13155   if (!FieldTy->isDependentType()) {
13156     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13157     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13158     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13159 
13160     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13161     // ABI.
13162     bool CStdConstraintViolation =
13163         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13164     bool MSBitfieldViolation =
13165         Value.ugt(TypeStorageSize) &&
13166         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13167     if (CStdConstraintViolation || MSBitfieldViolation) {
13168       unsigned DiagWidth =
13169           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13170       if (FieldName)
13171         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13172                << FieldName << (unsigned)Value.getZExtValue()
13173                << !CStdConstraintViolation << DiagWidth;
13174 
13175       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13176              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13177              << DiagWidth;
13178     }
13179 
13180     // Warn on types where the user might conceivably expect to get all
13181     // specified bits as value bits: that's all integral types other than
13182     // 'bool'.
13183     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13184       if (FieldName)
13185         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13186             << FieldName << (unsigned)Value.getZExtValue()
13187             << (unsigned)TypeWidth;
13188       else
13189         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13190             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13191     }
13192   }
13193 
13194   return BitWidth;
13195 }
13196 
13197 /// ActOnField - Each field of a C struct/union is passed into this in order
13198 /// to create a FieldDecl object for it.
13199 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13200                        Declarator &D, Expr *BitfieldWidth) {
13201   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13202                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13203                                /*InitStyle=*/ICIS_NoInit, AS_public);
13204   return Res;
13205 }
13206 
13207 /// HandleField - Analyze a field of a C struct or a C++ data member.
13208 ///
13209 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13210                              SourceLocation DeclStart,
13211                              Declarator &D, Expr *BitWidth,
13212                              InClassInitStyle InitStyle,
13213                              AccessSpecifier AS) {
13214   IdentifierInfo *II = D.getIdentifier();
13215   SourceLocation Loc = DeclStart;
13216   if (II) Loc = D.getIdentifierLoc();
13217 
13218   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13219   QualType T = TInfo->getType();
13220   if (getLangOpts().CPlusPlus) {
13221     CheckExtraCXXDefaultArguments(D);
13222 
13223     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13224                                         UPPC_DataMemberType)) {
13225       D.setInvalidType();
13226       T = Context.IntTy;
13227       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13228     }
13229   }
13230 
13231   // TR 18037 does not allow fields to be declared with address spaces.
13232   if (T.getQualifiers().hasAddressSpace()) {
13233     Diag(Loc, diag::err_field_with_address_space);
13234     D.setInvalidType();
13235   }
13236 
13237   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13238   // used as structure or union field: image, sampler, event or block types.
13239   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13240                           T->isSamplerT() || T->isBlockPointerType())) {
13241     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13242     D.setInvalidType();
13243   }
13244 
13245   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13246 
13247   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13248     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13249          diag::err_invalid_thread)
13250       << DeclSpec::getSpecifierName(TSCS);
13251 
13252   // Check to see if this name was declared as a member previously
13253   NamedDecl *PrevDecl = nullptr;
13254   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13255   LookupName(Previous, S);
13256   switch (Previous.getResultKind()) {
13257     case LookupResult::Found:
13258     case LookupResult::FoundUnresolvedValue:
13259       PrevDecl = Previous.getAsSingle<NamedDecl>();
13260       break;
13261 
13262     case LookupResult::FoundOverloaded:
13263       PrevDecl = Previous.getRepresentativeDecl();
13264       break;
13265 
13266     case LookupResult::NotFound:
13267     case LookupResult::NotFoundInCurrentInstantiation:
13268     case LookupResult::Ambiguous:
13269       break;
13270   }
13271   Previous.suppressDiagnostics();
13272 
13273   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13274     // Maybe we will complain about the shadowed template parameter.
13275     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13276     // Just pretend that we didn't see the previous declaration.
13277     PrevDecl = nullptr;
13278   }
13279 
13280   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13281     PrevDecl = nullptr;
13282 
13283   bool Mutable
13284     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13285   SourceLocation TSSL = D.getLocStart();
13286   FieldDecl *NewFD
13287     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13288                      TSSL, AS, PrevDecl, &D);
13289 
13290   if (NewFD->isInvalidDecl())
13291     Record->setInvalidDecl();
13292 
13293   if (D.getDeclSpec().isModulePrivateSpecified())
13294     NewFD->setModulePrivate();
13295 
13296   if (NewFD->isInvalidDecl() && PrevDecl) {
13297     // Don't introduce NewFD into scope; there's already something
13298     // with the same name in the same scope.
13299   } else if (II) {
13300     PushOnScopeChains(NewFD, S);
13301   } else
13302     Record->addDecl(NewFD);
13303 
13304   return NewFD;
13305 }
13306 
13307 /// \brief Build a new FieldDecl and check its well-formedness.
13308 ///
13309 /// This routine builds a new FieldDecl given the fields name, type,
13310 /// record, etc. \p PrevDecl should refer to any previous declaration
13311 /// with the same name and in the same scope as the field to be
13312 /// created.
13313 ///
13314 /// \returns a new FieldDecl.
13315 ///
13316 /// \todo The Declarator argument is a hack. It will be removed once
13317 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13318                                 TypeSourceInfo *TInfo,
13319                                 RecordDecl *Record, SourceLocation Loc,
13320                                 bool Mutable, Expr *BitWidth,
13321                                 InClassInitStyle InitStyle,
13322                                 SourceLocation TSSL,
13323                                 AccessSpecifier AS, NamedDecl *PrevDecl,
13324                                 Declarator *D) {
13325   IdentifierInfo *II = Name.getAsIdentifierInfo();
13326   bool InvalidDecl = false;
13327   if (D) InvalidDecl = D->isInvalidType();
13328 
13329   // If we receive a broken type, recover by assuming 'int' and
13330   // marking this declaration as invalid.
13331   if (T.isNull()) {
13332     InvalidDecl = true;
13333     T = Context.IntTy;
13334   }
13335 
13336   QualType EltTy = Context.getBaseElementType(T);
13337   if (!EltTy->isDependentType()) {
13338     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13339       // Fields of incomplete type force their record to be invalid.
13340       Record->setInvalidDecl();
13341       InvalidDecl = true;
13342     } else {
13343       NamedDecl *Def;
13344       EltTy->isIncompleteType(&Def);
13345       if (Def && Def->isInvalidDecl()) {
13346         Record->setInvalidDecl();
13347         InvalidDecl = true;
13348       }
13349     }
13350   }
13351 
13352   // OpenCL v1.2 s6.9.c: bitfields are not supported.
13353   if (BitWidth && getLangOpts().OpenCL) {
13354     Diag(Loc, diag::err_opencl_bitfields);
13355     InvalidDecl = true;
13356   }
13357 
13358   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13359   // than a variably modified type.
13360   if (!InvalidDecl && T->isVariablyModifiedType()) {
13361     bool SizeIsNegative;
13362     llvm::APSInt Oversized;
13363 
13364     TypeSourceInfo *FixedTInfo =
13365       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13366                                                     SizeIsNegative,
13367                                                     Oversized);
13368     if (FixedTInfo) {
13369       Diag(Loc, diag::warn_illegal_constant_array_size);
13370       TInfo = FixedTInfo;
13371       T = FixedTInfo->getType();
13372     } else {
13373       if (SizeIsNegative)
13374         Diag(Loc, diag::err_typecheck_negative_array_size);
13375       else if (Oversized.getBoolValue())
13376         Diag(Loc, diag::err_array_too_large)
13377           << Oversized.toString(10);
13378       else
13379         Diag(Loc, diag::err_typecheck_field_variable_size);
13380       InvalidDecl = true;
13381     }
13382   }
13383 
13384   // Fields can not have abstract class types
13385   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13386                                              diag::err_abstract_type_in_decl,
13387                                              AbstractFieldType))
13388     InvalidDecl = true;
13389 
13390   bool ZeroWidth = false;
13391   if (InvalidDecl)
13392     BitWidth = nullptr;
13393   // If this is declared as a bit-field, check the bit-field.
13394   if (BitWidth) {
13395     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13396                               &ZeroWidth).get();
13397     if (!BitWidth) {
13398       InvalidDecl = true;
13399       BitWidth = nullptr;
13400       ZeroWidth = false;
13401     }
13402   }
13403 
13404   // Check that 'mutable' is consistent with the type of the declaration.
13405   if (!InvalidDecl && Mutable) {
13406     unsigned DiagID = 0;
13407     if (T->isReferenceType())
13408       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13409                                         : diag::err_mutable_reference;
13410     else if (T.isConstQualified())
13411       DiagID = diag::err_mutable_const;
13412 
13413     if (DiagID) {
13414       SourceLocation ErrLoc = Loc;
13415       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13416         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13417       Diag(ErrLoc, DiagID);
13418       if (DiagID != diag::ext_mutable_reference) {
13419         Mutable = false;
13420         InvalidDecl = true;
13421       }
13422     }
13423   }
13424 
13425   // C++11 [class.union]p8 (DR1460):
13426   //   At most one variant member of a union may have a
13427   //   brace-or-equal-initializer.
13428   if (InitStyle != ICIS_NoInit)
13429     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13430 
13431   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13432                                        BitWidth, Mutable, InitStyle);
13433   if (InvalidDecl)
13434     NewFD->setInvalidDecl();
13435 
13436   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13437     Diag(Loc, diag::err_duplicate_member) << II;
13438     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13439     NewFD->setInvalidDecl();
13440   }
13441 
13442   if (!InvalidDecl && getLangOpts().CPlusPlus) {
13443     if (Record->isUnion()) {
13444       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13445         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13446         if (RDecl->getDefinition()) {
13447           // C++ [class.union]p1: An object of a class with a non-trivial
13448           // constructor, a non-trivial copy constructor, a non-trivial
13449           // destructor, or a non-trivial copy assignment operator
13450           // cannot be a member of a union, nor can an array of such
13451           // objects.
13452           if (CheckNontrivialField(NewFD))
13453             NewFD->setInvalidDecl();
13454         }
13455       }
13456 
13457       // C++ [class.union]p1: If a union contains a member of reference type,
13458       // the program is ill-formed, except when compiling with MSVC extensions
13459       // enabled.
13460       if (EltTy->isReferenceType()) {
13461         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13462                                     diag::ext_union_member_of_reference_type :
13463                                     diag::err_union_member_of_reference_type)
13464           << NewFD->getDeclName() << EltTy;
13465         if (!getLangOpts().MicrosoftExt)
13466           NewFD->setInvalidDecl();
13467       }
13468     }
13469   }
13470 
13471   // FIXME: We need to pass in the attributes given an AST
13472   // representation, not a parser representation.
13473   if (D) {
13474     // FIXME: The current scope is almost... but not entirely... correct here.
13475     ProcessDeclAttributes(getCurScope(), NewFD, *D);
13476 
13477     if (NewFD->hasAttrs())
13478       CheckAlignasUnderalignment(NewFD);
13479   }
13480 
13481   // In auto-retain/release, infer strong retension for fields of
13482   // retainable type.
13483   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13484     NewFD->setInvalidDecl();
13485 
13486   if (T.isObjCGCWeak())
13487     Diag(Loc, diag::warn_attribute_weak_on_field);
13488 
13489   NewFD->setAccess(AS);
13490   return NewFD;
13491 }
13492 
13493 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13494   assert(FD);
13495   assert(getLangOpts().CPlusPlus && "valid check only for C++");
13496 
13497   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13498     return false;
13499 
13500   QualType EltTy = Context.getBaseElementType(FD->getType());
13501   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13502     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13503     if (RDecl->getDefinition()) {
13504       // We check for copy constructors before constructors
13505       // because otherwise we'll never get complaints about
13506       // copy constructors.
13507 
13508       CXXSpecialMember member = CXXInvalid;
13509       // We're required to check for any non-trivial constructors. Since the
13510       // implicit default constructor is suppressed if there are any
13511       // user-declared constructors, we just need to check that there is a
13512       // trivial default constructor and a trivial copy constructor. (We don't
13513       // worry about move constructors here, since this is a C++98 check.)
13514       if (RDecl->hasNonTrivialCopyConstructor())
13515         member = CXXCopyConstructor;
13516       else if (!RDecl->hasTrivialDefaultConstructor())
13517         member = CXXDefaultConstructor;
13518       else if (RDecl->hasNonTrivialCopyAssignment())
13519         member = CXXCopyAssignment;
13520       else if (RDecl->hasNonTrivialDestructor())
13521         member = CXXDestructor;
13522 
13523       if (member != CXXInvalid) {
13524         if (!getLangOpts().CPlusPlus11 &&
13525             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13526           // Objective-C++ ARC: it is an error to have a non-trivial field of
13527           // a union. However, system headers in Objective-C programs
13528           // occasionally have Objective-C lifetime objects within unions,
13529           // and rather than cause the program to fail, we make those
13530           // members unavailable.
13531           SourceLocation Loc = FD->getLocation();
13532           if (getSourceManager().isInSystemHeader(Loc)) {
13533             if (!FD->hasAttr<UnavailableAttr>())
13534               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13535                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13536             return false;
13537           }
13538         }
13539 
13540         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13541                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13542                diag::err_illegal_union_or_anon_struct_member)
13543           << FD->getParent()->isUnion() << FD->getDeclName() << member;
13544         DiagnoseNontrivial(RDecl, member);
13545         return !getLangOpts().CPlusPlus11;
13546       }
13547     }
13548   }
13549 
13550   return false;
13551 }
13552 
13553 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13554 ///  AST enum value.
13555 static ObjCIvarDecl::AccessControl
13556 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13557   switch (ivarVisibility) {
13558   default: llvm_unreachable("Unknown visitibility kind");
13559   case tok::objc_private: return ObjCIvarDecl::Private;
13560   case tok::objc_public: return ObjCIvarDecl::Public;
13561   case tok::objc_protected: return ObjCIvarDecl::Protected;
13562   case tok::objc_package: return ObjCIvarDecl::Package;
13563   }
13564 }
13565 
13566 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13567 /// in order to create an IvarDecl object for it.
13568 Decl *Sema::ActOnIvar(Scope *S,
13569                                 SourceLocation DeclStart,
13570                                 Declarator &D, Expr *BitfieldWidth,
13571                                 tok::ObjCKeywordKind Visibility) {
13572 
13573   IdentifierInfo *II = D.getIdentifier();
13574   Expr *BitWidth = (Expr*)BitfieldWidth;
13575   SourceLocation Loc = DeclStart;
13576   if (II) Loc = D.getIdentifierLoc();
13577 
13578   // FIXME: Unnamed fields can be handled in various different ways, for
13579   // example, unnamed unions inject all members into the struct namespace!
13580 
13581   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13582   QualType T = TInfo->getType();
13583 
13584   if (BitWidth) {
13585     // 6.7.2.1p3, 6.7.2.1p4
13586     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13587     if (!BitWidth)
13588       D.setInvalidType();
13589   } else {
13590     // Not a bitfield.
13591 
13592     // validate II.
13593 
13594   }
13595   if (T->isReferenceType()) {
13596     Diag(Loc, diag::err_ivar_reference_type);
13597     D.setInvalidType();
13598   }
13599   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13600   // than a variably modified type.
13601   else if (T->isVariablyModifiedType()) {
13602     Diag(Loc, diag::err_typecheck_ivar_variable_size);
13603     D.setInvalidType();
13604   }
13605 
13606   // Get the visibility (access control) for this ivar.
13607   ObjCIvarDecl::AccessControl ac =
13608     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13609                                         : ObjCIvarDecl::None;
13610   // Must set ivar's DeclContext to its enclosing interface.
13611   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13612   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13613     return nullptr;
13614   ObjCContainerDecl *EnclosingContext;
13615   if (ObjCImplementationDecl *IMPDecl =
13616       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13617     if (LangOpts.ObjCRuntime.isFragile()) {
13618     // Case of ivar declared in an implementation. Context is that of its class.
13619       EnclosingContext = IMPDecl->getClassInterface();
13620       assert(EnclosingContext && "Implementation has no class interface!");
13621     }
13622     else
13623       EnclosingContext = EnclosingDecl;
13624   } else {
13625     if (ObjCCategoryDecl *CDecl =
13626         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13627       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13628         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13629         return nullptr;
13630       }
13631     }
13632     EnclosingContext = EnclosingDecl;
13633   }
13634 
13635   // Construct the decl.
13636   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13637                                              DeclStart, Loc, II, T,
13638                                              TInfo, ac, (Expr *)BitfieldWidth);
13639 
13640   if (II) {
13641     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13642                                            ForRedeclaration);
13643     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13644         && !isa<TagDecl>(PrevDecl)) {
13645       Diag(Loc, diag::err_duplicate_member) << II;
13646       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13647       NewID->setInvalidDecl();
13648     }
13649   }
13650 
13651   // Process attributes attached to the ivar.
13652   ProcessDeclAttributes(S, NewID, D);
13653 
13654   if (D.isInvalidType())
13655     NewID->setInvalidDecl();
13656 
13657   // In ARC, infer 'retaining' for ivars of retainable type.
13658   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13659     NewID->setInvalidDecl();
13660 
13661   if (D.getDeclSpec().isModulePrivateSpecified())
13662     NewID->setModulePrivate();
13663 
13664   if (II) {
13665     // FIXME: When interfaces are DeclContexts, we'll need to add
13666     // these to the interface.
13667     S->AddDecl(NewID);
13668     IdResolver.AddDecl(NewID);
13669   }
13670 
13671   if (LangOpts.ObjCRuntime.isNonFragile() &&
13672       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13673     Diag(Loc, diag::warn_ivars_in_interface);
13674 
13675   return NewID;
13676 }
13677 
13678 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13679 /// class and class extensions. For every class \@interface and class
13680 /// extension \@interface, if the last ivar is a bitfield of any type,
13681 /// then add an implicit `char :0` ivar to the end of that interface.
13682 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13683                              SmallVectorImpl<Decl *> &AllIvarDecls) {
13684   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13685     return;
13686 
13687   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13688   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13689 
13690   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13691     return;
13692   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13693   if (!ID) {
13694     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13695       if (!CD->IsClassExtension())
13696         return;
13697     }
13698     // No need to add this to end of @implementation.
13699     else
13700       return;
13701   }
13702   // All conditions are met. Add a new bitfield to the tail end of ivars.
13703   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13704   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13705 
13706   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13707                               DeclLoc, DeclLoc, nullptr,
13708                               Context.CharTy,
13709                               Context.getTrivialTypeSourceInfo(Context.CharTy,
13710                                                                DeclLoc),
13711                               ObjCIvarDecl::Private, BW,
13712                               true);
13713   AllIvarDecls.push_back(Ivar);
13714 }
13715 
13716 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13717                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
13718                        SourceLocation RBrac, AttributeList *Attr) {
13719   assert(EnclosingDecl && "missing record or interface decl");
13720 
13721   // If this is an Objective-C @implementation or category and we have
13722   // new fields here we should reset the layout of the interface since
13723   // it will now change.
13724   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13725     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13726     switch (DC->getKind()) {
13727     default: break;
13728     case Decl::ObjCCategory:
13729       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13730       break;
13731     case Decl::ObjCImplementation:
13732       Context.
13733         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13734       break;
13735     }
13736   }
13737 
13738   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13739 
13740   // Start counting up the number of named members; make sure to include
13741   // members of anonymous structs and unions in the total.
13742   unsigned NumNamedMembers = 0;
13743   if (Record) {
13744     for (const auto *I : Record->decls()) {
13745       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13746         if (IFD->getDeclName())
13747           ++NumNamedMembers;
13748     }
13749   }
13750 
13751   // Verify that all the fields are okay.
13752   SmallVector<FieldDecl*, 32> RecFields;
13753 
13754   bool ARCErrReported = false;
13755   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13756        i != end; ++i) {
13757     FieldDecl *FD = cast<FieldDecl>(*i);
13758 
13759     // Get the type for the field.
13760     const Type *FDTy = FD->getType().getTypePtr();
13761 
13762     if (!FD->isAnonymousStructOrUnion()) {
13763       // Remember all fields written by the user.
13764       RecFields.push_back(FD);
13765     }
13766 
13767     // If the field is already invalid for some reason, don't emit more
13768     // diagnostics about it.
13769     if (FD->isInvalidDecl()) {
13770       EnclosingDecl->setInvalidDecl();
13771       continue;
13772     }
13773 
13774     // C99 6.7.2.1p2:
13775     //   A structure or union shall not contain a member with
13776     //   incomplete or function type (hence, a structure shall not
13777     //   contain an instance of itself, but may contain a pointer to
13778     //   an instance of itself), except that the last member of a
13779     //   structure with more than one named member may have incomplete
13780     //   array type; such a structure (and any union containing,
13781     //   possibly recursively, a member that is such a structure)
13782     //   shall not be a member of a structure or an element of an
13783     //   array.
13784     if (FDTy->isFunctionType()) {
13785       // Field declared as a function.
13786       Diag(FD->getLocation(), diag::err_field_declared_as_function)
13787         << FD->getDeclName();
13788       FD->setInvalidDecl();
13789       EnclosingDecl->setInvalidDecl();
13790       continue;
13791     } else if (FDTy->isIncompleteArrayType() && Record &&
13792                ((i + 1 == Fields.end() && !Record->isUnion()) ||
13793                 ((getLangOpts().MicrosoftExt ||
13794                   getLangOpts().CPlusPlus) &&
13795                  (i + 1 == Fields.end() || Record->isUnion())))) {
13796       // Flexible array member.
13797       // Microsoft and g++ is more permissive regarding flexible array.
13798       // It will accept flexible array in union and also
13799       // as the sole element of a struct/class.
13800       unsigned DiagID = 0;
13801       if (Record->isUnion())
13802         DiagID = getLangOpts().MicrosoftExt
13803                      ? diag::ext_flexible_array_union_ms
13804                      : getLangOpts().CPlusPlus
13805                            ? diag::ext_flexible_array_union_gnu
13806                            : diag::err_flexible_array_union;
13807       else if (Fields.size() == 1)
13808         DiagID = getLangOpts().MicrosoftExt
13809                      ? diag::ext_flexible_array_empty_aggregate_ms
13810                      : getLangOpts().CPlusPlus
13811                            ? diag::ext_flexible_array_empty_aggregate_gnu
13812                            : NumNamedMembers < 1
13813                                  ? diag::err_flexible_array_empty_aggregate
13814                                  : 0;
13815 
13816       if (DiagID)
13817         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13818                                         << Record->getTagKind();
13819       // While the layout of types that contain virtual bases is not specified
13820       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13821       // virtual bases after the derived members.  This would make a flexible
13822       // array member declared at the end of an object not adjacent to the end
13823       // of the type.
13824       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13825         if (RD->getNumVBases() != 0)
13826           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13827             << FD->getDeclName() << Record->getTagKind();
13828       if (!getLangOpts().C99)
13829         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13830           << FD->getDeclName() << Record->getTagKind();
13831 
13832       // If the element type has a non-trivial destructor, we would not
13833       // implicitly destroy the elements, so disallow it for now.
13834       //
13835       // FIXME: GCC allows this. We should probably either implicitly delete
13836       // the destructor of the containing class, or just allow this.
13837       QualType BaseElem = Context.getBaseElementType(FD->getType());
13838       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13839         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13840           << FD->getDeclName() << FD->getType();
13841         FD->setInvalidDecl();
13842         EnclosingDecl->setInvalidDecl();
13843         continue;
13844       }
13845       // Okay, we have a legal flexible array member at the end of the struct.
13846       Record->setHasFlexibleArrayMember(true);
13847     } else if (!FDTy->isDependentType() &&
13848                RequireCompleteType(FD->getLocation(), FD->getType(),
13849                                    diag::err_field_incomplete)) {
13850       // Incomplete type
13851       FD->setInvalidDecl();
13852       EnclosingDecl->setInvalidDecl();
13853       continue;
13854     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13855       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13856         // A type which contains a flexible array member is considered to be a
13857         // flexible array member.
13858         Record->setHasFlexibleArrayMember(true);
13859         if (!Record->isUnion()) {
13860           // If this is a struct/class and this is not the last element, reject
13861           // it.  Note that GCC supports variable sized arrays in the middle of
13862           // structures.
13863           if (i + 1 != Fields.end())
13864             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13865               << FD->getDeclName() << FD->getType();
13866           else {
13867             // We support flexible arrays at the end of structs in
13868             // other structs as an extension.
13869             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13870               << FD->getDeclName();
13871           }
13872         }
13873       }
13874       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13875           RequireNonAbstractType(FD->getLocation(), FD->getType(),
13876                                  diag::err_abstract_type_in_decl,
13877                                  AbstractIvarType)) {
13878         // Ivars can not have abstract class types
13879         FD->setInvalidDecl();
13880       }
13881       if (Record && FDTTy->getDecl()->hasObjectMember())
13882         Record->setHasObjectMember(true);
13883       if (Record && FDTTy->getDecl()->hasVolatileMember())
13884         Record->setHasVolatileMember(true);
13885     } else if (FDTy->isObjCObjectType()) {
13886       /// A field cannot be an Objective-c object
13887       Diag(FD->getLocation(), diag::err_statically_allocated_object)
13888         << FixItHint::CreateInsertion(FD->getLocation(), "*");
13889       QualType T = Context.getObjCObjectPointerType(FD->getType());
13890       FD->setType(T);
13891     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13892                (!getLangOpts().CPlusPlus || Record->isUnion())) {
13893       // It's an error in ARC if a field has lifetime.
13894       // We don't want to report this in a system header, though,
13895       // so we just make the field unavailable.
13896       // FIXME: that's really not sufficient; we need to make the type
13897       // itself invalid to, say, initialize or copy.
13898       QualType T = FD->getType();
13899       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
13900       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13901         SourceLocation loc = FD->getLocation();
13902         if (getSourceManager().isInSystemHeader(loc)) {
13903           if (!FD->hasAttr<UnavailableAttr>()) {
13904             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13905                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
13906           }
13907         } else {
13908           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
13909             << T->isBlockPointerType() << Record->getTagKind();
13910         }
13911         ARCErrReported = true;
13912       }
13913     } else if (getLangOpts().ObjC1 &&
13914                getLangOpts().getGC() != LangOptions::NonGC &&
13915                Record && !Record->hasObjectMember()) {
13916       if (FD->getType()->isObjCObjectPointerType() ||
13917           FD->getType().isObjCGCStrong())
13918         Record->setHasObjectMember(true);
13919       else if (Context.getAsArrayType(FD->getType())) {
13920         QualType BaseType = Context.getBaseElementType(FD->getType());
13921         if (BaseType->isRecordType() &&
13922             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
13923           Record->setHasObjectMember(true);
13924         else if (BaseType->isObjCObjectPointerType() ||
13925                  BaseType.isObjCGCStrong())
13926                Record->setHasObjectMember(true);
13927       }
13928     }
13929     if (Record && FD->getType().isVolatileQualified())
13930       Record->setHasVolatileMember(true);
13931     // Keep track of the number of named members.
13932     if (FD->getIdentifier())
13933       ++NumNamedMembers;
13934   }
13935 
13936   // Okay, we successfully defined 'Record'.
13937   if (Record) {
13938     bool Completed = false;
13939     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
13940       if (!CXXRecord->isInvalidDecl()) {
13941         // Set access bits correctly on the directly-declared conversions.
13942         for (CXXRecordDecl::conversion_iterator
13943                I = CXXRecord->conversion_begin(),
13944                E = CXXRecord->conversion_end(); I != E; ++I)
13945           I.setAccess((*I)->getAccess());
13946       }
13947 
13948       if (!CXXRecord->isDependentType()) {
13949         if (CXXRecord->hasUserDeclaredDestructor()) {
13950           // Adjust user-defined destructor exception spec.
13951           if (getLangOpts().CPlusPlus11)
13952             AdjustDestructorExceptionSpec(CXXRecord,
13953                                           CXXRecord->getDestructor());
13954         }
13955 
13956         if (!CXXRecord->isInvalidDecl()) {
13957           // Add any implicitly-declared members to this class.
13958           AddImplicitlyDeclaredMembersToClass(CXXRecord);
13959 
13960           // If we have virtual base classes, we may end up finding multiple
13961           // final overriders for a given virtual function. Check for this
13962           // problem now.
13963           if (CXXRecord->getNumVBases()) {
13964             CXXFinalOverriderMap FinalOverriders;
13965             CXXRecord->getFinalOverriders(FinalOverriders);
13966 
13967             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
13968                                              MEnd = FinalOverriders.end();
13969                  M != MEnd; ++M) {
13970               for (OverridingMethods::iterator SO = M->second.begin(),
13971                                             SOEnd = M->second.end();
13972                    SO != SOEnd; ++SO) {
13973                 assert(SO->second.size() > 0 &&
13974                        "Virtual function without overridding functions?");
13975                 if (SO->second.size() == 1)
13976                   continue;
13977 
13978                 // C++ [class.virtual]p2:
13979                 //   In a derived class, if a virtual member function of a base
13980                 //   class subobject has more than one final overrider the
13981                 //   program is ill-formed.
13982                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
13983                   << (const NamedDecl *)M->first << Record;
13984                 Diag(M->first->getLocation(),
13985                      diag::note_overridden_virtual_function);
13986                 for (OverridingMethods::overriding_iterator
13987                           OM = SO->second.begin(),
13988                        OMEnd = SO->second.end();
13989                      OM != OMEnd; ++OM)
13990                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
13991                     << (const NamedDecl *)M->first << OM->Method->getParent();
13992 
13993                 Record->setInvalidDecl();
13994               }
13995             }
13996             CXXRecord->completeDefinition(&FinalOverriders);
13997             Completed = true;
13998           }
13999         }
14000       }
14001     }
14002 
14003     if (!Completed)
14004       Record->completeDefinition();
14005 
14006     if (Record->hasAttrs()) {
14007       CheckAlignasUnderalignment(Record);
14008 
14009       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14010         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14011                                            IA->getRange(), IA->getBestCase(),
14012                                            IA->getSemanticSpelling());
14013     }
14014 
14015     // Check if the structure/union declaration is a type that can have zero
14016     // size in C. For C this is a language extension, for C++ it may cause
14017     // compatibility problems.
14018     bool CheckForZeroSize;
14019     if (!getLangOpts().CPlusPlus) {
14020       CheckForZeroSize = true;
14021     } else {
14022       // For C++ filter out types that cannot be referenced in C code.
14023       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14024       CheckForZeroSize =
14025           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14026           !CXXRecord->isDependentType() &&
14027           CXXRecord->isCLike();
14028     }
14029     if (CheckForZeroSize) {
14030       bool ZeroSize = true;
14031       bool IsEmpty = true;
14032       unsigned NonBitFields = 0;
14033       for (RecordDecl::field_iterator I = Record->field_begin(),
14034                                       E = Record->field_end();
14035            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14036         IsEmpty = false;
14037         if (I->isUnnamedBitfield()) {
14038           if (I->getBitWidthValue(Context) > 0)
14039             ZeroSize = false;
14040         } else {
14041           ++NonBitFields;
14042           QualType FieldType = I->getType();
14043           if (FieldType->isIncompleteType() ||
14044               !Context.getTypeSizeInChars(FieldType).isZero())
14045             ZeroSize = false;
14046         }
14047       }
14048 
14049       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14050       // allowed in C++, but warn if its declaration is inside
14051       // extern "C" block.
14052       if (ZeroSize) {
14053         Diag(RecLoc, getLangOpts().CPlusPlus ?
14054                          diag::warn_zero_size_struct_union_in_extern_c :
14055                          diag::warn_zero_size_struct_union_compat)
14056           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14057       }
14058 
14059       // Structs without named members are extension in C (C99 6.7.2.1p7),
14060       // but are accepted by GCC.
14061       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14062         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14063                                diag::ext_no_named_members_in_struct_union)
14064           << Record->isUnion();
14065       }
14066     }
14067   } else {
14068     ObjCIvarDecl **ClsFields =
14069       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14070     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14071       ID->setEndOfDefinitionLoc(RBrac);
14072       // Add ivar's to class's DeclContext.
14073       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14074         ClsFields[i]->setLexicalDeclContext(ID);
14075         ID->addDecl(ClsFields[i]);
14076       }
14077       // Must enforce the rule that ivars in the base classes may not be
14078       // duplicates.
14079       if (ID->getSuperClass())
14080         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14081     } else if (ObjCImplementationDecl *IMPDecl =
14082                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14083       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14084       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14085         // Ivar declared in @implementation never belongs to the implementation.
14086         // Only it is in implementation's lexical context.
14087         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14088       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14089       IMPDecl->setIvarLBraceLoc(LBrac);
14090       IMPDecl->setIvarRBraceLoc(RBrac);
14091     } else if (ObjCCategoryDecl *CDecl =
14092                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14093       // case of ivars in class extension; all other cases have been
14094       // reported as errors elsewhere.
14095       // FIXME. Class extension does not have a LocEnd field.
14096       // CDecl->setLocEnd(RBrac);
14097       // Add ivar's to class extension's DeclContext.
14098       // Diagnose redeclaration of private ivars.
14099       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14100       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14101         if (IDecl) {
14102           if (const ObjCIvarDecl *ClsIvar =
14103               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14104             Diag(ClsFields[i]->getLocation(),
14105                  diag::err_duplicate_ivar_declaration);
14106             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14107             continue;
14108           }
14109           for (const auto *Ext : IDecl->known_extensions()) {
14110             if (const ObjCIvarDecl *ClsExtIvar
14111                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14112               Diag(ClsFields[i]->getLocation(),
14113                    diag::err_duplicate_ivar_declaration);
14114               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14115               continue;
14116             }
14117           }
14118         }
14119         ClsFields[i]->setLexicalDeclContext(CDecl);
14120         CDecl->addDecl(ClsFields[i]);
14121       }
14122       CDecl->setIvarLBraceLoc(LBrac);
14123       CDecl->setIvarRBraceLoc(RBrac);
14124     }
14125   }
14126 
14127   if (Attr)
14128     ProcessDeclAttributeList(S, Record, Attr);
14129 }
14130 
14131 /// \brief Determine whether the given integral value is representable within
14132 /// the given type T.
14133 static bool isRepresentableIntegerValue(ASTContext &Context,
14134                                         llvm::APSInt &Value,
14135                                         QualType T) {
14136   assert(T->isIntegralType(Context) && "Integral type required!");
14137   unsigned BitWidth = Context.getIntWidth(T);
14138 
14139   if (Value.isUnsigned() || Value.isNonNegative()) {
14140     if (T->isSignedIntegerOrEnumerationType())
14141       --BitWidth;
14142     return Value.getActiveBits() <= BitWidth;
14143   }
14144   return Value.getMinSignedBits() <= BitWidth;
14145 }
14146 
14147 // \brief Given an integral type, return the next larger integral type
14148 // (or a NULL type of no such type exists).
14149 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14150   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14151   // enum checking below.
14152   assert(T->isIntegralType(Context) && "Integral type required!");
14153   const unsigned NumTypes = 4;
14154   QualType SignedIntegralTypes[NumTypes] = {
14155     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14156   };
14157   QualType UnsignedIntegralTypes[NumTypes] = {
14158     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14159     Context.UnsignedLongLongTy
14160   };
14161 
14162   unsigned BitWidth = Context.getTypeSize(T);
14163   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14164                                                         : UnsignedIntegralTypes;
14165   for (unsigned I = 0; I != NumTypes; ++I)
14166     if (Context.getTypeSize(Types[I]) > BitWidth)
14167       return Types[I];
14168 
14169   return QualType();
14170 }
14171 
14172 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14173                                           EnumConstantDecl *LastEnumConst,
14174                                           SourceLocation IdLoc,
14175                                           IdentifierInfo *Id,
14176                                           Expr *Val) {
14177   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14178   llvm::APSInt EnumVal(IntWidth);
14179   QualType EltTy;
14180 
14181   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14182     Val = nullptr;
14183 
14184   if (Val)
14185     Val = DefaultLvalueConversion(Val).get();
14186 
14187   if (Val) {
14188     if (Enum->isDependentType() || Val->isTypeDependent())
14189       EltTy = Context.DependentTy;
14190     else {
14191       SourceLocation ExpLoc;
14192       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14193           !getLangOpts().MSVCCompat) {
14194         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14195         // constant-expression in the enumerator-definition shall be a converted
14196         // constant expression of the underlying type.
14197         EltTy = Enum->getIntegerType();
14198         ExprResult Converted =
14199           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14200                                            CCEK_Enumerator);
14201         if (Converted.isInvalid())
14202           Val = nullptr;
14203         else
14204           Val = Converted.get();
14205       } else if (!Val->isValueDependent() &&
14206                  !(Val = VerifyIntegerConstantExpression(Val,
14207                                                          &EnumVal).get())) {
14208         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14209       } else {
14210         if (Enum->isFixed()) {
14211           EltTy = Enum->getIntegerType();
14212 
14213           // In Obj-C and Microsoft mode, require the enumeration value to be
14214           // representable in the underlying type of the enumeration. In C++11,
14215           // we perform a non-narrowing conversion as part of converted constant
14216           // expression checking.
14217           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14218             if (getLangOpts().MSVCCompat) {
14219               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14220               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14221             } else
14222               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14223           } else
14224             Val = ImpCastExprToType(Val, EltTy,
14225                                     EltTy->isBooleanType() ?
14226                                     CK_IntegralToBoolean : CK_IntegralCast)
14227                     .get();
14228         } else if (getLangOpts().CPlusPlus) {
14229           // C++11 [dcl.enum]p5:
14230           //   If the underlying type is not fixed, the type of each enumerator
14231           //   is the type of its initializing value:
14232           //     - If an initializer is specified for an enumerator, the
14233           //       initializing value has the same type as the expression.
14234           EltTy = Val->getType();
14235         } else {
14236           // C99 6.7.2.2p2:
14237           //   The expression that defines the value of an enumeration constant
14238           //   shall be an integer constant expression that has a value
14239           //   representable as an int.
14240 
14241           // Complain if the value is not representable in an int.
14242           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14243             Diag(IdLoc, diag::ext_enum_value_not_int)
14244               << EnumVal.toString(10) << Val->getSourceRange()
14245               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14246           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14247             // Force the type of the expression to 'int'.
14248             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14249           }
14250           EltTy = Val->getType();
14251         }
14252       }
14253     }
14254   }
14255 
14256   if (!Val) {
14257     if (Enum->isDependentType())
14258       EltTy = Context.DependentTy;
14259     else if (!LastEnumConst) {
14260       // C++0x [dcl.enum]p5:
14261       //   If the underlying type is not fixed, the type of each enumerator
14262       //   is the type of its initializing value:
14263       //     - If no initializer is specified for the first enumerator, the
14264       //       initializing value has an unspecified integral type.
14265       //
14266       // GCC uses 'int' for its unspecified integral type, as does
14267       // C99 6.7.2.2p3.
14268       if (Enum->isFixed()) {
14269         EltTy = Enum->getIntegerType();
14270       }
14271       else {
14272         EltTy = Context.IntTy;
14273       }
14274     } else {
14275       // Assign the last value + 1.
14276       EnumVal = LastEnumConst->getInitVal();
14277       ++EnumVal;
14278       EltTy = LastEnumConst->getType();
14279 
14280       // Check for overflow on increment.
14281       if (EnumVal < LastEnumConst->getInitVal()) {
14282         // C++0x [dcl.enum]p5:
14283         //   If the underlying type is not fixed, the type of each enumerator
14284         //   is the type of its initializing value:
14285         //
14286         //     - Otherwise the type of the initializing value is the same as
14287         //       the type of the initializing value of the preceding enumerator
14288         //       unless the incremented value is not representable in that type,
14289         //       in which case the type is an unspecified integral type
14290         //       sufficient to contain the incremented value. If no such type
14291         //       exists, the program is ill-formed.
14292         QualType T = getNextLargerIntegralType(Context, EltTy);
14293         if (T.isNull() || Enum->isFixed()) {
14294           // There is no integral type larger enough to represent this
14295           // value. Complain, then allow the value to wrap around.
14296           EnumVal = LastEnumConst->getInitVal();
14297           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14298           ++EnumVal;
14299           if (Enum->isFixed())
14300             // When the underlying type is fixed, this is ill-formed.
14301             Diag(IdLoc, diag::err_enumerator_wrapped)
14302               << EnumVal.toString(10)
14303               << EltTy;
14304           else
14305             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14306               << EnumVal.toString(10);
14307         } else {
14308           EltTy = T;
14309         }
14310 
14311         // Retrieve the last enumerator's value, extent that type to the
14312         // type that is supposed to be large enough to represent the incremented
14313         // value, then increment.
14314         EnumVal = LastEnumConst->getInitVal();
14315         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14316         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14317         ++EnumVal;
14318 
14319         // If we're not in C++, diagnose the overflow of enumerator values,
14320         // which in C99 means that the enumerator value is not representable in
14321         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14322         // permits enumerator values that are representable in some larger
14323         // integral type.
14324         if (!getLangOpts().CPlusPlus && !T.isNull())
14325           Diag(IdLoc, diag::warn_enum_value_overflow);
14326       } else if (!getLangOpts().CPlusPlus &&
14327                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14328         // Enforce C99 6.7.2.2p2 even when we compute the next value.
14329         Diag(IdLoc, diag::ext_enum_value_not_int)
14330           << EnumVal.toString(10) << 1;
14331       }
14332     }
14333   }
14334 
14335   if (!EltTy->isDependentType()) {
14336     // Make the enumerator value match the signedness and size of the
14337     // enumerator's type.
14338     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14339     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14340   }
14341 
14342   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14343                                   Val, EnumVal);
14344 }
14345 
14346 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14347                                                 SourceLocation IILoc) {
14348   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14349       !getLangOpts().CPlusPlus)
14350     return SkipBodyInfo();
14351 
14352   // We have an anonymous enum definition. Look up the first enumerator to
14353   // determine if we should merge the definition with an existing one and
14354   // skip the body.
14355   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14356                                          ForRedeclaration);
14357   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14358   if (!PrevECD)
14359     return SkipBodyInfo();
14360 
14361   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14362   NamedDecl *Hidden;
14363   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14364     SkipBodyInfo Skip;
14365     Skip.Previous = Hidden;
14366     return Skip;
14367   }
14368 
14369   return SkipBodyInfo();
14370 }
14371 
14372 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14373                               SourceLocation IdLoc, IdentifierInfo *Id,
14374                               AttributeList *Attr,
14375                               SourceLocation EqualLoc, Expr *Val) {
14376   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14377   EnumConstantDecl *LastEnumConst =
14378     cast_or_null<EnumConstantDecl>(lastEnumConst);
14379 
14380   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14381   // we find one that is.
14382   S = getNonFieldDeclScope(S);
14383 
14384   // Verify that there isn't already something declared with this name in this
14385   // scope.
14386   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14387                                          ForRedeclaration);
14388   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14389     // Maybe we will complain about the shadowed template parameter.
14390     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14391     // Just pretend that we didn't see the previous declaration.
14392     PrevDecl = nullptr;
14393   }
14394 
14395   // C++ [class.mem]p15:
14396   // If T is the name of a class, then each of the following shall have a name
14397   // different from T:
14398   // - every enumerator of every member of class T that is an unscoped
14399   // enumerated type
14400   if (!TheEnumDecl->isScoped())
14401     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14402                             DeclarationNameInfo(Id, IdLoc));
14403 
14404   EnumConstantDecl *New =
14405     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14406   if (!New)
14407     return nullptr;
14408 
14409   if (PrevDecl) {
14410     // When in C++, we may get a TagDecl with the same name; in this case the
14411     // enum constant will 'hide' the tag.
14412     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14413            "Received TagDecl when not in C++!");
14414     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14415         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14416       if (isa<EnumConstantDecl>(PrevDecl))
14417         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14418       else
14419         Diag(IdLoc, diag::err_redefinition) << Id;
14420       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14421       return nullptr;
14422     }
14423   }
14424 
14425   // Process attributes.
14426   if (Attr) ProcessDeclAttributeList(S, New, Attr);
14427 
14428   // Register this decl in the current scope stack.
14429   New->setAccess(TheEnumDecl->getAccess());
14430   PushOnScopeChains(New, S);
14431 
14432   ActOnDocumentableDecl(New);
14433 
14434   return New;
14435 }
14436 
14437 // Returns true when the enum initial expression does not trigger the
14438 // duplicate enum warning.  A few common cases are exempted as follows:
14439 // Element2 = Element1
14440 // Element2 = Element1 + 1
14441 // Element2 = Element1 - 1
14442 // Where Element2 and Element1 are from the same enum.
14443 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14444   Expr *InitExpr = ECD->getInitExpr();
14445   if (!InitExpr)
14446     return true;
14447   InitExpr = InitExpr->IgnoreImpCasts();
14448 
14449   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14450     if (!BO->isAdditiveOp())
14451       return true;
14452     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14453     if (!IL)
14454       return true;
14455     if (IL->getValue() != 1)
14456       return true;
14457 
14458     InitExpr = BO->getLHS();
14459   }
14460 
14461   // This checks if the elements are from the same enum.
14462   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14463   if (!DRE)
14464     return true;
14465 
14466   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14467   if (!EnumConstant)
14468     return true;
14469 
14470   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14471       Enum)
14472     return true;
14473 
14474   return false;
14475 }
14476 
14477 namespace {
14478 struct DupKey {
14479   int64_t val;
14480   bool isTombstoneOrEmptyKey;
14481   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14482     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14483 };
14484 
14485 static DupKey GetDupKey(const llvm::APSInt& Val) {
14486   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14487                 false);
14488 }
14489 
14490 struct DenseMapInfoDupKey {
14491   static DupKey getEmptyKey() { return DupKey(0, true); }
14492   static DupKey getTombstoneKey() { return DupKey(1, true); }
14493   static unsigned getHashValue(const DupKey Key) {
14494     return (unsigned)(Key.val * 37);
14495   }
14496   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14497     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14498            LHS.val == RHS.val;
14499   }
14500 };
14501 } // end anonymous namespace
14502 
14503 // Emits a warning when an element is implicitly set a value that
14504 // a previous element has already been set to.
14505 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14506                                         EnumDecl *Enum,
14507                                         QualType EnumType) {
14508   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14509     return;
14510   // Avoid anonymous enums
14511   if (!Enum->getIdentifier())
14512     return;
14513 
14514   // Only check for small enums.
14515   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14516     return;
14517 
14518   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14519   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14520 
14521   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14522   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14523           ValueToVectorMap;
14524 
14525   DuplicatesVector DupVector;
14526   ValueToVectorMap EnumMap;
14527 
14528   // Populate the EnumMap with all values represented by enum constants without
14529   // an initialier.
14530   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14531     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14532 
14533     // Null EnumConstantDecl means a previous diagnostic has been emitted for
14534     // this constant.  Skip this enum since it may be ill-formed.
14535     if (!ECD) {
14536       return;
14537     }
14538 
14539     if (ECD->getInitExpr())
14540       continue;
14541 
14542     DupKey Key = GetDupKey(ECD->getInitVal());
14543     DeclOrVector &Entry = EnumMap[Key];
14544 
14545     // First time encountering this value.
14546     if (Entry.isNull())
14547       Entry = ECD;
14548   }
14549 
14550   // Create vectors for any values that has duplicates.
14551   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14552     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14553     if (!ValidDuplicateEnum(ECD, Enum))
14554       continue;
14555 
14556     DupKey Key = GetDupKey(ECD->getInitVal());
14557 
14558     DeclOrVector& Entry = EnumMap[Key];
14559     if (Entry.isNull())
14560       continue;
14561 
14562     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14563       // Ensure constants are different.
14564       if (D == ECD)
14565         continue;
14566 
14567       // Create new vector and push values onto it.
14568       ECDVector *Vec = new ECDVector();
14569       Vec->push_back(D);
14570       Vec->push_back(ECD);
14571 
14572       // Update entry to point to the duplicates vector.
14573       Entry = Vec;
14574 
14575       // Store the vector somewhere we can consult later for quick emission of
14576       // diagnostics.
14577       DupVector.push_back(Vec);
14578       continue;
14579     }
14580 
14581     ECDVector *Vec = Entry.get<ECDVector*>();
14582     // Make sure constants are not added more than once.
14583     if (*Vec->begin() == ECD)
14584       continue;
14585 
14586     Vec->push_back(ECD);
14587   }
14588 
14589   // Emit diagnostics.
14590   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14591                                   DupVectorEnd = DupVector.end();
14592        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14593     ECDVector *Vec = *DupVectorIter;
14594     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14595 
14596     // Emit warning for one enum constant.
14597     ECDVector::iterator I = Vec->begin();
14598     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14599       << (*I)->getName() << (*I)->getInitVal().toString(10)
14600       << (*I)->getSourceRange();
14601     ++I;
14602 
14603     // Emit one note for each of the remaining enum constants with
14604     // the same value.
14605     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14606       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14607         << (*I)->getName() << (*I)->getInitVal().toString(10)
14608         << (*I)->getSourceRange();
14609     delete Vec;
14610   }
14611 }
14612 
14613 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14614                              bool AllowMask) const {
14615   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14616   assert(ED->isCompleteDefinition() && "expected enum definition");
14617 
14618   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14619   llvm::APInt &FlagBits = R.first->second;
14620 
14621   if (R.second) {
14622     for (auto *E : ED->enumerators()) {
14623       const auto &EVal = E->getInitVal();
14624       // Only single-bit enumerators introduce new flag values.
14625       if (EVal.isPowerOf2())
14626         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14627     }
14628   }
14629 
14630   // A value is in a flag enum if either its bits are a subset of the enum's
14631   // flag bits (the first condition) or we are allowing masks and the same is
14632   // true of its complement (the second condition). When masks are allowed, we
14633   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14634   //
14635   // While it's true that any value could be used as a mask, the assumption is
14636   // that a mask will have all of the insignificant bits set. Anything else is
14637   // likely a logic error.
14638   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14639   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14640 }
14641 
14642 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14643                          SourceLocation RBraceLoc, Decl *EnumDeclX,
14644                          ArrayRef<Decl *> Elements,
14645                          Scope *S, AttributeList *Attr) {
14646   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14647   QualType EnumType = Context.getTypeDeclType(Enum);
14648 
14649   if (Attr)
14650     ProcessDeclAttributeList(S, Enum, Attr);
14651 
14652   if (Enum->isDependentType()) {
14653     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14654       EnumConstantDecl *ECD =
14655         cast_or_null<EnumConstantDecl>(Elements[i]);
14656       if (!ECD) continue;
14657 
14658       ECD->setType(EnumType);
14659     }
14660 
14661     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14662     return;
14663   }
14664 
14665   // TODO: If the result value doesn't fit in an int, it must be a long or long
14666   // long value.  ISO C does not support this, but GCC does as an extension,
14667   // emit a warning.
14668   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14669   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14670   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14671 
14672   // Verify that all the values are okay, compute the size of the values, and
14673   // reverse the list.
14674   unsigned NumNegativeBits = 0;
14675   unsigned NumPositiveBits = 0;
14676 
14677   // Keep track of whether all elements have type int.
14678   bool AllElementsInt = true;
14679 
14680   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14681     EnumConstantDecl *ECD =
14682       cast_or_null<EnumConstantDecl>(Elements[i]);
14683     if (!ECD) continue;  // Already issued a diagnostic.
14684 
14685     const llvm::APSInt &InitVal = ECD->getInitVal();
14686 
14687     // Keep track of the size of positive and negative values.
14688     if (InitVal.isUnsigned() || InitVal.isNonNegative())
14689       NumPositiveBits = std::max(NumPositiveBits,
14690                                  (unsigned)InitVal.getActiveBits());
14691     else
14692       NumNegativeBits = std::max(NumNegativeBits,
14693                                  (unsigned)InitVal.getMinSignedBits());
14694 
14695     // Keep track of whether every enum element has type int (very commmon).
14696     if (AllElementsInt)
14697       AllElementsInt = ECD->getType() == Context.IntTy;
14698   }
14699 
14700   // Figure out the type that should be used for this enum.
14701   QualType BestType;
14702   unsigned BestWidth;
14703 
14704   // C++0x N3000 [conv.prom]p3:
14705   //   An rvalue of an unscoped enumeration type whose underlying
14706   //   type is not fixed can be converted to an rvalue of the first
14707   //   of the following types that can represent all the values of
14708   //   the enumeration: int, unsigned int, long int, unsigned long
14709   //   int, long long int, or unsigned long long int.
14710   // C99 6.4.4.3p2:
14711   //   An identifier declared as an enumeration constant has type int.
14712   // The C99 rule is modified by a gcc extension
14713   QualType BestPromotionType;
14714 
14715   bool Packed = Enum->hasAttr<PackedAttr>();
14716   // -fshort-enums is the equivalent to specifying the packed attribute on all
14717   // enum definitions.
14718   if (LangOpts.ShortEnums)
14719     Packed = true;
14720 
14721   if (Enum->isFixed()) {
14722     BestType = Enum->getIntegerType();
14723     if (BestType->isPromotableIntegerType())
14724       BestPromotionType = Context.getPromotedIntegerType(BestType);
14725     else
14726       BestPromotionType = BestType;
14727 
14728     BestWidth = Context.getIntWidth(BestType);
14729   }
14730   else if (NumNegativeBits) {
14731     // If there is a negative value, figure out the smallest integer type (of
14732     // int/long/longlong) that fits.
14733     // If it's packed, check also if it fits a char or a short.
14734     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14735       BestType = Context.SignedCharTy;
14736       BestWidth = CharWidth;
14737     } else if (Packed && NumNegativeBits <= ShortWidth &&
14738                NumPositiveBits < ShortWidth) {
14739       BestType = Context.ShortTy;
14740       BestWidth = ShortWidth;
14741     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14742       BestType = Context.IntTy;
14743       BestWidth = IntWidth;
14744     } else {
14745       BestWidth = Context.getTargetInfo().getLongWidth();
14746 
14747       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14748         BestType = Context.LongTy;
14749       } else {
14750         BestWidth = Context.getTargetInfo().getLongLongWidth();
14751 
14752         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14753           Diag(Enum->getLocation(), diag::ext_enum_too_large);
14754         BestType = Context.LongLongTy;
14755       }
14756     }
14757     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14758   } else {
14759     // If there is no negative value, figure out the smallest type that fits
14760     // all of the enumerator values.
14761     // If it's packed, check also if it fits a char or a short.
14762     if (Packed && NumPositiveBits <= CharWidth) {
14763       BestType = Context.UnsignedCharTy;
14764       BestPromotionType = Context.IntTy;
14765       BestWidth = CharWidth;
14766     } else if (Packed && NumPositiveBits <= ShortWidth) {
14767       BestType = Context.UnsignedShortTy;
14768       BestPromotionType = Context.IntTy;
14769       BestWidth = ShortWidth;
14770     } else if (NumPositiveBits <= IntWidth) {
14771       BestType = Context.UnsignedIntTy;
14772       BestWidth = IntWidth;
14773       BestPromotionType
14774         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14775                            ? Context.UnsignedIntTy : Context.IntTy;
14776     } else if (NumPositiveBits <=
14777                (BestWidth = Context.getTargetInfo().getLongWidth())) {
14778       BestType = Context.UnsignedLongTy;
14779       BestPromotionType
14780         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14781                            ? Context.UnsignedLongTy : Context.LongTy;
14782     } else {
14783       BestWidth = Context.getTargetInfo().getLongLongWidth();
14784       assert(NumPositiveBits <= BestWidth &&
14785              "How could an initializer get larger than ULL?");
14786       BestType = Context.UnsignedLongLongTy;
14787       BestPromotionType
14788         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14789                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
14790     }
14791   }
14792 
14793   // Loop over all of the enumerator constants, changing their types to match
14794   // the type of the enum if needed.
14795   for (auto *D : Elements) {
14796     auto *ECD = cast_or_null<EnumConstantDecl>(D);
14797     if (!ECD) continue;  // Already issued a diagnostic.
14798 
14799     // Standard C says the enumerators have int type, but we allow, as an
14800     // extension, the enumerators to be larger than int size.  If each
14801     // enumerator value fits in an int, type it as an int, otherwise type it the
14802     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
14803     // that X has type 'int', not 'unsigned'.
14804 
14805     // Determine whether the value fits into an int.
14806     llvm::APSInt InitVal = ECD->getInitVal();
14807 
14808     // If it fits into an integer type, force it.  Otherwise force it to match
14809     // the enum decl type.
14810     QualType NewTy;
14811     unsigned NewWidth;
14812     bool NewSign;
14813     if (!getLangOpts().CPlusPlus &&
14814         !Enum->isFixed() &&
14815         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14816       NewTy = Context.IntTy;
14817       NewWidth = IntWidth;
14818       NewSign = true;
14819     } else if (ECD->getType() == BestType) {
14820       // Already the right type!
14821       if (getLangOpts().CPlusPlus)
14822         // C++ [dcl.enum]p4: Following the closing brace of an
14823         // enum-specifier, each enumerator has the type of its
14824         // enumeration.
14825         ECD->setType(EnumType);
14826       continue;
14827     } else {
14828       NewTy = BestType;
14829       NewWidth = BestWidth;
14830       NewSign = BestType->isSignedIntegerOrEnumerationType();
14831     }
14832 
14833     // Adjust the APSInt value.
14834     InitVal = InitVal.extOrTrunc(NewWidth);
14835     InitVal.setIsSigned(NewSign);
14836     ECD->setInitVal(InitVal);
14837 
14838     // Adjust the Expr initializer and type.
14839     if (ECD->getInitExpr() &&
14840         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14841       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14842                                                 CK_IntegralCast,
14843                                                 ECD->getInitExpr(),
14844                                                 /*base paths*/ nullptr,
14845                                                 VK_RValue));
14846     if (getLangOpts().CPlusPlus)
14847       // C++ [dcl.enum]p4: Following the closing brace of an
14848       // enum-specifier, each enumerator has the type of its
14849       // enumeration.
14850       ECD->setType(EnumType);
14851     else
14852       ECD->setType(NewTy);
14853   }
14854 
14855   Enum->completeDefinition(BestType, BestPromotionType,
14856                            NumPositiveBits, NumNegativeBits);
14857 
14858   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14859 
14860   if (Enum->hasAttr<FlagEnumAttr>()) {
14861     for (Decl *D : Elements) {
14862       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14863       if (!ECD) continue;  // Already issued a diagnostic.
14864 
14865       llvm::APSInt InitVal = ECD->getInitVal();
14866       if (InitVal != 0 && !InitVal.isPowerOf2() &&
14867           !IsValueInFlagEnum(Enum, InitVal, true))
14868         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14869           << ECD << Enum;
14870     }
14871   }
14872 
14873   // Now that the enum type is defined, ensure it's not been underaligned.
14874   if (Enum->hasAttrs())
14875     CheckAlignasUnderalignment(Enum);
14876 }
14877 
14878 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
14879                                   SourceLocation StartLoc,
14880                                   SourceLocation EndLoc) {
14881   StringLiteral *AsmString = cast<StringLiteral>(expr);
14882 
14883   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
14884                                                    AsmString, StartLoc,
14885                                                    EndLoc);
14886   CurContext->addDecl(New);
14887   return New;
14888 }
14889 
14890 static void checkModuleImportContext(Sema &S, Module *M,
14891                                      SourceLocation ImportLoc, DeclContext *DC,
14892                                      bool FromInclude = false) {
14893   SourceLocation ExternCLoc;
14894 
14895   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14896     switch (LSD->getLanguage()) {
14897     case LinkageSpecDecl::lang_c:
14898       if (ExternCLoc.isInvalid())
14899         ExternCLoc = LSD->getLocStart();
14900       break;
14901     case LinkageSpecDecl::lang_cxx:
14902       break;
14903     }
14904     DC = LSD->getParent();
14905   }
14906 
14907   while (isa<LinkageSpecDecl>(DC))
14908     DC = DC->getParent();
14909 
14910   if (!isa<TranslationUnitDecl>(DC)) {
14911     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
14912                           ? diag::ext_module_import_not_at_top_level_noop
14913                           : diag::err_module_import_not_at_top_level_fatal)
14914         << M->getFullModuleName() << DC;
14915     S.Diag(cast<Decl>(DC)->getLocStart(),
14916            diag::note_module_import_not_at_top_level) << DC;
14917   } else if (!M->IsExternC && ExternCLoc.isValid()) {
14918     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
14919       << M->getFullModuleName();
14920     S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
14921   }
14922 }
14923 
14924 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
14925   return checkModuleImportContext(*this, M, ImportLoc, CurContext);
14926 }
14927 
14928 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
14929                                    SourceLocation ImportLoc,
14930                                    ModuleIdPath Path) {
14931   Module *Mod =
14932       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
14933                                    /*IsIncludeDirective=*/false);
14934   if (!Mod)
14935     return true;
14936 
14937   VisibleModules.setVisible(Mod, ImportLoc);
14938 
14939   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
14940 
14941   // FIXME: we should support importing a submodule within a different submodule
14942   // of the same top-level module. Until we do, make it an error rather than
14943   // silently ignoring the import.
14944   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
14945     Diag(ImportLoc, getLangOpts().CompilingModule
14946                         ? diag::err_module_self_import
14947                         : diag::err_module_import_in_implementation)
14948         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
14949 
14950   SmallVector<SourceLocation, 2> IdentifierLocs;
14951   Module *ModCheck = Mod;
14952   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
14953     // If we've run out of module parents, just drop the remaining identifiers.
14954     // We need the length to be consistent.
14955     if (!ModCheck)
14956       break;
14957     ModCheck = ModCheck->Parent;
14958 
14959     IdentifierLocs.push_back(Path[I].second);
14960   }
14961 
14962   ImportDecl *Import = ImportDecl::Create(Context,
14963                                           Context.getTranslationUnitDecl(),
14964                                           AtLoc.isValid()? AtLoc : ImportLoc,
14965                                           Mod, IdentifierLocs);
14966   Context.getTranslationUnitDecl()->addDecl(Import);
14967   return Import;
14968 }
14969 
14970 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
14971   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
14972 
14973   // Determine whether we're in the #include buffer for a module. The #includes
14974   // in that buffer do not qualify as module imports; they're just an
14975   // implementation detail of us building the module.
14976   //
14977   // FIXME: Should we even get ActOnModuleInclude calls for those?
14978   bool IsInModuleIncludes =
14979       TUKind == TU_Module &&
14980       getSourceManager().isWrittenInMainFile(DirectiveLoc);
14981 
14982   // Similarly, if we're in the implementation of a module, don't
14983   // synthesize an illegal module import. FIXME: Why not?
14984   bool ShouldAddImport =
14985       !IsInModuleIncludes &&
14986       (getLangOpts().CompilingModule ||
14987        getLangOpts().CurrentModule.empty() ||
14988        getLangOpts().CurrentModule != Mod->getTopLevelModuleName());
14989 
14990   // If this module import was due to an inclusion directive, create an
14991   // implicit import declaration to capture it in the AST.
14992   if (ShouldAddImport) {
14993     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14994     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14995                                                      DirectiveLoc, Mod,
14996                                                      DirectiveLoc);
14997     TU->addDecl(ImportD);
14998     Consumer.HandleImplicitImportDecl(ImportD);
14999   }
15000 
15001   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15002   VisibleModules.setVisible(Mod, DirectiveLoc);
15003 }
15004 
15005 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15006   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15007 
15008   if (getLangOpts().ModulesLocalVisibility)
15009     VisibleModulesStack.push_back(std::move(VisibleModules));
15010   VisibleModules.setVisible(Mod, DirectiveLoc);
15011 }
15012 
15013 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
15014   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15015 
15016   if (getLangOpts().ModulesLocalVisibility) {
15017     VisibleModules = std::move(VisibleModulesStack.back());
15018     VisibleModulesStack.pop_back();
15019     VisibleModules.setVisible(Mod, DirectiveLoc);
15020     // Leaving a module hides namespace names, so our visible namespace cache
15021     // is now out of date.
15022     VisibleNamespaceCache.clear();
15023   }
15024 }
15025 
15026 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15027                                                       Module *Mod) {
15028   // Bail if we're not allowed to implicitly import a module here.
15029   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15030     return;
15031 
15032   // Create the implicit import declaration.
15033   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15034   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15035                                                    Loc, Mod, Loc);
15036   TU->addDecl(ImportD);
15037   Consumer.HandleImplicitImportDecl(ImportD);
15038 
15039   // Make the module visible.
15040   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15041   VisibleModules.setVisible(Mod, Loc);
15042 }
15043 
15044 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15045                                       IdentifierInfo* AliasName,
15046                                       SourceLocation PragmaLoc,
15047                                       SourceLocation NameLoc,
15048                                       SourceLocation AliasNameLoc) {
15049   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15050                                          LookupOrdinaryName);
15051   AsmLabelAttr *Attr =
15052       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15053 
15054   // If a declaration that:
15055   // 1) declares a function or a variable
15056   // 2) has external linkage
15057   // already exists, add a label attribute to it.
15058   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15059     if (isDeclExternC(PrevDecl))
15060       PrevDecl->addAttr(Attr);
15061     else
15062       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15063           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15064   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15065   } else
15066     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15067 }
15068 
15069 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15070                              SourceLocation PragmaLoc,
15071                              SourceLocation NameLoc) {
15072   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15073 
15074   if (PrevDecl) {
15075     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15076   } else {
15077     (void)WeakUndeclaredIdentifiers.insert(
15078       std::pair<IdentifierInfo*,WeakInfo>
15079         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15080   }
15081 }
15082 
15083 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15084                                 IdentifierInfo* AliasName,
15085                                 SourceLocation PragmaLoc,
15086                                 SourceLocation NameLoc,
15087                                 SourceLocation AliasNameLoc) {
15088   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15089                                     LookupOrdinaryName);
15090   WeakInfo W = WeakInfo(Name, NameLoc);
15091 
15092   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15093     if (!PrevDecl->hasAttr<AliasAttr>())
15094       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15095         DeclApplyPragmaWeak(TUScope, ND, W);
15096   } else {
15097     (void)WeakUndeclaredIdentifiers.insert(
15098       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15099   }
15100 }
15101 
15102 Decl *Sema::getObjCDeclContext() const {
15103   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15104 }
15105 
15106 AvailabilityResult Sema::getCurContextAvailability() const {
15107   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
15108   if (!D)
15109     return AR_Available;
15110 
15111   // If we are within an Objective-C method, we should consult
15112   // both the availability of the method as well as the
15113   // enclosing class.  If the class is (say) deprecated,
15114   // the entire method is considered deprecated from the
15115   // purpose of checking if the current context is deprecated.
15116   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
15117     AvailabilityResult R = MD->getAvailability();
15118     if (R != AR_Available)
15119       return R;
15120     D = MD->getClassInterface();
15121   }
15122   // If we are within an Objective-c @implementation, it
15123   // gets the same availability context as the @interface.
15124   else if (const ObjCImplementationDecl *ID =
15125             dyn_cast<ObjCImplementationDecl>(D)) {
15126     D = ID->getClassInterface();
15127   }
15128   // Recover from user error.
15129   return D ? D->getAvailability() : AR_Available;
15130 }
15131