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/Parse/ParseDiagnostic.h"
37 #include "clang/Sema/CXXFieldCollector.h"
38 #include "clang/Sema/DeclSpec.h"
39 #include "clang/Sema/DelayedDiagnostic.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
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 }
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     return true;
115 
116   case tok::annot_typename:
117   case tok::kw_char16_t:
118   case tok::kw_char32_t:
119   case tok::kw_typeof:
120   case tok::annot_decltype:
121   case tok::kw_decltype:
122     return getLangOpts().CPlusPlus;
123 
124   default:
125     break;
126   }
127 
128   return false;
129 }
130 
131 namespace {
132 enum class UnqualifiedTypeNameLookupResult {
133   NotFound,
134   FoundNonType,
135   FoundType
136 };
137 } // namespace
138 
139 /// \brief Tries to perform unqualified lookup of the type decls in bases for
140 /// dependent class.
141 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
142 /// type decl, \a FoundType if only type decls are found.
143 static UnqualifiedTypeNameLookupResult
144 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
145                                 SourceLocation NameLoc,
146                                 const CXXRecordDecl *RD) {
147   if (!RD->hasDefinition())
148     return UnqualifiedTypeNameLookupResult::NotFound;
149   // Look for type decls in base classes.
150   UnqualifiedTypeNameLookupResult FoundTypeDecl =
151       UnqualifiedTypeNameLookupResult::NotFound;
152   for (const auto &Base : RD->bases()) {
153     const CXXRecordDecl *BaseRD = nullptr;
154     if (auto *BaseTT = Base.getType()->getAs<TagType>())
155       BaseRD = BaseTT->getAsCXXRecordDecl();
156     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
157       // Look for type decls in dependent base classes that have known primary
158       // templates.
159       if (!TST || !TST->isDependentType())
160         continue;
161       auto *TD = TST->getTemplateName().getAsTemplateDecl();
162       if (!TD)
163         continue;
164       auto *BasePrimaryTemplate =
165           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
166       if (!BasePrimaryTemplate)
167         continue;
168       BaseRD = BasePrimaryTemplate;
169     }
170     if (BaseRD) {
171       for (NamedDecl *ND : BaseRD->lookup(&II)) {
172         if (!isa<TypeDecl>(ND))
173           return UnqualifiedTypeNameLookupResult::FoundNonType;
174         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
175       }
176       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
177         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
178         case UnqualifiedTypeNameLookupResult::FoundNonType:
179           return UnqualifiedTypeNameLookupResult::FoundNonType;
180         case UnqualifiedTypeNameLookupResult::FoundType:
181           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
182           break;
183         case UnqualifiedTypeNameLookupResult::NotFound:
184           break;
185         }
186       }
187     }
188   }
189 
190   return FoundTypeDecl;
191 }
192 
193 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
194                                                       const IdentifierInfo &II,
195                                                       SourceLocation NameLoc) {
196   // Lookup in the parent class template context, if any.
197   const CXXRecordDecl *RD = nullptr;
198   UnqualifiedTypeNameLookupResult FoundTypeDecl =
199       UnqualifiedTypeNameLookupResult::NotFound;
200   for (DeclContext *DC = S.CurContext;
201        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
202        DC = DC->getParent()) {
203     // Look for type decls in dependent base classes that have known primary
204     // templates.
205     RD = dyn_cast<CXXRecordDecl>(DC);
206     if (RD && RD->getDescribedClassTemplate())
207       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
208   }
209   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
210     return ParsedType();
211 
212   // We found some types in dependent base classes.  Recover as if the user
213   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
214   // lookup during template instantiation.
215   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
216 
217   ASTContext &Context = S.Context;
218   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
219                                           cast<Type>(Context.getRecordType(RD)));
220   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
221 
222   CXXScopeSpec SS;
223   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
224 
225   TypeLocBuilder Builder;
226   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
227   DepTL.setNameLoc(NameLoc);
228   DepTL.setElaboratedKeywordLoc(SourceLocation());
229   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
230   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
231 }
232 
233 /// \brief If the identifier refers to a type name within this scope,
234 /// return the declaration of that type.
235 ///
236 /// This routine performs ordinary name lookup of the identifier II
237 /// within the given scope, with optional C++ scope specifier SS, to
238 /// determine whether the name refers to a type. If so, returns an
239 /// opaque pointer (actually a QualType) corresponding to that
240 /// type. Otherwise, returns NULL.
241 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
242                              Scope *S, CXXScopeSpec *SS,
243                              bool isClassName, bool HasTrailingDot,
244                              ParsedType ObjectTypePtr,
245                              bool IsCtorOrDtorName,
246                              bool WantNontrivialTypeSourceInfo,
247                              IdentifierInfo **CorrectedII) {
248   // Determine where we will perform name lookup.
249   DeclContext *LookupCtx = nullptr;
250   if (ObjectTypePtr) {
251     QualType ObjectType = ObjectTypePtr.get();
252     if (ObjectType->isRecordType())
253       LookupCtx = computeDeclContext(ObjectType);
254   } else if (SS && SS->isNotEmpty()) {
255     LookupCtx = computeDeclContext(*SS, false);
256 
257     if (!LookupCtx) {
258       if (isDependentScopeSpecifier(*SS)) {
259         // C++ [temp.res]p3:
260         //   A qualified-id that refers to a type and in which the
261         //   nested-name-specifier depends on a template-parameter (14.6.2)
262         //   shall be prefixed by the keyword typename to indicate that the
263         //   qualified-id denotes a type, forming an
264         //   elaborated-type-specifier (7.1.5.3).
265         //
266         // We therefore do not perform any name lookup if the result would
267         // refer to a member of an unknown specialization.
268         if (!isClassName && !IsCtorOrDtorName)
269           return ParsedType();
270 
271         // We know from the grammar that this name refers to a type,
272         // so build a dependent node to describe the type.
273         if (WantNontrivialTypeSourceInfo)
274           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
275 
276         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
277         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
278                                        II, NameLoc);
279         return ParsedType::make(T);
280       }
281 
282       return ParsedType();
283     }
284 
285     if (!LookupCtx->isDependentContext() &&
286         RequireCompleteDeclContext(*SS, LookupCtx))
287       return ParsedType();
288   }
289 
290   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
291   // lookup for class-names.
292   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
293                                       LookupOrdinaryName;
294   LookupResult Result(*this, &II, NameLoc, Kind);
295   if (LookupCtx) {
296     // Perform "qualified" name lookup into the declaration context we
297     // computed, which is either the type of the base of a member access
298     // expression or the declaration context associated with a prior
299     // nested-name-specifier.
300     LookupQualifiedName(Result, LookupCtx);
301 
302     if (ObjectTypePtr && Result.empty()) {
303       // C++ [basic.lookup.classref]p3:
304       //   If the unqualified-id is ~type-name, the type-name is looked up
305       //   in the context of the entire postfix-expression. If the type T of
306       //   the object expression is of a class type C, the type-name is also
307       //   looked up in the scope of class C. At least one of the lookups shall
308       //   find a name that refers to (possibly cv-qualified) T.
309       LookupName(Result, S);
310     }
311   } else {
312     // Perform unqualified name lookup.
313     LookupName(Result, S);
314 
315     // For unqualified lookup in a class template in MSVC mode, look into
316     // dependent base classes where the primary class template is known.
317     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
318       if (ParsedType TypeInBase =
319               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
320         return TypeInBase;
321     }
322   }
323 
324   NamedDecl *IIDecl = nullptr;
325   switch (Result.getResultKind()) {
326   case LookupResult::NotFound:
327   case LookupResult::NotFoundInCurrentInstantiation:
328     if (CorrectedII) {
329       TypoCorrection Correction = CorrectTypo(
330           Result.getLookupNameInfo(), Kind, S, SS,
331           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
332           CTK_ErrorRecovery);
333       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
334       TemplateTy Template;
335       bool MemberOfUnknownSpecialization;
336       UnqualifiedId TemplateName;
337       TemplateName.setIdentifier(NewII, NameLoc);
338       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
339       CXXScopeSpec NewSS, *NewSSPtr = SS;
340       if (SS && NNS) {
341         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
342         NewSSPtr = &NewSS;
343       }
344       if (Correction && (NNS || NewII != &II) &&
345           // Ignore a correction to a template type as the to-be-corrected
346           // identifier is not a template (typo correction for template names
347           // is handled elsewhere).
348           !(getLangOpts().CPlusPlus && NewSSPtr &&
349             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
350                            false, Template, MemberOfUnknownSpecialization))) {
351         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
352                                     isClassName, HasTrailingDot, ObjectTypePtr,
353                                     IsCtorOrDtorName,
354                                     WantNontrivialTypeSourceInfo);
355         if (Ty) {
356           diagnoseTypo(Correction,
357                        PDiag(diag::err_unknown_type_or_class_name_suggest)
358                          << Result.getLookupName() << isClassName);
359           if (SS && NNS)
360             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
361           *CorrectedII = NewII;
362           return Ty;
363         }
364       }
365     }
366     // If typo correction failed or was not performed, fall through
367   case LookupResult::FoundOverloaded:
368   case LookupResult::FoundUnresolvedValue:
369     Result.suppressDiagnostics();
370     return ParsedType();
371 
372   case LookupResult::Ambiguous:
373     // Recover from type-hiding ambiguities by hiding the type.  We'll
374     // do the lookup again when looking for an object, and we can
375     // diagnose the error then.  If we don't do this, then the error
376     // about hiding the type will be immediately followed by an error
377     // that only makes sense if the identifier was treated like a type.
378     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
379       Result.suppressDiagnostics();
380       return ParsedType();
381     }
382 
383     // Look to see if we have a type anywhere in the list of results.
384     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
385          Res != ResEnd; ++Res) {
386       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
387         if (!IIDecl ||
388             (*Res)->getLocation().getRawEncoding() <
389               IIDecl->getLocation().getRawEncoding())
390           IIDecl = *Res;
391       }
392     }
393 
394     if (!IIDecl) {
395       // None of the entities we found is a type, so there is no way
396       // to even assume that the result is a type. In this case, don't
397       // complain about the ambiguity. The parser will either try to
398       // perform this lookup again (e.g., as an object name), which
399       // will produce the ambiguity, or will complain that it expected
400       // a type name.
401       Result.suppressDiagnostics();
402       return ParsedType();
403     }
404 
405     // We found a type within the ambiguous lookup; diagnose the
406     // ambiguity and then return that type. This might be the right
407     // answer, or it might not be, but it suppresses any attempt to
408     // perform the name lookup again.
409     break;
410 
411   case LookupResult::Found:
412     IIDecl = Result.getFoundDecl();
413     break;
414   }
415 
416   assert(IIDecl && "Didn't find decl");
417 
418   QualType T;
419   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
420     DiagnoseUseOfDecl(IIDecl, NameLoc);
421 
422     T = Context.getTypeDeclType(TD);
423     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
424 
425     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
426     // constructor or destructor name (in such a case, the scope specifier
427     // will be attached to the enclosing Expr or Decl node).
428     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
429       if (WantNontrivialTypeSourceInfo) {
430         // Construct a type with type-source information.
431         TypeLocBuilder Builder;
432         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
433 
434         T = getElaboratedType(ETK_None, *SS, T);
435         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
436         ElabTL.setElaboratedKeywordLoc(SourceLocation());
437         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
438         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
439       } else {
440         T = getElaboratedType(ETK_None, *SS, T);
441       }
442     }
443   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
444     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
445     if (!HasTrailingDot)
446       T = Context.getObjCInterfaceType(IDecl);
447   }
448 
449   if (T.isNull()) {
450     // If it's not plausibly a type, suppress diagnostics.
451     Result.suppressDiagnostics();
452     return ParsedType();
453   }
454   return ParsedType::make(T);
455 }
456 
457 // Builds a fake NNS for the given decl context.
458 static NestedNameSpecifier *
459 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
460   for (;; DC = DC->getLookupParent()) {
461     DC = DC->getPrimaryContext();
462     auto *ND = dyn_cast<NamespaceDecl>(DC);
463     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
464       return NestedNameSpecifier::Create(Context, nullptr, ND);
465     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
466       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
467                                          RD->getTypeForDecl());
468     else if (isa<TranslationUnitDecl>(DC))
469       return NestedNameSpecifier::GlobalSpecifier(Context);
470   }
471   llvm_unreachable("something isn't in TU scope?");
472 }
473 
474 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
475                                                 SourceLocation NameLoc) {
476   // Accepting an undeclared identifier as a default argument for a template
477   // type parameter is a Microsoft extension.
478   Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
479 
480   // Build a fake DependentNameType that will perform lookup into CurContext at
481   // instantiation time.  The name specifier isn't dependent, so template
482   // instantiation won't transform it.  It will retry the lookup, however.
483   NestedNameSpecifier *NNS =
484       synthesizeCurrentNestedNameSpecifier(Context, CurContext);
485   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
486 
487   // Build type location information.  We synthesized the qualifier, so we have
488   // to build a fake NestedNameSpecifierLoc.
489   NestedNameSpecifierLocBuilder NNSLocBuilder;
490   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
491   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
492 
493   TypeLocBuilder Builder;
494   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
495   DepTL.setNameLoc(NameLoc);
496   DepTL.setElaboratedKeywordLoc(SourceLocation());
497   DepTL.setQualifierLoc(QualifierLoc);
498   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
499 }
500 
501 /// isTagName() - This method is called *for error recovery purposes only*
502 /// to determine if the specified name is a valid tag name ("struct foo").  If
503 /// so, this returns the TST for the tag corresponding to it (TST_enum,
504 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
505 /// cases in C where the user forgot to specify the tag.
506 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
507   // Do a tag name lookup in this scope.
508   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
509   LookupName(R, S, false);
510   R.suppressDiagnostics();
511   if (R.getResultKind() == LookupResult::Found)
512     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
513       switch (TD->getTagKind()) {
514       case TTK_Struct: return DeclSpec::TST_struct;
515       case TTK_Interface: return DeclSpec::TST_interface;
516       case TTK_Union:  return DeclSpec::TST_union;
517       case TTK_Class:  return DeclSpec::TST_class;
518       case TTK_Enum:   return DeclSpec::TST_enum;
519       }
520     }
521 
522   return DeclSpec::TST_unspecified;
523 }
524 
525 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
526 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
527 /// then downgrade the missing typename error to a warning.
528 /// This is needed for MSVC compatibility; Example:
529 /// @code
530 /// template<class T> class A {
531 /// public:
532 ///   typedef int TYPE;
533 /// };
534 /// template<class T> class B : public A<T> {
535 /// public:
536 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
537 /// };
538 /// @endcode
539 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
540   if (CurContext->isRecord()) {
541     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
542       return true;
543 
544     const Type *Ty = SS->getScopeRep()->getAsType();
545 
546     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
547     for (const auto &Base : RD->bases())
548       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
549         return true;
550     return S->isFunctionPrototypeScope();
551   }
552   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
553 }
554 
555 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
556                                    SourceLocation IILoc,
557                                    Scope *S,
558                                    CXXScopeSpec *SS,
559                                    ParsedType &SuggestedType,
560                                    bool AllowClassTemplates) {
561   // We don't have anything to suggest (yet).
562   SuggestedType = ParsedType();
563 
564   // There may have been a typo in the name of the type. Look up typo
565   // results, in case we have something that we can suggest.
566   if (TypoCorrection Corrected =
567           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
568                       llvm::make_unique<TypeNameValidatorCCC>(
569                           false, false, AllowClassTemplates),
570                       CTK_ErrorRecovery)) {
571     if (Corrected.isKeyword()) {
572       // We corrected to a keyword.
573       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
574       II = Corrected.getCorrectionAsIdentifierInfo();
575     } else {
576       // We found a similarly-named type or interface; suggest that.
577       if (!SS || !SS->isSet()) {
578         diagnoseTypo(Corrected,
579                      PDiag(diag::err_unknown_typename_suggest) << II);
580       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
581         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
582         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
583                                 II->getName().equals(CorrectedStr);
584         diagnoseTypo(Corrected,
585                      PDiag(diag::err_unknown_nested_typename_suggest)
586                        << II << DC << DroppedSpecifier << SS->getRange());
587       } else {
588         llvm_unreachable("could not have corrected a typo here");
589       }
590 
591       CXXScopeSpec tmpSS;
592       if (Corrected.getCorrectionSpecifier())
593         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
594                           SourceRange(IILoc));
595       SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
596                                   IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
597                                   false, ParsedType(),
598                                   /*IsCtorOrDtorName=*/false,
599                                   /*NonTrivialTypeSourceInfo=*/true);
600     }
601     return;
602   }
603 
604   if (getLangOpts().CPlusPlus) {
605     // See if II is a class template that the user forgot to pass arguments to.
606     UnqualifiedId Name;
607     Name.setIdentifier(II, IILoc);
608     CXXScopeSpec EmptySS;
609     TemplateTy TemplateResult;
610     bool MemberOfUnknownSpecialization;
611     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
612                        Name, ParsedType(), true, TemplateResult,
613                        MemberOfUnknownSpecialization) == TNK_Type_template) {
614       TemplateName TplName = TemplateResult.get();
615       Diag(IILoc, diag::err_template_missing_args) << TplName;
616       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
617         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
618           << TplDecl->getTemplateParameters()->getSourceRange();
619       }
620       return;
621     }
622   }
623 
624   // FIXME: Should we move the logic that tries to recover from a missing tag
625   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
626 
627   if (!SS || (!SS->isSet() && !SS->isInvalid()))
628     Diag(IILoc, diag::err_unknown_typename) << II;
629   else if (DeclContext *DC = computeDeclContext(*SS, false))
630     Diag(IILoc, diag::err_typename_nested_not_found)
631       << II << DC << SS->getRange();
632   else if (isDependentScopeSpecifier(*SS)) {
633     unsigned DiagID = diag::err_typename_missing;
634     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
635       DiagID = diag::ext_typename_missing;
636 
637     Diag(SS->getRange().getBegin(), DiagID)
638       << SS->getScopeRep() << II->getName()
639       << SourceRange(SS->getRange().getBegin(), IILoc)
640       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
641     SuggestedType = ActOnTypenameType(S, SourceLocation(),
642                                       *SS, *II, IILoc).get();
643   } else {
644     assert(SS && SS->isInvalid() &&
645            "Invalid scope specifier has already been diagnosed");
646   }
647 }
648 
649 /// \brief Determine whether the given result set contains either a type name
650 /// or
651 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
652   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
653                        NextToken.is(tok::less);
654 
655   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
656     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
657       return true;
658 
659     if (CheckTemplate && isa<TemplateDecl>(*I))
660       return true;
661   }
662 
663   return false;
664 }
665 
666 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
667                                     Scope *S, CXXScopeSpec &SS,
668                                     IdentifierInfo *&Name,
669                                     SourceLocation NameLoc) {
670   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
671   SemaRef.LookupParsedName(R, S, &SS);
672   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
673     StringRef FixItTagName;
674     switch (Tag->getTagKind()) {
675       case TTK_Class:
676         FixItTagName = "class ";
677         break;
678 
679       case TTK_Enum:
680         FixItTagName = "enum ";
681         break;
682 
683       case TTK_Struct:
684         FixItTagName = "struct ";
685         break;
686 
687       case TTK_Interface:
688         FixItTagName = "__interface ";
689         break;
690 
691       case TTK_Union:
692         FixItTagName = "union ";
693         break;
694     }
695 
696     StringRef TagName = FixItTagName.drop_back();
697     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
698       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
699       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
700 
701     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
702          I != IEnd; ++I)
703       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
704         << Name << TagName;
705 
706     // Replace lookup results with just the tag decl.
707     Result.clear(Sema::LookupTagName);
708     SemaRef.LookupParsedName(Result, S, &SS);
709     return true;
710   }
711 
712   return false;
713 }
714 
715 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
716 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
717                                   QualType T, SourceLocation NameLoc) {
718   ASTContext &Context = S.Context;
719 
720   TypeLocBuilder Builder;
721   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
722 
723   T = S.getElaboratedType(ETK_None, SS, T);
724   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
725   ElabTL.setElaboratedKeywordLoc(SourceLocation());
726   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
727   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
728 }
729 
730 Sema::NameClassification
731 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
732                    SourceLocation NameLoc, const Token &NextToken,
733                    bool IsAddressOfOperand,
734                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
735   DeclarationNameInfo NameInfo(Name, NameLoc);
736   ObjCMethodDecl *CurMethod = getCurMethodDecl();
737 
738   if (NextToken.is(tok::coloncolon)) {
739     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
740                                 QualType(), false, SS, nullptr, false);
741   }
742 
743   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
744   LookupParsedName(Result, S, &SS, !CurMethod);
745 
746   // For unqualified lookup in a class template in MSVC mode, look into
747   // dependent base classes where the primary class template is known.
748   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
749     if (ParsedType TypeInBase =
750             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
751       return TypeInBase;
752   }
753 
754   // Perform lookup for Objective-C instance variables (including automatically
755   // synthesized instance variables), if we're in an Objective-C method.
756   // FIXME: This lookup really, really needs to be folded in to the normal
757   // unqualified lookup mechanism.
758   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
759     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
760     if (E.get() || E.isInvalid())
761       return E;
762   }
763 
764   bool SecondTry = false;
765   bool IsFilteredTemplateName = false;
766 
767 Corrected:
768   switch (Result.getResultKind()) {
769   case LookupResult::NotFound:
770     // If an unqualified-id is followed by a '(', then we have a function
771     // call.
772     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
773       // In C++, this is an ADL-only call.
774       // FIXME: Reference?
775       if (getLangOpts().CPlusPlus)
776         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
777 
778       // C90 6.3.2.2:
779       //   If the expression that precedes the parenthesized argument list in a
780       //   function call consists solely of an identifier, and if no
781       //   declaration is visible for this identifier, the identifier is
782       //   implicitly declared exactly as if, in the innermost block containing
783       //   the function call, the declaration
784       //
785       //     extern int identifier ();
786       //
787       //   appeared.
788       //
789       // We also allow this in C99 as an extension.
790       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
791         Result.addDecl(D);
792         Result.resolveKind();
793         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
794       }
795     }
796 
797     // In C, we first see whether there is a tag type by the same name, in
798     // which case it's likely that the user just forget to write "enum",
799     // "struct", or "union".
800     if (!getLangOpts().CPlusPlus && !SecondTry &&
801         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
802       break;
803     }
804 
805     // Perform typo correction to determine if there is another name that is
806     // close to this name.
807     if (!SecondTry && CCC) {
808       SecondTry = true;
809       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
810                                                  Result.getLookupKind(), S,
811                                                  &SS, std::move(CCC),
812                                                  CTK_ErrorRecovery)) {
813         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
814         unsigned QualifiedDiag = diag::err_no_member_suggest;
815 
816         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
817         NamedDecl *UnderlyingFirstDecl
818           = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
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.is(tok::amp) || NextToken.is(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);
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 /// EnterDeclaratorContext - Used when we must lookup names in the context
1085 /// of a declarator's nested name specifier.
1086 ///
1087 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1088   // C++0x [basic.lookup.unqual]p13:
1089   //   A name used in the definition of a static data member of class
1090   //   X (after the qualified-id of the static member) is looked up as
1091   //   if the name was used in a member function of X.
1092   // C++0x [basic.lookup.unqual]p14:
1093   //   If a variable member of a namespace is defined outside of the
1094   //   scope of its namespace then any name used in the definition of
1095   //   the variable member (after the declarator-id) is looked up as
1096   //   if the definition of the variable member occurred in its
1097   //   namespace.
1098   // Both of these imply that we should push a scope whose context
1099   // is the semantic context of the declaration.  We can't use
1100   // PushDeclContext here because that context is not necessarily
1101   // lexically contained in the current context.  Fortunately,
1102   // the containing scope should have the appropriate information.
1103 
1104   assert(!S->getEntity() && "scope already has entity");
1105 
1106 #ifndef NDEBUG
1107   Scope *Ancestor = S->getParent();
1108   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1109   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1110 #endif
1111 
1112   CurContext = DC;
1113   S->setEntity(DC);
1114 }
1115 
1116 void Sema::ExitDeclaratorContext(Scope *S) {
1117   assert(S->getEntity() == CurContext && "Context imbalance!");
1118 
1119   // Switch back to the lexical context.  The safety of this is
1120   // enforced by an assert in EnterDeclaratorContext.
1121   Scope *Ancestor = S->getParent();
1122   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1123   CurContext = Ancestor->getEntity();
1124 
1125   // We don't need to do anything with the scope, which is going to
1126   // disappear.
1127 }
1128 
1129 
1130 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1131   // We assume that the caller has already called
1132   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1133   FunctionDecl *FD = D->getAsFunction();
1134   if (!FD)
1135     return;
1136 
1137   // Same implementation as PushDeclContext, but enters the context
1138   // from the lexical parent, rather than the top-level class.
1139   assert(CurContext == FD->getLexicalParent() &&
1140     "The next DeclContext should be lexically contained in the current one.");
1141   CurContext = FD;
1142   S->setEntity(CurContext);
1143 
1144   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1145     ParmVarDecl *Param = FD->getParamDecl(P);
1146     // If the parameter has an identifier, then add it to the scope
1147     if (Param->getIdentifier()) {
1148       S->AddDecl(Param);
1149       IdResolver.AddDecl(Param);
1150     }
1151   }
1152 }
1153 
1154 
1155 void Sema::ActOnExitFunctionContext() {
1156   // Same implementation as PopDeclContext, but returns to the lexical parent,
1157   // rather than the top-level class.
1158   assert(CurContext && "DeclContext imbalance!");
1159   CurContext = CurContext->getLexicalParent();
1160   assert(CurContext && "Popped translation unit!");
1161 }
1162 
1163 
1164 /// \brief Determine whether we allow overloading of the function
1165 /// PrevDecl with another declaration.
1166 ///
1167 /// This routine determines whether overloading is possible, not
1168 /// whether some new function is actually an overload. It will return
1169 /// true in C++ (where we can always provide overloads) or, as an
1170 /// extension, in C when the previous function is already an
1171 /// overloaded function declaration or has the "overloadable"
1172 /// attribute.
1173 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1174                                        ASTContext &Context) {
1175   if (Context.getLangOpts().CPlusPlus)
1176     return true;
1177 
1178   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1179     return true;
1180 
1181   return (Previous.getResultKind() == LookupResult::Found
1182           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1183 }
1184 
1185 /// Add this decl to the scope shadowed decl chains.
1186 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1187   // Move up the scope chain until we find the nearest enclosing
1188   // non-transparent context. The declaration will be introduced into this
1189   // scope.
1190   while (S->getEntity() && S->getEntity()->isTransparentContext())
1191     S = S->getParent();
1192 
1193   // Add scoped declarations into their context, so that they can be
1194   // found later. Declarations without a context won't be inserted
1195   // into any context.
1196   if (AddToContext)
1197     CurContext->addDecl(D);
1198 
1199   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1200   // are function-local declarations.
1201   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1202       !D->getDeclContext()->getRedeclContext()->Equals(
1203         D->getLexicalDeclContext()->getRedeclContext()) &&
1204       !D->getLexicalDeclContext()->isFunctionOrMethod())
1205     return;
1206 
1207   // Template instantiations should also not be pushed into scope.
1208   if (isa<FunctionDecl>(D) &&
1209       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1210     return;
1211 
1212   // If this replaces anything in the current scope,
1213   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1214                                IEnd = IdResolver.end();
1215   for (; I != IEnd; ++I) {
1216     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1217       S->RemoveDecl(*I);
1218       IdResolver.RemoveDecl(*I);
1219 
1220       // Should only need to replace one decl.
1221       break;
1222     }
1223   }
1224 
1225   S->AddDecl(D);
1226 
1227   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1228     // Implicitly-generated labels may end up getting generated in an order that
1229     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1230     // the label at the appropriate place in the identifier chain.
1231     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1232       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1233       if (IDC == CurContext) {
1234         if (!S->isDeclScope(*I))
1235           continue;
1236       } else if (IDC->Encloses(CurContext))
1237         break;
1238     }
1239 
1240     IdResolver.InsertDeclAfter(I, D);
1241   } else {
1242     IdResolver.AddDecl(D);
1243   }
1244 }
1245 
1246 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1247   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1248     TUScope->AddDecl(D);
1249 }
1250 
1251 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1252                          bool AllowInlineNamespace) {
1253   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1254 }
1255 
1256 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1257   DeclContext *TargetDC = DC->getPrimaryContext();
1258   do {
1259     if (DeclContext *ScopeDC = S->getEntity())
1260       if (ScopeDC->getPrimaryContext() == TargetDC)
1261         return S;
1262   } while ((S = S->getParent()));
1263 
1264   return nullptr;
1265 }
1266 
1267 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1268                                             DeclContext*,
1269                                             ASTContext&);
1270 
1271 /// Filters out lookup results that don't fall within the given scope
1272 /// as determined by isDeclInScope.
1273 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1274                                 bool ConsiderLinkage,
1275                                 bool AllowInlineNamespace) {
1276   LookupResult::Filter F = R.makeFilter();
1277   while (F.hasNext()) {
1278     NamedDecl *D = F.next();
1279 
1280     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1281       continue;
1282 
1283     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1284       continue;
1285 
1286     F.erase();
1287   }
1288 
1289   F.done();
1290 }
1291 
1292 static bool isUsingDecl(NamedDecl *D) {
1293   return isa<UsingShadowDecl>(D) ||
1294          isa<UnresolvedUsingTypenameDecl>(D) ||
1295          isa<UnresolvedUsingValueDecl>(D);
1296 }
1297 
1298 /// Removes using shadow declarations from the lookup results.
1299 static void RemoveUsingDecls(LookupResult &R) {
1300   LookupResult::Filter F = R.makeFilter();
1301   while (F.hasNext())
1302     if (isUsingDecl(F.next()))
1303       F.erase();
1304 
1305   F.done();
1306 }
1307 
1308 /// \brief Check for this common pattern:
1309 /// @code
1310 /// class S {
1311 ///   S(const S&); // DO NOT IMPLEMENT
1312 ///   void operator=(const S&); // DO NOT IMPLEMENT
1313 /// };
1314 /// @endcode
1315 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1316   // FIXME: Should check for private access too but access is set after we get
1317   // the decl here.
1318   if (D->doesThisDeclarationHaveABody())
1319     return false;
1320 
1321   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1322     return CD->isCopyConstructor();
1323   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1324     return Method->isCopyAssignmentOperator();
1325   return false;
1326 }
1327 
1328 // We need this to handle
1329 //
1330 // typedef struct {
1331 //   void *foo() { return 0; }
1332 // } A;
1333 //
1334 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1335 // for example. If 'A', foo will have external linkage. If we have '*A',
1336 // foo will have no linkage. Since we can't know until we get to the end
1337 // of the typedef, this function finds out if D might have non-external linkage.
1338 // Callers should verify at the end of the TU if it D has external linkage or
1339 // not.
1340 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1341   const DeclContext *DC = D->getDeclContext();
1342   while (!DC->isTranslationUnit()) {
1343     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1344       if (!RD->hasNameForLinkage())
1345         return true;
1346     }
1347     DC = DC->getParent();
1348   }
1349 
1350   return !D->isExternallyVisible();
1351 }
1352 
1353 // FIXME: This needs to be refactored; some other isInMainFile users want
1354 // these semantics.
1355 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1356   if (S.TUKind != TU_Complete)
1357     return false;
1358   return S.SourceMgr.isInMainFile(Loc);
1359 }
1360 
1361 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1362   assert(D);
1363 
1364   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1365     return false;
1366 
1367   // Ignore all entities declared within templates, and out-of-line definitions
1368   // of members of class templates.
1369   if (D->getDeclContext()->isDependentContext() ||
1370       D->getLexicalDeclContext()->isDependentContext())
1371     return false;
1372 
1373   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1374     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1375       return false;
1376 
1377     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1378       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1379         return false;
1380     } else {
1381       // 'static inline' functions are defined in headers; don't warn.
1382       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1383         return false;
1384     }
1385 
1386     if (FD->doesThisDeclarationHaveABody() &&
1387         Context.DeclMustBeEmitted(FD))
1388       return false;
1389   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1390     // Constants and utility variables are defined in headers with internal
1391     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1392     // like "inline".)
1393     if (!isMainFileLoc(*this, VD->getLocation()))
1394       return false;
1395 
1396     if (Context.DeclMustBeEmitted(VD))
1397       return false;
1398 
1399     if (VD->isStaticDataMember() &&
1400         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1401       return false;
1402   } else {
1403     return false;
1404   }
1405 
1406   // Only warn for unused decls internal to the translation unit.
1407   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1408   // for inline functions defined in the main source file, for instance.
1409   return mightHaveNonExternalLinkage(D);
1410 }
1411 
1412 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1413   if (!D)
1414     return;
1415 
1416   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1417     const FunctionDecl *First = FD->getFirstDecl();
1418     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1419       return; // First should already be in the vector.
1420   }
1421 
1422   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1423     const VarDecl *First = VD->getFirstDecl();
1424     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1425       return; // First should already be in the vector.
1426   }
1427 
1428   if (ShouldWarnIfUnusedFileScopedDecl(D))
1429     UnusedFileScopedDecls.push_back(D);
1430 }
1431 
1432 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1433   if (D->isInvalidDecl())
1434     return false;
1435 
1436   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1437       D->hasAttr<ObjCPreciseLifetimeAttr>())
1438     return false;
1439 
1440   if (isa<LabelDecl>(D))
1441     return true;
1442 
1443   // Except for labels, we only care about unused decls that are local to
1444   // functions.
1445   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1446   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1447     // For dependent types, the diagnostic is deferred.
1448     WithinFunction =
1449         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1450   if (!WithinFunction)
1451     return false;
1452 
1453   if (isa<TypedefNameDecl>(D))
1454     return true;
1455 
1456   // White-list anything that isn't a local variable.
1457   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1458     return false;
1459 
1460   // Types of valid local variables should be complete, so this should succeed.
1461   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1462 
1463     // White-list anything with an __attribute__((unused)) type.
1464     QualType Ty = VD->getType();
1465 
1466     // Only look at the outermost level of typedef.
1467     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1468       if (TT->getDecl()->hasAttr<UnusedAttr>())
1469         return false;
1470     }
1471 
1472     // If we failed to complete the type for some reason, or if the type is
1473     // dependent, don't diagnose the variable.
1474     if (Ty->isIncompleteType() || Ty->isDependentType())
1475       return false;
1476 
1477     if (const TagType *TT = Ty->getAs<TagType>()) {
1478       const TagDecl *Tag = TT->getDecl();
1479       if (Tag->hasAttr<UnusedAttr>())
1480         return false;
1481 
1482       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1483         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1484           return false;
1485 
1486         if (const Expr *Init = VD->getInit()) {
1487           if (const ExprWithCleanups *Cleanups =
1488                   dyn_cast<ExprWithCleanups>(Init))
1489             Init = Cleanups->getSubExpr();
1490           const CXXConstructExpr *Construct =
1491             dyn_cast<CXXConstructExpr>(Init);
1492           if (Construct && !Construct->isElidable()) {
1493             CXXConstructorDecl *CD = Construct->getConstructor();
1494             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1495               return false;
1496           }
1497         }
1498       }
1499     }
1500 
1501     // TODO: __attribute__((unused)) templates?
1502   }
1503 
1504   return true;
1505 }
1506 
1507 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1508                                      FixItHint &Hint) {
1509   if (isa<LabelDecl>(D)) {
1510     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1511                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1512     if (AfterColon.isInvalid())
1513       return;
1514     Hint = FixItHint::CreateRemoval(CharSourceRange::
1515                                     getCharRange(D->getLocStart(), AfterColon));
1516   }
1517   return;
1518 }
1519 
1520 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1521   if (D->getTypeForDecl()->isDependentType())
1522     return;
1523 
1524   for (auto *TmpD : D->decls()) {
1525     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1526       DiagnoseUnusedDecl(T);
1527     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1528       DiagnoseUnusedNestedTypedefs(R);
1529   }
1530 }
1531 
1532 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1533 /// unless they are marked attr(unused).
1534 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1535   if (!ShouldDiagnoseUnusedDecl(D))
1536     return;
1537 
1538   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1539     // typedefs can be referenced later on, so the diagnostics are emitted
1540     // at end-of-translation-unit.
1541     UnusedLocalTypedefNameCandidates.insert(TD);
1542     return;
1543   }
1544 
1545   FixItHint Hint;
1546   GenerateFixForUnusedDecl(D, Context, Hint);
1547 
1548   unsigned DiagID;
1549   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1550     DiagID = diag::warn_unused_exception_param;
1551   else if (isa<LabelDecl>(D))
1552     DiagID = diag::warn_unused_label;
1553   else
1554     DiagID = diag::warn_unused_variable;
1555 
1556   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1557 }
1558 
1559 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1560   // Verify that we have no forward references left.  If so, there was a goto
1561   // or address of a label taken, but no definition of it.  Label fwd
1562   // definitions are indicated with a null substmt which is also not a resolved
1563   // MS inline assembly label name.
1564   bool Diagnose = false;
1565   if (L->isMSAsmLabel())
1566     Diagnose = !L->isResolvedMSAsmLabel();
1567   else
1568     Diagnose = L->getStmt() == nullptr;
1569   if (Diagnose)
1570     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1571 }
1572 
1573 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1574   S->mergeNRVOIntoParent();
1575 
1576   if (S->decl_empty()) return;
1577   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1578          "Scope shouldn't contain decls!");
1579 
1580   for (auto *TmpD : S->decls()) {
1581     assert(TmpD && "This decl didn't get pushed??");
1582 
1583     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1584     NamedDecl *D = cast<NamedDecl>(TmpD);
1585 
1586     if (!D->getDeclName()) continue;
1587 
1588     // Diagnose unused variables in this scope.
1589     if (!S->hasUnrecoverableErrorOccurred()) {
1590       DiagnoseUnusedDecl(D);
1591       if (const auto *RD = dyn_cast<RecordDecl>(D))
1592         DiagnoseUnusedNestedTypedefs(RD);
1593     }
1594 
1595     // If this was a forward reference to a label, verify it was defined.
1596     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1597       CheckPoppedLabel(LD, *this);
1598 
1599     // Remove this name from our lexical scope.
1600     IdResolver.RemoveDecl(D);
1601   }
1602 }
1603 
1604 /// \brief Look for an Objective-C class in the translation unit.
1605 ///
1606 /// \param Id The name of the Objective-C class we're looking for. If
1607 /// typo-correction fixes this name, the Id will be updated
1608 /// to the fixed name.
1609 ///
1610 /// \param IdLoc The location of the name in the translation unit.
1611 ///
1612 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1613 /// if there is no class with the given name.
1614 ///
1615 /// \returns The declaration of the named Objective-C class, or NULL if the
1616 /// class could not be found.
1617 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1618                                               SourceLocation IdLoc,
1619                                               bool DoTypoCorrection) {
1620   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1621   // creation from this context.
1622   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1623 
1624   if (!IDecl && DoTypoCorrection) {
1625     // Perform typo correction at the given location, but only if we
1626     // find an Objective-C class name.
1627     if (TypoCorrection C = CorrectTypo(
1628             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1629             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1630             CTK_ErrorRecovery)) {
1631       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1632       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1633       Id = IDecl->getIdentifier();
1634     }
1635   }
1636   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1637   // This routine must always return a class definition, if any.
1638   if (Def && Def->getDefinition())
1639       Def = Def->getDefinition();
1640   return Def;
1641 }
1642 
1643 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1644 /// from S, where a non-field would be declared. This routine copes
1645 /// with the difference between C and C++ scoping rules in structs and
1646 /// unions. For example, the following code is well-formed in C but
1647 /// ill-formed in C++:
1648 /// @code
1649 /// struct S6 {
1650 ///   enum { BAR } e;
1651 /// };
1652 ///
1653 /// void test_S6() {
1654 ///   struct S6 a;
1655 ///   a.e = BAR;
1656 /// }
1657 /// @endcode
1658 /// For the declaration of BAR, this routine will return a different
1659 /// scope. The scope S will be the scope of the unnamed enumeration
1660 /// within S6. In C++, this routine will return the scope associated
1661 /// with S6, because the enumeration's scope is a transparent
1662 /// context but structures can contain non-field names. In C, this
1663 /// routine will return the translation unit scope, since the
1664 /// enumeration's scope is a transparent context and structures cannot
1665 /// contain non-field names.
1666 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1667   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1668          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1669          (S->isClassScope() && !getLangOpts().CPlusPlus))
1670     S = S->getParent();
1671   return S;
1672 }
1673 
1674 /// \brief Looks up the declaration of "struct objc_super" and
1675 /// saves it for later use in building builtin declaration of
1676 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1677 /// pre-existing declaration exists no action takes place.
1678 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1679                                         IdentifierInfo *II) {
1680   if (!II->isStr("objc_msgSendSuper"))
1681     return;
1682   ASTContext &Context = ThisSema.Context;
1683 
1684   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1685                       SourceLocation(), Sema::LookupTagName);
1686   ThisSema.LookupName(Result, S);
1687   if (Result.getResultKind() == LookupResult::Found)
1688     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1689       Context.setObjCSuperType(Context.getTagDeclType(TD));
1690 }
1691 
1692 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1693   switch (Error) {
1694   case ASTContext::GE_None:
1695     return "";
1696   case ASTContext::GE_Missing_stdio:
1697     return "stdio.h";
1698   case ASTContext::GE_Missing_setjmp:
1699     return "setjmp.h";
1700   case ASTContext::GE_Missing_ucontext:
1701     return "ucontext.h";
1702   }
1703   llvm_unreachable("unhandled error kind");
1704 }
1705 
1706 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1707 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1708 /// if we're creating this built-in in anticipation of redeclaring the
1709 /// built-in.
1710 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1711                                      Scope *S, bool ForRedeclaration,
1712                                      SourceLocation Loc) {
1713   LookupPredefedObjCSuperType(*this, S, II);
1714 
1715   ASTContext::GetBuiltinTypeError Error;
1716   QualType R = Context.GetBuiltinType(ID, Error);
1717   if (Error) {
1718     if (ForRedeclaration)
1719       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1720           << getHeaderName(Error)
1721           << Context.BuiltinInfo.GetName(ID);
1722     return nullptr;
1723   }
1724 
1725   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1726     Diag(Loc, diag::ext_implicit_lib_function_decl)
1727       << Context.BuiltinInfo.GetName(ID)
1728       << R;
1729     if (Context.BuiltinInfo.getHeaderName(ID) &&
1730         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1731       Diag(Loc, diag::note_include_header_or_declare)
1732           << Context.BuiltinInfo.getHeaderName(ID)
1733           << Context.BuiltinInfo.GetName(ID);
1734   }
1735 
1736   DeclContext *Parent = Context.getTranslationUnitDecl();
1737   if (getLangOpts().CPlusPlus) {
1738     LinkageSpecDecl *CLinkageDecl =
1739         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1740                                 LinkageSpecDecl::lang_c, false);
1741     CLinkageDecl->setImplicit();
1742     Parent->addDecl(CLinkageDecl);
1743     Parent = CLinkageDecl;
1744   }
1745 
1746   FunctionDecl *New = FunctionDecl::Create(Context,
1747                                            Parent,
1748                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1749                                            SC_Extern,
1750                                            false,
1751                                            /*hasPrototype=*/true);
1752   New->setImplicit();
1753 
1754   // Create Decl objects for each parameter, adding them to the
1755   // FunctionDecl.
1756   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1757     SmallVector<ParmVarDecl*, 16> Params;
1758     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1759       ParmVarDecl *parm =
1760           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1761                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1762                               SC_None, nullptr);
1763       parm->setScopeInfo(0, i);
1764       Params.push_back(parm);
1765     }
1766     New->setParams(Params);
1767   }
1768 
1769   AddKnownFunctionAttributes(New);
1770   RegisterLocallyScopedExternCDecl(New, S);
1771 
1772   // TUScope is the translation-unit scope to insert this function into.
1773   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1774   // relate Scopes to DeclContexts, and probably eliminate CurContext
1775   // entirely, but we're not there yet.
1776   DeclContext *SavedContext = CurContext;
1777   CurContext = Parent;
1778   PushOnScopeChains(New, TUScope);
1779   CurContext = SavedContext;
1780   return New;
1781 }
1782 
1783 /// \brief Filter out any previous declarations that the given declaration
1784 /// should not consider because they are not permitted to conflict, e.g.,
1785 /// because they come from hidden sub-modules and do not refer to the same
1786 /// entity.
1787 static void filterNonConflictingPreviousDecls(ASTContext &context,
1788                                               NamedDecl *decl,
1789                                               LookupResult &previous){
1790   // This is only interesting when modules are enabled.
1791   if (!context.getLangOpts().Modules)
1792     return;
1793 
1794   // Empty sets are uninteresting.
1795   if (previous.empty())
1796     return;
1797 
1798   LookupResult::Filter filter = previous.makeFilter();
1799   while (filter.hasNext()) {
1800     NamedDecl *old = filter.next();
1801 
1802     // Non-hidden declarations are never ignored.
1803     if (!old->isHidden())
1804       continue;
1805 
1806     if (!old->isExternallyVisible())
1807       filter.erase();
1808   }
1809 
1810   filter.done();
1811 }
1812 
1813 /// Typedef declarations don't have linkage, but they still denote the same
1814 /// entity if their types are the same.
1815 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1816 /// isSameEntity.
1817 static void filterNonConflictingPreviousTypedefDecls(ASTContext &Context,
1818                                                      TypedefNameDecl *Decl,
1819                                                      LookupResult &Previous) {
1820   // This is only interesting when modules are enabled.
1821   if (!Context.getLangOpts().Modules)
1822     return;
1823 
1824   // Empty sets are uninteresting.
1825   if (Previous.empty())
1826     return;
1827 
1828   LookupResult::Filter Filter = Previous.makeFilter();
1829   while (Filter.hasNext()) {
1830     NamedDecl *Old = Filter.next();
1831 
1832     // Non-hidden declarations are never ignored.
1833     if (!Old->isHidden())
1834       continue;
1835 
1836     // Declarations of the same entity are not ignored, even if they have
1837     // different linkages.
1838     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old))
1839       if (Context.hasSameType(OldTD->getUnderlyingType(),
1840                               Decl->getUnderlyingType()))
1841         continue;
1842 
1843     if (!Old->isExternallyVisible())
1844       Filter.erase();
1845   }
1846 
1847   Filter.done();
1848 }
1849 
1850 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1851   QualType OldType;
1852   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1853     OldType = OldTypedef->getUnderlyingType();
1854   else
1855     OldType = Context.getTypeDeclType(Old);
1856   QualType NewType = New->getUnderlyingType();
1857 
1858   if (NewType->isVariablyModifiedType()) {
1859     // Must not redefine a typedef with a variably-modified type.
1860     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1861     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1862       << Kind << NewType;
1863     if (Old->getLocation().isValid())
1864       Diag(Old->getLocation(), diag::note_previous_definition);
1865     New->setInvalidDecl();
1866     return true;
1867   }
1868 
1869   if (OldType != NewType &&
1870       !OldType->isDependentType() &&
1871       !NewType->isDependentType() &&
1872       !Context.hasSameType(OldType, NewType)) {
1873     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1874     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1875       << Kind << NewType << OldType;
1876     if (Old->getLocation().isValid())
1877       Diag(Old->getLocation(), diag::note_previous_definition);
1878     New->setInvalidDecl();
1879     return true;
1880   }
1881   return false;
1882 }
1883 
1884 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1885 /// same name and scope as a previous declaration 'Old'.  Figure out
1886 /// how to resolve this situation, merging decls or emitting
1887 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1888 ///
1889 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1890   // If the new decl is known invalid already, don't bother doing any
1891   // merging checks.
1892   if (New->isInvalidDecl()) return;
1893 
1894   // Allow multiple definitions for ObjC built-in typedefs.
1895   // FIXME: Verify the underlying types are equivalent!
1896   if (getLangOpts().ObjC1) {
1897     const IdentifierInfo *TypeID = New->getIdentifier();
1898     switch (TypeID->getLength()) {
1899     default: break;
1900     case 2:
1901       {
1902         if (!TypeID->isStr("id"))
1903           break;
1904         QualType T = New->getUnderlyingType();
1905         if (!T->isPointerType())
1906           break;
1907         if (!T->isVoidPointerType()) {
1908           QualType PT = T->getAs<PointerType>()->getPointeeType();
1909           if (!PT->isStructureType())
1910             break;
1911         }
1912         Context.setObjCIdRedefinitionType(T);
1913         // Install the built-in type for 'id', ignoring the current definition.
1914         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1915         return;
1916       }
1917     case 5:
1918       if (!TypeID->isStr("Class"))
1919         break;
1920       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1921       // Install the built-in type for 'Class', ignoring the current definition.
1922       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1923       return;
1924     case 3:
1925       if (!TypeID->isStr("SEL"))
1926         break;
1927       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1928       // Install the built-in type for 'SEL', ignoring the current definition.
1929       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1930       return;
1931     }
1932     // Fall through - the typedef name was not a builtin type.
1933   }
1934 
1935   // Verify the old decl was also a type.
1936   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1937   if (!Old) {
1938     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1939       << New->getDeclName();
1940 
1941     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1942     if (OldD->getLocation().isValid())
1943       Diag(OldD->getLocation(), diag::note_previous_definition);
1944 
1945     return New->setInvalidDecl();
1946   }
1947 
1948   // If the old declaration is invalid, just give up here.
1949   if (Old->isInvalidDecl())
1950     return New->setInvalidDecl();
1951 
1952   // If the typedef types are not identical, reject them in all languages and
1953   // with any extensions enabled.
1954   if (isIncompatibleTypedef(Old, New))
1955     return;
1956 
1957   // The types match.  Link up the redeclaration chain and merge attributes if
1958   // the old declaration was a typedef.
1959   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1960     New->setPreviousDecl(Typedef);
1961     mergeDeclAttributes(New, Old);
1962   }
1963 
1964   if (getLangOpts().MicrosoftExt)
1965     return;
1966 
1967   if (getLangOpts().CPlusPlus) {
1968     // C++ [dcl.typedef]p2:
1969     //   In a given non-class scope, a typedef specifier can be used to
1970     //   redefine the name of any type declared in that scope to refer
1971     //   to the type to which it already refers.
1972     if (!isa<CXXRecordDecl>(CurContext))
1973       return;
1974 
1975     // C++0x [dcl.typedef]p4:
1976     //   In a given class scope, a typedef specifier can be used to redefine
1977     //   any class-name declared in that scope that is not also a typedef-name
1978     //   to refer to the type to which it already refers.
1979     //
1980     // This wording came in via DR424, which was a correction to the
1981     // wording in DR56, which accidentally banned code like:
1982     //
1983     //   struct S {
1984     //     typedef struct A { } A;
1985     //   };
1986     //
1987     // in the C++03 standard. We implement the C++0x semantics, which
1988     // allow the above but disallow
1989     //
1990     //   struct S {
1991     //     typedef int I;
1992     //     typedef int I;
1993     //   };
1994     //
1995     // since that was the intent of DR56.
1996     if (!isa<TypedefNameDecl>(Old))
1997       return;
1998 
1999     Diag(New->getLocation(), diag::err_redefinition)
2000       << New->getDeclName();
2001     Diag(Old->getLocation(), diag::note_previous_definition);
2002     return New->setInvalidDecl();
2003   }
2004 
2005   // Modules always permit redefinition of typedefs, as does C11.
2006   if (getLangOpts().Modules || getLangOpts().C11)
2007     return;
2008 
2009   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2010   // is normally mapped to an error, but can be controlled with
2011   // -Wtypedef-redefinition.  If either the original or the redefinition is
2012   // in a system header, don't emit this for compatibility with GCC.
2013   if (getDiagnostics().getSuppressSystemWarnings() &&
2014       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2015        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2016     return;
2017 
2018   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2019     << New->getDeclName();
2020   Diag(Old->getLocation(), diag::note_previous_definition);
2021   return;
2022 }
2023 
2024 /// DeclhasAttr - returns true if decl Declaration already has the target
2025 /// attribute.
2026 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2027   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2028   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2029   for (const auto *i : D->attrs())
2030     if (i->getKind() == A->getKind()) {
2031       if (Ann) {
2032         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2033           return true;
2034         continue;
2035       }
2036       // FIXME: Don't hardcode this check
2037       if (OA && isa<OwnershipAttr>(i))
2038         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2039       return true;
2040     }
2041 
2042   return false;
2043 }
2044 
2045 static bool isAttributeTargetADefinition(Decl *D) {
2046   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2047     return VD->isThisDeclarationADefinition();
2048   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2049     return TD->isCompleteDefinition() || TD->isBeingDefined();
2050   return true;
2051 }
2052 
2053 /// Merge alignment attributes from \p Old to \p New, taking into account the
2054 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2055 ///
2056 /// \return \c true if any attributes were added to \p New.
2057 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2058   // Look for alignas attributes on Old, and pick out whichever attribute
2059   // specifies the strictest alignment requirement.
2060   AlignedAttr *OldAlignasAttr = nullptr;
2061   AlignedAttr *OldStrictestAlignAttr = nullptr;
2062   unsigned OldAlign = 0;
2063   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2064     // FIXME: We have no way of representing inherited dependent alignments
2065     // in a case like:
2066     //   template<int A, int B> struct alignas(A) X;
2067     //   template<int A, int B> struct alignas(B) X {};
2068     // For now, we just ignore any alignas attributes which are not on the
2069     // definition in such a case.
2070     if (I->isAlignmentDependent())
2071       return false;
2072 
2073     if (I->isAlignas())
2074       OldAlignasAttr = I;
2075 
2076     unsigned Align = I->getAlignment(S.Context);
2077     if (Align > OldAlign) {
2078       OldAlign = Align;
2079       OldStrictestAlignAttr = I;
2080     }
2081   }
2082 
2083   // Look for alignas attributes on New.
2084   AlignedAttr *NewAlignasAttr = nullptr;
2085   unsigned NewAlign = 0;
2086   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2087     if (I->isAlignmentDependent())
2088       return false;
2089 
2090     if (I->isAlignas())
2091       NewAlignasAttr = I;
2092 
2093     unsigned Align = I->getAlignment(S.Context);
2094     if (Align > NewAlign)
2095       NewAlign = Align;
2096   }
2097 
2098   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2099     // Both declarations have 'alignas' attributes. We require them to match.
2100     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2101     // fall short. (If two declarations both have alignas, they must both match
2102     // every definition, and so must match each other if there is a definition.)
2103 
2104     // If either declaration only contains 'alignas(0)' specifiers, then it
2105     // specifies the natural alignment for the type.
2106     if (OldAlign == 0 || NewAlign == 0) {
2107       QualType Ty;
2108       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2109         Ty = VD->getType();
2110       else
2111         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2112 
2113       if (OldAlign == 0)
2114         OldAlign = S.Context.getTypeAlign(Ty);
2115       if (NewAlign == 0)
2116         NewAlign = S.Context.getTypeAlign(Ty);
2117     }
2118 
2119     if (OldAlign != NewAlign) {
2120       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2121         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2122         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2123       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2124     }
2125   }
2126 
2127   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2128     // C++11 [dcl.align]p6:
2129     //   if any declaration of an entity has an alignment-specifier,
2130     //   every defining declaration of that entity shall specify an
2131     //   equivalent alignment.
2132     // C11 6.7.5/7:
2133     //   If the definition of an object does not have an alignment
2134     //   specifier, any other declaration of that object shall also
2135     //   have no alignment specifier.
2136     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2137       << OldAlignasAttr;
2138     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2139       << OldAlignasAttr;
2140   }
2141 
2142   bool AnyAdded = false;
2143 
2144   // Ensure we have an attribute representing the strictest alignment.
2145   if (OldAlign > NewAlign) {
2146     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2147     Clone->setInherited(true);
2148     New->addAttr(Clone);
2149     AnyAdded = true;
2150   }
2151 
2152   // Ensure we have an alignas attribute if the old declaration had one.
2153   if (OldAlignasAttr && !NewAlignasAttr &&
2154       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2155     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2156     Clone->setInherited(true);
2157     New->addAttr(Clone);
2158     AnyAdded = true;
2159   }
2160 
2161   return AnyAdded;
2162 }
2163 
2164 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2165                                const InheritableAttr *Attr, bool Override) {
2166   InheritableAttr *NewAttr = nullptr;
2167   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2168   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2169     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2170                                       AA->getIntroduced(), AA->getDeprecated(),
2171                                       AA->getObsoleted(), AA->getUnavailable(),
2172                                       AA->getMessage(), Override,
2173                                       AttrSpellingListIndex);
2174   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2175     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2176                                     AttrSpellingListIndex);
2177   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2178     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2179                                         AttrSpellingListIndex);
2180   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2181     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2182                                    AttrSpellingListIndex);
2183   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2184     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2185                                    AttrSpellingListIndex);
2186   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2187     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2188                                 FA->getFormatIdx(), FA->getFirstArg(),
2189                                 AttrSpellingListIndex);
2190   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2191     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2192                                  AttrSpellingListIndex);
2193   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2194     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2195                                        AttrSpellingListIndex,
2196                                        IA->getSemanticSpelling());
2197   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2198     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2199                                       &S.Context.Idents.get(AA->getSpelling()),
2200                                       AttrSpellingListIndex);
2201   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2202     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2203   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2204     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2205   else if (isa<AlignedAttr>(Attr))
2206     // AlignedAttrs are handled separately, because we need to handle all
2207     // such attributes on a declaration at the same time.
2208     NewAttr = nullptr;
2209   else if (isa<DeprecatedAttr>(Attr) && Override)
2210     NewAttr = nullptr;
2211   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2212     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2213 
2214   if (NewAttr) {
2215     NewAttr->setInherited(true);
2216     D->addAttr(NewAttr);
2217     return true;
2218   }
2219 
2220   return false;
2221 }
2222 
2223 static const Decl *getDefinition(const Decl *D) {
2224   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2225     return TD->getDefinition();
2226   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2227     const VarDecl *Def = VD->getDefinition();
2228     if (Def)
2229       return Def;
2230     return VD->getActingDefinition();
2231   }
2232   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2233     const FunctionDecl* Def;
2234     if (FD->isDefined(Def))
2235       return Def;
2236   }
2237   return nullptr;
2238 }
2239 
2240 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2241   for (const auto *Attribute : D->attrs())
2242     if (Attribute->getKind() == Kind)
2243       return true;
2244   return false;
2245 }
2246 
2247 /// checkNewAttributesAfterDef - If we already have a definition, check that
2248 /// there are no new attributes in this declaration.
2249 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2250   if (!New->hasAttrs())
2251     return;
2252 
2253   const Decl *Def = getDefinition(Old);
2254   if (!Def || Def == New)
2255     return;
2256 
2257   AttrVec &NewAttributes = New->getAttrs();
2258   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2259     const Attr *NewAttribute = NewAttributes[I];
2260 
2261     if (isa<AliasAttr>(NewAttribute)) {
2262       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2263         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2264       else {
2265         VarDecl *VD = cast<VarDecl>(New);
2266         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2267                                 VarDecl::TentativeDefinition
2268                             ? diag::err_alias_after_tentative
2269                             : diag::err_redefinition;
2270         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2271         S.Diag(Def->getLocation(), diag::note_previous_definition);
2272         VD->setInvalidDecl();
2273       }
2274       ++I;
2275       continue;
2276     }
2277 
2278     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2279       // Tentative definitions are only interesting for the alias check above.
2280       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2281         ++I;
2282         continue;
2283       }
2284     }
2285 
2286     if (hasAttribute(Def, NewAttribute->getKind())) {
2287       ++I;
2288       continue; // regular attr merging will take care of validating this.
2289     }
2290 
2291     if (isa<C11NoReturnAttr>(NewAttribute)) {
2292       // C's _Noreturn is allowed to be added to a function after it is defined.
2293       ++I;
2294       continue;
2295     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2296       if (AA->isAlignas()) {
2297         // C++11 [dcl.align]p6:
2298         //   if any declaration of an entity has an alignment-specifier,
2299         //   every defining declaration of that entity shall specify an
2300         //   equivalent alignment.
2301         // C11 6.7.5/7:
2302         //   If the definition of an object does not have an alignment
2303         //   specifier, any other declaration of that object shall also
2304         //   have no alignment specifier.
2305         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2306           << AA;
2307         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2308           << AA;
2309         NewAttributes.erase(NewAttributes.begin() + I);
2310         --E;
2311         continue;
2312       }
2313     }
2314 
2315     S.Diag(NewAttribute->getLocation(),
2316            diag::warn_attribute_precede_definition);
2317     S.Diag(Def->getLocation(), diag::note_previous_definition);
2318     NewAttributes.erase(NewAttributes.begin() + I);
2319     --E;
2320   }
2321 }
2322 
2323 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2324 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2325                                AvailabilityMergeKind AMK) {
2326   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2327     UsedAttr *NewAttr = OldAttr->clone(Context);
2328     NewAttr->setInherited(true);
2329     New->addAttr(NewAttr);
2330   }
2331 
2332   if (!Old->hasAttrs() && !New->hasAttrs())
2333     return;
2334 
2335   // attributes declared post-definition are currently ignored
2336   checkNewAttributesAfterDef(*this, New, Old);
2337 
2338   if (!Old->hasAttrs())
2339     return;
2340 
2341   bool foundAny = New->hasAttrs();
2342 
2343   // Ensure that any moving of objects within the allocated map is done before
2344   // we process them.
2345   if (!foundAny) New->setAttrs(AttrVec());
2346 
2347   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2348     bool Override = false;
2349     // Ignore deprecated/unavailable/availability attributes if requested.
2350     if (isa<DeprecatedAttr>(I) ||
2351         isa<UnavailableAttr>(I) ||
2352         isa<AvailabilityAttr>(I)) {
2353       switch (AMK) {
2354       case AMK_None:
2355         continue;
2356 
2357       case AMK_Redeclaration:
2358         break;
2359 
2360       case AMK_Override:
2361         Override = true;
2362         break;
2363       }
2364     }
2365 
2366     // Already handled.
2367     if (isa<UsedAttr>(I))
2368       continue;
2369 
2370     if (mergeDeclAttribute(*this, New, I, Override))
2371       foundAny = true;
2372   }
2373 
2374   if (mergeAlignedAttrs(*this, New, Old))
2375     foundAny = true;
2376 
2377   if (!foundAny) New->dropAttrs();
2378 }
2379 
2380 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2381 /// to the new one.
2382 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2383                                      const ParmVarDecl *oldDecl,
2384                                      Sema &S) {
2385   // C++11 [dcl.attr.depend]p2:
2386   //   The first declaration of a function shall specify the
2387   //   carries_dependency attribute for its declarator-id if any declaration
2388   //   of the function specifies the carries_dependency attribute.
2389   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2390   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2391     S.Diag(CDA->getLocation(),
2392            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2393     // Find the first declaration of the parameter.
2394     // FIXME: Should we build redeclaration chains for function parameters?
2395     const FunctionDecl *FirstFD =
2396       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2397     const ParmVarDecl *FirstVD =
2398       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2399     S.Diag(FirstVD->getLocation(),
2400            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2401   }
2402 
2403   if (!oldDecl->hasAttrs())
2404     return;
2405 
2406   bool foundAny = newDecl->hasAttrs();
2407 
2408   // Ensure that any moving of objects within the allocated map is
2409   // done before we process them.
2410   if (!foundAny) newDecl->setAttrs(AttrVec());
2411 
2412   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2413     if (!DeclHasAttr(newDecl, I)) {
2414       InheritableAttr *newAttr =
2415         cast<InheritableParamAttr>(I->clone(S.Context));
2416       newAttr->setInherited(true);
2417       newDecl->addAttr(newAttr);
2418       foundAny = true;
2419     }
2420   }
2421 
2422   if (!foundAny) newDecl->dropAttrs();
2423 }
2424 
2425 namespace {
2426 
2427 /// Used in MergeFunctionDecl to keep track of function parameters in
2428 /// C.
2429 struct GNUCompatibleParamWarning {
2430   ParmVarDecl *OldParm;
2431   ParmVarDecl *NewParm;
2432   QualType PromotedType;
2433 };
2434 
2435 }
2436 
2437 /// getSpecialMember - get the special member enum for a method.
2438 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2439   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2440     if (Ctor->isDefaultConstructor())
2441       return Sema::CXXDefaultConstructor;
2442 
2443     if (Ctor->isCopyConstructor())
2444       return Sema::CXXCopyConstructor;
2445 
2446     if (Ctor->isMoveConstructor())
2447       return Sema::CXXMoveConstructor;
2448   } else if (isa<CXXDestructorDecl>(MD)) {
2449     return Sema::CXXDestructor;
2450   } else if (MD->isCopyAssignmentOperator()) {
2451     return Sema::CXXCopyAssignment;
2452   } else if (MD->isMoveAssignmentOperator()) {
2453     return Sema::CXXMoveAssignment;
2454   }
2455 
2456   return Sema::CXXInvalid;
2457 }
2458 
2459 // Determine whether the previous declaration was a definition, implicit
2460 // declaration, or a declaration.
2461 template <typename T>
2462 static std::pair<diag::kind, SourceLocation>
2463 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2464   diag::kind PrevDiag;
2465   SourceLocation OldLocation = Old->getLocation();
2466   if (Old->isThisDeclarationADefinition())
2467     PrevDiag = diag::note_previous_definition;
2468   else if (Old->isImplicit()) {
2469     PrevDiag = diag::note_previous_implicit_declaration;
2470     if (OldLocation.isInvalid())
2471       OldLocation = New->getLocation();
2472   } else
2473     PrevDiag = diag::note_previous_declaration;
2474   return std::make_pair(PrevDiag, OldLocation);
2475 }
2476 
2477 /// canRedefineFunction - checks if a function can be redefined. Currently,
2478 /// only extern inline functions can be redefined, and even then only in
2479 /// GNU89 mode.
2480 static bool canRedefineFunction(const FunctionDecl *FD,
2481                                 const LangOptions& LangOpts) {
2482   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2483           !LangOpts.CPlusPlus &&
2484           FD->isInlineSpecified() &&
2485           FD->getStorageClass() == SC_Extern);
2486 }
2487 
2488 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2489   const AttributedType *AT = T->getAs<AttributedType>();
2490   while (AT && !AT->isCallingConv())
2491     AT = AT->getModifiedType()->getAs<AttributedType>();
2492   return AT;
2493 }
2494 
2495 template <typename T>
2496 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2497   const DeclContext *DC = Old->getDeclContext();
2498   if (DC->isRecord())
2499     return false;
2500 
2501   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2502   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2503     return true;
2504   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2505     return true;
2506   return false;
2507 }
2508 
2509 /// MergeFunctionDecl - We just parsed a function 'New' from
2510 /// declarator D which has the same name and scope as a previous
2511 /// declaration 'Old'.  Figure out how to resolve this situation,
2512 /// merging decls or emitting diagnostics as appropriate.
2513 ///
2514 /// In C++, New and Old must be declarations that are not
2515 /// overloaded. Use IsOverload to determine whether New and Old are
2516 /// overloaded, and to select the Old declaration that New should be
2517 /// merged with.
2518 ///
2519 /// Returns true if there was an error, false otherwise.
2520 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2521                              Scope *S, bool MergeTypeWithOld) {
2522   // Verify the old decl was also a function.
2523   FunctionDecl *Old = OldD->getAsFunction();
2524   if (!Old) {
2525     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2526       if (New->getFriendObjectKind()) {
2527         Diag(New->getLocation(), diag::err_using_decl_friend);
2528         Diag(Shadow->getTargetDecl()->getLocation(),
2529              diag::note_using_decl_target);
2530         Diag(Shadow->getUsingDecl()->getLocation(),
2531              diag::note_using_decl) << 0;
2532         return true;
2533       }
2534 
2535       // C++11 [namespace.udecl]p14:
2536       //   If a function declaration in namespace scope or block scope has the
2537       //   same name and the same parameter-type-list as a function introduced
2538       //   by a using-declaration, and the declarations do not declare the same
2539       //   function, the program is ill-formed.
2540 
2541       // Check whether the two declarations might declare the same function.
2542       Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
2543       if (Old &&
2544           !Old->getDeclContext()->getRedeclContext()->Equals(
2545               New->getDeclContext()->getRedeclContext()) &&
2546           !(Old->isExternC() && New->isExternC()))
2547         Old = nullptr;
2548 
2549       if (!Old) {
2550         Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2551         Diag(Shadow->getTargetDecl()->getLocation(),
2552              diag::note_using_decl_target);
2553         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2554         return true;
2555       }
2556       OldD = Old;
2557     } else {
2558       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2559         << New->getDeclName();
2560       Diag(OldD->getLocation(), diag::note_previous_definition);
2561       return true;
2562     }
2563   }
2564 
2565   // If the old declaration is invalid, just give up here.
2566   if (Old->isInvalidDecl())
2567     return true;
2568 
2569   diag::kind PrevDiag;
2570   SourceLocation OldLocation;
2571   std::tie(PrevDiag, OldLocation) =
2572       getNoteDiagForInvalidRedeclaration(Old, New);
2573 
2574   // Don't complain about this if we're in GNU89 mode and the old function
2575   // is an extern inline function.
2576   // Don't complain about specializations. They are not supposed to have
2577   // storage classes.
2578   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2579       New->getStorageClass() == SC_Static &&
2580       Old->hasExternalFormalLinkage() &&
2581       !New->getTemplateSpecializationInfo() &&
2582       !canRedefineFunction(Old, getLangOpts())) {
2583     if (getLangOpts().MicrosoftExt) {
2584       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2585       Diag(OldLocation, PrevDiag);
2586     } else {
2587       Diag(New->getLocation(), diag::err_static_non_static) << New;
2588       Diag(OldLocation, PrevDiag);
2589       return true;
2590     }
2591   }
2592 
2593 
2594   // If a function is first declared with a calling convention, but is later
2595   // declared or defined without one, all following decls assume the calling
2596   // convention of the first.
2597   //
2598   // It's OK if a function is first declared without a calling convention,
2599   // but is later declared or defined with the default calling convention.
2600   //
2601   // To test if either decl has an explicit calling convention, we look for
2602   // AttributedType sugar nodes on the type as written.  If they are missing or
2603   // were canonicalized away, we assume the calling convention was implicit.
2604   //
2605   // Note also that we DO NOT return at this point, because we still have
2606   // other tests to run.
2607   QualType OldQType = Context.getCanonicalType(Old->getType());
2608   QualType NewQType = Context.getCanonicalType(New->getType());
2609   const FunctionType *OldType = cast<FunctionType>(OldQType);
2610   const FunctionType *NewType = cast<FunctionType>(NewQType);
2611   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2612   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2613   bool RequiresAdjustment = false;
2614 
2615   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2616     FunctionDecl *First = Old->getFirstDecl();
2617     const FunctionType *FT =
2618         First->getType().getCanonicalType()->castAs<FunctionType>();
2619     FunctionType::ExtInfo FI = FT->getExtInfo();
2620     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2621     if (!NewCCExplicit) {
2622       // Inherit the CC from the previous declaration if it was specified
2623       // there but not here.
2624       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2625       RequiresAdjustment = true;
2626     } else {
2627       // Calling conventions aren't compatible, so complain.
2628       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2629       Diag(New->getLocation(), diag::err_cconv_change)
2630         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2631         << !FirstCCExplicit
2632         << (!FirstCCExplicit ? "" :
2633             FunctionType::getNameForCallConv(FI.getCC()));
2634 
2635       // Put the note on the first decl, since it is the one that matters.
2636       Diag(First->getLocation(), diag::note_previous_declaration);
2637       return true;
2638     }
2639   }
2640 
2641   // FIXME: diagnose the other way around?
2642   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2643     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2644     RequiresAdjustment = true;
2645   }
2646 
2647   // Merge regparm attribute.
2648   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2649       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2650     if (NewTypeInfo.getHasRegParm()) {
2651       Diag(New->getLocation(), diag::err_regparm_mismatch)
2652         << NewType->getRegParmType()
2653         << OldType->getRegParmType();
2654       Diag(OldLocation, diag::note_previous_declaration);
2655       return true;
2656     }
2657 
2658     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2659     RequiresAdjustment = true;
2660   }
2661 
2662   // Merge ns_returns_retained attribute.
2663   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2664     if (NewTypeInfo.getProducesResult()) {
2665       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2666       Diag(OldLocation, diag::note_previous_declaration);
2667       return true;
2668     }
2669 
2670     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2671     RequiresAdjustment = true;
2672   }
2673 
2674   if (RequiresAdjustment) {
2675     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2676     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2677     New->setType(QualType(AdjustedType, 0));
2678     NewQType = Context.getCanonicalType(New->getType());
2679     NewType = cast<FunctionType>(NewQType);
2680   }
2681 
2682   // If this redeclaration makes the function inline, we may need to add it to
2683   // UndefinedButUsed.
2684   if (!Old->isInlined() && New->isInlined() &&
2685       !New->hasAttr<GNUInlineAttr>() &&
2686       (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2687       Old->isUsed(false) &&
2688       !Old->isDefined() && !New->isThisDeclarationADefinition())
2689     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2690                                            SourceLocation()));
2691 
2692   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2693   // about it.
2694   if (New->hasAttr<GNUInlineAttr>() &&
2695       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2696     UndefinedButUsed.erase(Old->getCanonicalDecl());
2697   }
2698 
2699   if (getLangOpts().CPlusPlus) {
2700     // (C++98 13.1p2):
2701     //   Certain function declarations cannot be overloaded:
2702     //     -- Function declarations that differ only in the return type
2703     //        cannot be overloaded.
2704 
2705     // Go back to the type source info to compare the declared return types,
2706     // per C++1y [dcl.type.auto]p13:
2707     //   Redeclarations or specializations of a function or function template
2708     //   with a declared return type that uses a placeholder type shall also
2709     //   use that placeholder, not a deduced type.
2710     QualType OldDeclaredReturnType =
2711         (Old->getTypeSourceInfo()
2712              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2713              : OldType)->getReturnType();
2714     QualType NewDeclaredReturnType =
2715         (New->getTypeSourceInfo()
2716              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2717              : NewType)->getReturnType();
2718     QualType ResQT;
2719     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2720         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2721           New->isLocalExternDecl())) {
2722       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2723           OldDeclaredReturnType->isObjCObjectPointerType())
2724         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2725       if (ResQT.isNull()) {
2726         if (New->isCXXClassMember() && New->isOutOfLine())
2727           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2728               << New << New->getReturnTypeSourceRange();
2729         else
2730           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2731               << New->getReturnTypeSourceRange();
2732         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2733                                     << Old->getReturnTypeSourceRange();
2734         return true;
2735       }
2736       else
2737         NewQType = ResQT;
2738     }
2739 
2740     QualType OldReturnType = OldType->getReturnType();
2741     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2742     if (OldReturnType != NewReturnType) {
2743       // If this function has a deduced return type and has already been
2744       // defined, copy the deduced value from the old declaration.
2745       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2746       if (OldAT && OldAT->isDeduced()) {
2747         New->setType(
2748             SubstAutoType(New->getType(),
2749                           OldAT->isDependentType() ? Context.DependentTy
2750                                                    : OldAT->getDeducedType()));
2751         NewQType = Context.getCanonicalType(
2752             SubstAutoType(NewQType,
2753                           OldAT->isDependentType() ? Context.DependentTy
2754                                                    : OldAT->getDeducedType()));
2755       }
2756     }
2757 
2758     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2759     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2760     if (OldMethod && NewMethod) {
2761       // Preserve triviality.
2762       NewMethod->setTrivial(OldMethod->isTrivial());
2763 
2764       // MSVC allows explicit template specialization at class scope:
2765       // 2 CXXMethodDecls referring to the same function will be injected.
2766       // We don't want a redeclaration error.
2767       bool IsClassScopeExplicitSpecialization =
2768                               OldMethod->isFunctionTemplateSpecialization() &&
2769                               NewMethod->isFunctionTemplateSpecialization();
2770       bool isFriend = NewMethod->getFriendObjectKind();
2771 
2772       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2773           !IsClassScopeExplicitSpecialization) {
2774         //    -- Member function declarations with the same name and the
2775         //       same parameter types cannot be overloaded if any of them
2776         //       is a static member function declaration.
2777         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2778           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2779           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2780           return true;
2781         }
2782 
2783         // C++ [class.mem]p1:
2784         //   [...] A member shall not be declared twice in the
2785         //   member-specification, except that a nested class or member
2786         //   class template can be declared and then later defined.
2787         if (ActiveTemplateInstantiations.empty()) {
2788           unsigned NewDiag;
2789           if (isa<CXXConstructorDecl>(OldMethod))
2790             NewDiag = diag::err_constructor_redeclared;
2791           else if (isa<CXXDestructorDecl>(NewMethod))
2792             NewDiag = diag::err_destructor_redeclared;
2793           else if (isa<CXXConversionDecl>(NewMethod))
2794             NewDiag = diag::err_conv_function_redeclared;
2795           else
2796             NewDiag = diag::err_member_redeclared;
2797 
2798           Diag(New->getLocation(), NewDiag);
2799         } else {
2800           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2801             << New << New->getType();
2802         }
2803         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2804         return true;
2805 
2806       // Complain if this is an explicit declaration of a special
2807       // member that was initially declared implicitly.
2808       //
2809       // As an exception, it's okay to befriend such methods in order
2810       // to permit the implicit constructor/destructor/operator calls.
2811       } else if (OldMethod->isImplicit()) {
2812         if (isFriend) {
2813           NewMethod->setImplicit();
2814         } else {
2815           Diag(NewMethod->getLocation(),
2816                diag::err_definition_of_implicitly_declared_member)
2817             << New << getSpecialMember(OldMethod);
2818           return true;
2819         }
2820       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2821         Diag(NewMethod->getLocation(),
2822              diag::err_definition_of_explicitly_defaulted_member)
2823           << getSpecialMember(OldMethod);
2824         return true;
2825       }
2826     }
2827 
2828     // C++11 [dcl.attr.noreturn]p1:
2829     //   The first declaration of a function shall specify the noreturn
2830     //   attribute if any declaration of that function specifies the noreturn
2831     //   attribute.
2832     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2833     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2834       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2835       Diag(Old->getFirstDecl()->getLocation(),
2836            diag::note_noreturn_missing_first_decl);
2837     }
2838 
2839     // C++11 [dcl.attr.depend]p2:
2840     //   The first declaration of a function shall specify the
2841     //   carries_dependency attribute for its declarator-id if any declaration
2842     //   of the function specifies the carries_dependency attribute.
2843     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2844     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2845       Diag(CDA->getLocation(),
2846            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2847       Diag(Old->getFirstDecl()->getLocation(),
2848            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2849     }
2850 
2851     // (C++98 8.3.5p3):
2852     //   All declarations for a function shall agree exactly in both the
2853     //   return type and the parameter-type-list.
2854     // We also want to respect all the extended bits except noreturn.
2855 
2856     // noreturn should now match unless the old type info didn't have it.
2857     QualType OldQTypeForComparison = OldQType;
2858     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2859       assert(OldQType == QualType(OldType, 0));
2860       const FunctionType *OldTypeForComparison
2861         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2862       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2863       assert(OldQTypeForComparison.isCanonical());
2864     }
2865 
2866     if (haveIncompatibleLanguageLinkages(Old, New)) {
2867       // As a special case, retain the language linkage from previous
2868       // declarations of a friend function as an extension.
2869       //
2870       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2871       // and is useful because there's otherwise no way to specify language
2872       // linkage within class scope.
2873       //
2874       // Check cautiously as the friend object kind isn't yet complete.
2875       if (New->getFriendObjectKind() != Decl::FOK_None) {
2876         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2877         Diag(OldLocation, PrevDiag);
2878       } else {
2879         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2880         Diag(OldLocation, PrevDiag);
2881         return true;
2882       }
2883     }
2884 
2885     if (OldQTypeForComparison == NewQType)
2886       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2887 
2888     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2889         New->isLocalExternDecl()) {
2890       // It's OK if we couldn't merge types for a local function declaraton
2891       // if either the old or new type is dependent. We'll merge the types
2892       // when we instantiate the function.
2893       return false;
2894     }
2895 
2896     // Fall through for conflicting redeclarations and redefinitions.
2897   }
2898 
2899   // C: Function types need to be compatible, not identical. This handles
2900   // duplicate function decls like "void f(int); void f(enum X);" properly.
2901   if (!getLangOpts().CPlusPlus &&
2902       Context.typesAreCompatible(OldQType, NewQType)) {
2903     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2904     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2905     const FunctionProtoType *OldProto = nullptr;
2906     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
2907         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2908       // The old declaration provided a function prototype, but the
2909       // new declaration does not. Merge in the prototype.
2910       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2911       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
2912       NewQType =
2913           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2914                                   OldProto->getExtProtoInfo());
2915       New->setType(NewQType);
2916       New->setHasInheritedPrototype();
2917 
2918       // Synthesize parameters with the same types.
2919       SmallVector<ParmVarDecl*, 16> Params;
2920       for (const auto &ParamType : OldProto->param_types()) {
2921         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
2922                                                  SourceLocation(), nullptr,
2923                                                  ParamType, /*TInfo=*/nullptr,
2924                                                  SC_None, nullptr);
2925         Param->setScopeInfo(0, Params.size());
2926         Param->setImplicit();
2927         Params.push_back(Param);
2928       }
2929 
2930       New->setParams(Params);
2931     }
2932 
2933     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2934   }
2935 
2936   // GNU C permits a K&R definition to follow a prototype declaration
2937   // if the declared types of the parameters in the K&R definition
2938   // match the types in the prototype declaration, even when the
2939   // promoted types of the parameters from the K&R definition differ
2940   // from the types in the prototype. GCC then keeps the types from
2941   // the prototype.
2942   //
2943   // If a variadic prototype is followed by a non-variadic K&R definition,
2944   // the K&R definition becomes variadic.  This is sort of an edge case, but
2945   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2946   // C99 6.9.1p8.
2947   if (!getLangOpts().CPlusPlus &&
2948       Old->hasPrototype() && !New->hasPrototype() &&
2949       New->getType()->getAs<FunctionProtoType>() &&
2950       Old->getNumParams() == New->getNumParams()) {
2951     SmallVector<QualType, 16> ArgTypes;
2952     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2953     const FunctionProtoType *OldProto
2954       = Old->getType()->getAs<FunctionProtoType>();
2955     const FunctionProtoType *NewProto
2956       = New->getType()->getAs<FunctionProtoType>();
2957 
2958     // Determine whether this is the GNU C extension.
2959     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
2960                                                NewProto->getReturnType());
2961     bool LooseCompatible = !MergedReturn.isNull();
2962     for (unsigned Idx = 0, End = Old->getNumParams();
2963          LooseCompatible && Idx != End; ++Idx) {
2964       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2965       ParmVarDecl *NewParm = New->getParamDecl(Idx);
2966       if (Context.typesAreCompatible(OldParm->getType(),
2967                                      NewProto->getParamType(Idx))) {
2968         ArgTypes.push_back(NewParm->getType());
2969       } else if (Context.typesAreCompatible(OldParm->getType(),
2970                                             NewParm->getType(),
2971                                             /*CompareUnqualified=*/true)) {
2972         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
2973                                            NewProto->getParamType(Idx) };
2974         Warnings.push_back(Warn);
2975         ArgTypes.push_back(NewParm->getType());
2976       } else
2977         LooseCompatible = false;
2978     }
2979 
2980     if (LooseCompatible) {
2981       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2982         Diag(Warnings[Warn].NewParm->getLocation(),
2983              diag::ext_param_promoted_not_compatible_with_prototype)
2984           << Warnings[Warn].PromotedType
2985           << Warnings[Warn].OldParm->getType();
2986         if (Warnings[Warn].OldParm->getLocation().isValid())
2987           Diag(Warnings[Warn].OldParm->getLocation(),
2988                diag::note_previous_declaration);
2989       }
2990 
2991       if (MergeTypeWithOld)
2992         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2993                                              OldProto->getExtProtoInfo()));
2994       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2995     }
2996 
2997     // Fall through to diagnose conflicting types.
2998   }
2999 
3000   // A function that has already been declared has been redeclared or
3001   // defined with a different type; show an appropriate diagnostic.
3002 
3003   // If the previous declaration was an implicitly-generated builtin
3004   // declaration, then at the very least we should use a specialized note.
3005   unsigned BuiltinID;
3006   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3007     // If it's actually a library-defined builtin function like 'malloc'
3008     // or 'printf', just warn about the incompatible redeclaration.
3009     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3010       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3011       Diag(OldLocation, diag::note_previous_builtin_declaration)
3012         << Old << Old->getType();
3013 
3014       // If this is a global redeclaration, just forget hereafter
3015       // about the "builtin-ness" of the function.
3016       //
3017       // Doing this for local extern declarations is problematic.  If
3018       // the builtin declaration remains visible, a second invalid
3019       // local declaration will produce a hard error; if it doesn't
3020       // remain visible, a single bogus local redeclaration (which is
3021       // actually only a warning) could break all the downstream code.
3022       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3023         New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
3024 
3025       return false;
3026     }
3027 
3028     PrevDiag = diag::note_previous_builtin_declaration;
3029   }
3030 
3031   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3032   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3033   return true;
3034 }
3035 
3036 /// \brief Completes the merge of two function declarations that are
3037 /// known to be compatible.
3038 ///
3039 /// This routine handles the merging of attributes and other
3040 /// properties of function declarations from the old declaration to
3041 /// the new declaration, once we know that New is in fact a
3042 /// redeclaration of Old.
3043 ///
3044 /// \returns false
3045 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3046                                         Scope *S, bool MergeTypeWithOld) {
3047   // Merge the attributes
3048   mergeDeclAttributes(New, Old);
3049 
3050   // Merge "pure" flag.
3051   if (Old->isPure())
3052     New->setPure();
3053 
3054   // Merge "used" flag.
3055   if (Old->getMostRecentDecl()->isUsed(false))
3056     New->setIsUsed();
3057 
3058   // Merge attributes from the parameters.  These can mismatch with K&R
3059   // declarations.
3060   if (New->getNumParams() == Old->getNumParams())
3061     for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
3062       mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
3063                                *this);
3064 
3065   if (getLangOpts().CPlusPlus)
3066     return MergeCXXFunctionDecl(New, Old, S);
3067 
3068   // Merge the function types so the we get the composite types for the return
3069   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3070   // was visible.
3071   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3072   if (!Merged.isNull() && MergeTypeWithOld)
3073     New->setType(Merged);
3074 
3075   return false;
3076 }
3077 
3078 
3079 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3080                                 ObjCMethodDecl *oldMethod) {
3081 
3082   // Merge the attributes, including deprecated/unavailable
3083   AvailabilityMergeKind MergeKind =
3084     isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3085                                                    : AMK_Override;
3086   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3087 
3088   // Merge attributes from the parameters.
3089   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3090                                        oe = oldMethod->param_end();
3091   for (ObjCMethodDecl::param_iterator
3092          ni = newMethod->param_begin(), ne = newMethod->param_end();
3093        ni != ne && oi != oe; ++ni, ++oi)
3094     mergeParamDeclAttributes(*ni, *oi, *this);
3095 
3096   CheckObjCMethodOverride(newMethod, oldMethod);
3097 }
3098 
3099 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3100 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3101 /// emitting diagnostics as appropriate.
3102 ///
3103 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3104 /// to here in AddInitializerToDecl. We can't check them before the initializer
3105 /// is attached.
3106 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3107                              bool MergeTypeWithOld) {
3108   if (New->isInvalidDecl() || Old->isInvalidDecl())
3109     return;
3110 
3111   QualType MergedT;
3112   if (getLangOpts().CPlusPlus) {
3113     if (New->getType()->isUndeducedType()) {
3114       // We don't know what the new type is until the initializer is attached.
3115       return;
3116     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3117       // These could still be something that needs exception specs checked.
3118       return MergeVarDeclExceptionSpecs(New, Old);
3119     }
3120     // C++ [basic.link]p10:
3121     //   [...] the types specified by all declarations referring to a given
3122     //   object or function shall be identical, except that declarations for an
3123     //   array object can specify array types that differ by the presence or
3124     //   absence of a major array bound (8.3.4).
3125     else if (Old->getType()->isIncompleteArrayType() &&
3126              New->getType()->isArrayType()) {
3127       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3128       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3129       if (Context.hasSameType(OldArray->getElementType(),
3130                               NewArray->getElementType()))
3131         MergedT = New->getType();
3132     } else if (Old->getType()->isArrayType() &&
3133                New->getType()->isIncompleteArrayType()) {
3134       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3135       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3136       if (Context.hasSameType(OldArray->getElementType(),
3137                               NewArray->getElementType()))
3138         MergedT = Old->getType();
3139     } else if (New->getType()->isObjCObjectPointerType() &&
3140                Old->getType()->isObjCObjectPointerType()) {
3141       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3142                                               Old->getType());
3143     }
3144   } else {
3145     // C 6.2.7p2:
3146     //   All declarations that refer to the same object or function shall have
3147     //   compatible type.
3148     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3149   }
3150   if (MergedT.isNull()) {
3151     // It's OK if we couldn't merge types if either type is dependent, for a
3152     // block-scope variable. In other cases (static data members of class
3153     // templates, variable templates, ...), we require the types to be
3154     // equivalent.
3155     // FIXME: The C++ standard doesn't say anything about this.
3156     if ((New->getType()->isDependentType() ||
3157          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3158       // If the old type was dependent, we can't merge with it, so the new type
3159       // becomes dependent for now. We'll reproduce the original type when we
3160       // instantiate the TypeSourceInfo for the variable.
3161       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3162         New->setType(Context.DependentTy);
3163       return;
3164     }
3165 
3166     // FIXME: Even if this merging succeeds, some other non-visible declaration
3167     // of this variable might have an incompatible type. For instance:
3168     //
3169     //   extern int arr[];
3170     //   void f() { extern int arr[2]; }
3171     //   void g() { extern int arr[3]; }
3172     //
3173     // Neither C nor C++ requires a diagnostic for this, but we should still try
3174     // to diagnose it.
3175     Diag(New->getLocation(), diag::err_redefinition_different_type)
3176       << New->getDeclName() << New->getType() << Old->getType();
3177     Diag(Old->getLocation(), diag::note_previous_definition);
3178     return New->setInvalidDecl();
3179   }
3180 
3181   // Don't actually update the type on the new declaration if the old
3182   // declaration was an extern declaration in a different scope.
3183   if (MergeTypeWithOld)
3184     New->setType(MergedT);
3185 }
3186 
3187 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3188                                   LookupResult &Previous) {
3189   // C11 6.2.7p4:
3190   //   For an identifier with internal or external linkage declared
3191   //   in a scope in which a prior declaration of that identifier is
3192   //   visible, if the prior declaration specifies internal or
3193   //   external linkage, the type of the identifier at the later
3194   //   declaration becomes the composite type.
3195   //
3196   // If the variable isn't visible, we do not merge with its type.
3197   if (Previous.isShadowed())
3198     return false;
3199 
3200   if (S.getLangOpts().CPlusPlus) {
3201     // C++11 [dcl.array]p3:
3202     //   If there is a preceding declaration of the entity in the same
3203     //   scope in which the bound was specified, an omitted array bound
3204     //   is taken to be the same as in that earlier declaration.
3205     return NewVD->isPreviousDeclInSameBlockScope() ||
3206            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3207             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3208   } else {
3209     // If the old declaration was function-local, don't merge with its
3210     // type unless we're in the same function.
3211     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3212            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3213   }
3214 }
3215 
3216 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3217 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3218 /// situation, merging decls or emitting diagnostics as appropriate.
3219 ///
3220 /// Tentative definition rules (C99 6.9.2p2) are checked by
3221 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3222 /// definitions here, since the initializer hasn't been attached.
3223 ///
3224 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3225   // If the new decl is already invalid, don't do any other checking.
3226   if (New->isInvalidDecl())
3227     return;
3228 
3229   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3230 
3231   // Verify the old decl was also a variable or variable template.
3232   VarDecl *Old = nullptr;
3233   VarTemplateDecl *OldTemplate = nullptr;
3234   if (Previous.isSingleResult()) {
3235     if (NewTemplate) {
3236       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3237       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3238     } else
3239       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3240   }
3241   if (!Old) {
3242     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3243       << New->getDeclName();
3244     Diag(Previous.getRepresentativeDecl()->getLocation(),
3245          diag::note_previous_definition);
3246     return New->setInvalidDecl();
3247   }
3248 
3249   if (!shouldLinkPossiblyHiddenDecl(Old, New))
3250     return;
3251 
3252   // Ensure the template parameters are compatible.
3253   if (NewTemplate &&
3254       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3255                                       OldTemplate->getTemplateParameters(),
3256                                       /*Complain=*/true, TPL_TemplateMatch))
3257     return;
3258 
3259   // C++ [class.mem]p1:
3260   //   A member shall not be declared twice in the member-specification [...]
3261   //
3262   // Here, we need only consider static data members.
3263   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3264     Diag(New->getLocation(), diag::err_duplicate_member)
3265       << New->getIdentifier();
3266     Diag(Old->getLocation(), diag::note_previous_declaration);
3267     New->setInvalidDecl();
3268   }
3269 
3270   mergeDeclAttributes(New, Old);
3271   // Warn if an already-declared variable is made a weak_import in a subsequent
3272   // declaration
3273   if (New->hasAttr<WeakImportAttr>() &&
3274       Old->getStorageClass() == SC_None &&
3275       !Old->hasAttr<WeakImportAttr>()) {
3276     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3277     Diag(Old->getLocation(), diag::note_previous_definition);
3278     // Remove weak_import attribute on new declaration.
3279     New->dropAttr<WeakImportAttr>();
3280   }
3281 
3282   // Merge the types.
3283   VarDecl *MostRecent = Old->getMostRecentDecl();
3284   if (MostRecent != Old) {
3285     MergeVarDeclTypes(New, MostRecent,
3286                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3287     if (New->isInvalidDecl())
3288       return;
3289   }
3290 
3291   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3292   if (New->isInvalidDecl())
3293     return;
3294 
3295   diag::kind PrevDiag;
3296   SourceLocation OldLocation;
3297   std::tie(PrevDiag, OldLocation) =
3298       getNoteDiagForInvalidRedeclaration(Old, New);
3299 
3300   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3301   if (New->getStorageClass() == SC_Static &&
3302       !New->isStaticDataMember() &&
3303       Old->hasExternalFormalLinkage()) {
3304     if (getLangOpts().MicrosoftExt) {
3305       Diag(New->getLocation(), diag::ext_static_non_static)
3306           << New->getDeclName();
3307       Diag(OldLocation, PrevDiag);
3308     } else {
3309       Diag(New->getLocation(), diag::err_static_non_static)
3310           << New->getDeclName();
3311       Diag(OldLocation, PrevDiag);
3312       return New->setInvalidDecl();
3313     }
3314   }
3315   // C99 6.2.2p4:
3316   //   For an identifier declared with the storage-class specifier
3317   //   extern in a scope in which a prior declaration of that
3318   //   identifier is visible,23) if the prior declaration specifies
3319   //   internal or external linkage, the linkage of the identifier at
3320   //   the later declaration is the same as the linkage specified at
3321   //   the prior declaration. If no prior declaration is visible, or
3322   //   if the prior declaration specifies no linkage, then the
3323   //   identifier has external linkage.
3324   if (New->hasExternalStorage() && Old->hasLinkage())
3325     /* Okay */;
3326   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3327            !New->isStaticDataMember() &&
3328            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3329     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3330     Diag(OldLocation, PrevDiag);
3331     return New->setInvalidDecl();
3332   }
3333 
3334   // Check if extern is followed by non-extern and vice-versa.
3335   if (New->hasExternalStorage() &&
3336       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3337     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3338     Diag(OldLocation, PrevDiag);
3339     return New->setInvalidDecl();
3340   }
3341   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3342       !New->hasExternalStorage()) {
3343     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3344     Diag(OldLocation, PrevDiag);
3345     return New->setInvalidDecl();
3346   }
3347 
3348   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3349 
3350   // FIXME: The test for external storage here seems wrong? We still
3351   // need to check for mismatches.
3352   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3353       // Don't complain about out-of-line definitions of static members.
3354       !(Old->getLexicalDeclContext()->isRecord() &&
3355         !New->getLexicalDeclContext()->isRecord())) {
3356     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3357     Diag(OldLocation, PrevDiag);
3358     return New->setInvalidDecl();
3359   }
3360 
3361   if (New->getTLSKind() != Old->getTLSKind()) {
3362     if (!Old->getTLSKind()) {
3363       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3364       Diag(OldLocation, PrevDiag);
3365     } else if (!New->getTLSKind()) {
3366       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3367       Diag(OldLocation, PrevDiag);
3368     } else {
3369       // Do not allow redeclaration to change the variable between requiring
3370       // static and dynamic initialization.
3371       // FIXME: GCC allows this, but uses the TLS keyword on the first
3372       // declaration to determine the kind. Do we need to be compatible here?
3373       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3374         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3375       Diag(OldLocation, PrevDiag);
3376     }
3377   }
3378 
3379   // C++ doesn't have tentative definitions, so go right ahead and check here.
3380   const VarDecl *Def;
3381   if (getLangOpts().CPlusPlus &&
3382       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3383       (Def = Old->getDefinition())) {
3384     Diag(New->getLocation(), diag::err_redefinition) << New;
3385     Diag(Def->getLocation(), diag::note_previous_definition);
3386     New->setInvalidDecl();
3387     return;
3388   }
3389 
3390   if (haveIncompatibleLanguageLinkages(Old, New)) {
3391     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3392     Diag(OldLocation, PrevDiag);
3393     New->setInvalidDecl();
3394     return;
3395   }
3396 
3397   // Merge "used" flag.
3398   if (Old->getMostRecentDecl()->isUsed(false))
3399     New->setIsUsed();
3400 
3401   // Keep a chain of previous declarations.
3402   New->setPreviousDecl(Old);
3403   if (NewTemplate)
3404     NewTemplate->setPreviousDecl(OldTemplate);
3405 
3406   // Inherit access appropriately.
3407   New->setAccess(Old->getAccess());
3408   if (NewTemplate)
3409     NewTemplate->setAccess(New->getAccess());
3410 }
3411 
3412 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3413 /// no declarator (e.g. "struct foo;") is parsed.
3414 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3415                                        DeclSpec &DS) {
3416   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3417 }
3418 
3419 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) {
3420   if (!S.Context.getLangOpts().CPlusPlus)
3421     return;
3422 
3423   if (isa<CXXRecordDecl>(Tag->getParent())) {
3424     // If this tag is the direct child of a class, number it if
3425     // it is anonymous.
3426     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3427       return;
3428     MangleNumberingContext &MCtx =
3429         S.Context.getManglingNumberContext(Tag->getParent());
3430     S.Context.setManglingNumber(
3431         Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
3432     return;
3433   }
3434 
3435   // If this tag isn't a direct child of a class, number it if it is local.
3436   Decl *ManglingContextDecl;
3437   if (MangleNumberingContext *MCtx =
3438           S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3439                                           ManglingContextDecl)) {
3440     S.Context.setManglingNumber(
3441         Tag,
3442         MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
3443   }
3444 }
3445 
3446 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3447 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3448 /// parameters to cope with template friend declarations.
3449 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3450                                        DeclSpec &DS,
3451                                        MultiTemplateParamsArg TemplateParams,
3452                                        bool IsExplicitInstantiation) {
3453   Decl *TagD = nullptr;
3454   TagDecl *Tag = nullptr;
3455   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3456       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3457       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3458       DS.getTypeSpecType() == DeclSpec::TST_union ||
3459       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3460     TagD = DS.getRepAsDecl();
3461 
3462     if (!TagD) // We probably had an error
3463       return nullptr;
3464 
3465     // Note that the above type specs guarantee that the
3466     // type rep is a Decl, whereas in many of the others
3467     // it's a Type.
3468     if (isa<TagDecl>(TagD))
3469       Tag = cast<TagDecl>(TagD);
3470     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3471       Tag = CTD->getTemplatedDecl();
3472   }
3473 
3474   if (Tag) {
3475     HandleTagNumbering(*this, Tag, S);
3476     Tag->setFreeStanding();
3477     if (Tag->isInvalidDecl())
3478       return Tag;
3479   }
3480 
3481   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3482     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3483     // or incomplete types shall not be restrict-qualified."
3484     if (TypeQuals & DeclSpec::TQ_restrict)
3485       Diag(DS.getRestrictSpecLoc(),
3486            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3487            << DS.getSourceRange();
3488   }
3489 
3490   if (DS.isConstexprSpecified()) {
3491     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3492     // and definitions of functions and variables.
3493     if (Tag)
3494       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3495         << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3496             DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3497             DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3498             DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
3499     else
3500       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3501     // Don't emit warnings after this error.
3502     return TagD;
3503   }
3504 
3505   DiagnoseFunctionSpecifiers(DS);
3506 
3507   if (DS.isFriendSpecified()) {
3508     // If we're dealing with a decl but not a TagDecl, assume that
3509     // whatever routines created it handled the friendship aspect.
3510     if (TagD && !Tag)
3511       return nullptr;
3512     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3513   }
3514 
3515   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3516   bool IsExplicitSpecialization =
3517     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3518   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3519       !IsExplicitInstantiation && !IsExplicitSpecialization) {
3520     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3521     // nested-name-specifier unless it is an explicit instantiation
3522     // or an explicit specialization.
3523     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3524     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3525       << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3526           DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3527           DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3528           DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3529       << SS.getRange();
3530     return nullptr;
3531   }
3532 
3533   // Track whether this decl-specifier declares anything.
3534   bool DeclaresAnything = true;
3535 
3536   // Handle anonymous struct definitions.
3537   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3538     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3539         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3540       if (getLangOpts().CPlusPlus ||
3541           Record->getDeclContext()->isRecord())
3542         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3543                                            Context.getPrintingPolicy());
3544 
3545       DeclaresAnything = false;
3546     }
3547   }
3548 
3549   // C11 6.7.2.1p2:
3550   //   A struct-declaration that does not declare an anonymous structure or
3551   //   anonymous union shall contain a struct-declarator-list.
3552   //
3553   // This rule also existed in C89 and C99; the grammar for struct-declaration
3554   // did not permit a struct-declaration without a struct-declarator-list.
3555   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3556       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3557     // Check for Microsoft C extension: anonymous struct/union member.
3558     // Handle 2 kinds of anonymous struct/union:
3559     //   struct STRUCT;
3560     //   union UNION;
3561     // and
3562     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3563     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3564     if ((Tag && Tag->getDeclName()) ||
3565         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3566       RecordDecl *Record = nullptr;
3567       if (Tag)
3568         Record = dyn_cast<RecordDecl>(Tag);
3569       else if (const RecordType *RT =
3570                    DS.getRepAsType().get()->getAsStructureType())
3571         Record = RT->getDecl();
3572       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3573         Record = UT->getDecl();
3574 
3575       if (Record && getLangOpts().MicrosoftExt) {
3576         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3577           << Record->isUnion() << DS.getSourceRange();
3578         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3579       }
3580 
3581       DeclaresAnything = false;
3582     }
3583   }
3584 
3585   // Skip all the checks below if we have a type error.
3586   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3587       (TagD && TagD->isInvalidDecl()))
3588     return TagD;
3589 
3590   if (getLangOpts().CPlusPlus &&
3591       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3592     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3593       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3594           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3595         DeclaresAnything = false;
3596 
3597   if (!DS.isMissingDeclaratorOk()) {
3598     // Customize diagnostic for a typedef missing a name.
3599     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3600       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3601         << DS.getSourceRange();
3602     else
3603       DeclaresAnything = false;
3604   }
3605 
3606   if (DS.isModulePrivateSpecified() &&
3607       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3608     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3609       << Tag->getTagKind()
3610       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3611 
3612   ActOnDocumentableDecl(TagD);
3613 
3614   // C 6.7/2:
3615   //   A declaration [...] shall declare at least a declarator [...], a tag,
3616   //   or the members of an enumeration.
3617   // C++ [dcl.dcl]p3:
3618   //   [If there are no declarators], and except for the declaration of an
3619   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3620   //   names into the program, or shall redeclare a name introduced by a
3621   //   previous declaration.
3622   if (!DeclaresAnything) {
3623     // In C, we allow this as a (popular) extension / bug. Don't bother
3624     // producing further diagnostics for redundant qualifiers after this.
3625     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3626     return TagD;
3627   }
3628 
3629   // C++ [dcl.stc]p1:
3630   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3631   //   init-declarator-list of the declaration shall not be empty.
3632   // C++ [dcl.fct.spec]p1:
3633   //   If a cv-qualifier appears in a decl-specifier-seq, the
3634   //   init-declarator-list of the declaration shall not be empty.
3635   //
3636   // Spurious qualifiers here appear to be valid in C.
3637   unsigned DiagID = diag::warn_standalone_specifier;
3638   if (getLangOpts().CPlusPlus)
3639     DiagID = diag::ext_standalone_specifier;
3640 
3641   // Note that a linkage-specification sets a storage class, but
3642   // 'extern "C" struct foo;' is actually valid and not theoretically
3643   // useless.
3644   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3645     if (SCS == DeclSpec::SCS_mutable)
3646       // Since mutable is not a viable storage class specifier in C, there is
3647       // no reason to treat it as an extension. Instead, diagnose as an error.
3648       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3649     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3650       Diag(DS.getStorageClassSpecLoc(), DiagID)
3651         << DeclSpec::getSpecifierName(SCS);
3652   }
3653 
3654   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3655     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3656       << DeclSpec::getSpecifierName(TSCS);
3657   if (DS.getTypeQualifiers()) {
3658     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3659       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3660     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3661       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3662     // Restrict is covered above.
3663     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3664       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3665   }
3666 
3667   // Warn about ignored type attributes, for example:
3668   // __attribute__((aligned)) struct A;
3669   // Attributes should be placed after tag to apply to type declaration.
3670   if (!DS.getAttributes().empty()) {
3671     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3672     if (TypeSpecType == DeclSpec::TST_class ||
3673         TypeSpecType == DeclSpec::TST_struct ||
3674         TypeSpecType == DeclSpec::TST_interface ||
3675         TypeSpecType == DeclSpec::TST_union ||
3676         TypeSpecType == DeclSpec::TST_enum) {
3677       AttributeList* attrs = DS.getAttributes().getList();
3678       while (attrs) {
3679         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3680         << attrs->getName()
3681         << (TypeSpecType == DeclSpec::TST_class ? 0 :
3682             TypeSpecType == DeclSpec::TST_struct ? 1 :
3683             TypeSpecType == DeclSpec::TST_union ? 2 :
3684             TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
3685         attrs = attrs->getNext();
3686       }
3687     }
3688   }
3689 
3690   return TagD;
3691 }
3692 
3693 /// We are trying to inject an anonymous member into the given scope;
3694 /// check if there's an existing declaration that can't be overloaded.
3695 ///
3696 /// \return true if this is a forbidden redeclaration
3697 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3698                                          Scope *S,
3699                                          DeclContext *Owner,
3700                                          DeclarationName Name,
3701                                          SourceLocation NameLoc,
3702                                          unsigned diagnostic) {
3703   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3704                  Sema::ForRedeclaration);
3705   if (!SemaRef.LookupName(R, S)) return false;
3706 
3707   if (R.getAsSingle<TagDecl>())
3708     return false;
3709 
3710   // Pick a representative declaration.
3711   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3712   assert(PrevDecl && "Expected a non-null Decl");
3713 
3714   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3715     return false;
3716 
3717   SemaRef.Diag(NameLoc, diagnostic) << Name;
3718   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3719 
3720   return true;
3721 }
3722 
3723 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3724 /// anonymous struct or union AnonRecord into the owning context Owner
3725 /// and scope S. This routine will be invoked just after we realize
3726 /// that an unnamed union or struct is actually an anonymous union or
3727 /// struct, e.g.,
3728 ///
3729 /// @code
3730 /// union {
3731 ///   int i;
3732 ///   float f;
3733 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3734 ///    // f into the surrounding scope.x
3735 /// @endcode
3736 ///
3737 /// This routine is recursive, injecting the names of nested anonymous
3738 /// structs/unions into the owning context and scope as well.
3739 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3740                                          DeclContext *Owner,
3741                                          RecordDecl *AnonRecord,
3742                                          AccessSpecifier AS,
3743                                          SmallVectorImpl<NamedDecl *> &Chaining,
3744                                          bool MSAnonStruct) {
3745   unsigned diagKind
3746     = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3747                             : diag::err_anonymous_struct_member_redecl;
3748 
3749   bool Invalid = false;
3750 
3751   // Look every FieldDecl and IndirectFieldDecl with a name.
3752   for (auto *D : AnonRecord->decls()) {
3753     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3754         cast<NamedDecl>(D)->getDeclName()) {
3755       ValueDecl *VD = cast<ValueDecl>(D);
3756       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3757                                        VD->getLocation(), diagKind)) {
3758         // C++ [class.union]p2:
3759         //   The names of the members of an anonymous union shall be
3760         //   distinct from the names of any other entity in the
3761         //   scope in which the anonymous union is declared.
3762         Invalid = true;
3763       } else {
3764         // C++ [class.union]p2:
3765         //   For the purpose of name lookup, after the anonymous union
3766         //   definition, the members of the anonymous union are
3767         //   considered to have been defined in the scope in which the
3768         //   anonymous union is declared.
3769         unsigned OldChainingSize = Chaining.size();
3770         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3771           Chaining.append(IF->chain_begin(), IF->chain_end());
3772         else
3773           Chaining.push_back(VD);
3774 
3775         assert(Chaining.size() >= 2);
3776         NamedDecl **NamedChain =
3777           new (SemaRef.Context)NamedDecl*[Chaining.size()];
3778         for (unsigned i = 0; i < Chaining.size(); i++)
3779           NamedChain[i] = Chaining[i];
3780 
3781         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
3782             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
3783             VD->getType(), NamedChain, Chaining.size());
3784 
3785         for (const auto *Attr : VD->attrs())
3786           IndirectField->addAttr(Attr->clone(SemaRef.Context));
3787 
3788         IndirectField->setAccess(AS);
3789         IndirectField->setImplicit();
3790         SemaRef.PushOnScopeChains(IndirectField, S);
3791 
3792         // That includes picking up the appropriate access specifier.
3793         if (AS != AS_none) IndirectField->setAccess(AS);
3794 
3795         Chaining.resize(OldChainingSize);
3796       }
3797     }
3798   }
3799 
3800   return Invalid;
3801 }
3802 
3803 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3804 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
3805 /// illegal input values are mapped to SC_None.
3806 static StorageClass
3807 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3808   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3809   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3810          "Parser allowed 'typedef' as storage class VarDecl.");
3811   switch (StorageClassSpec) {
3812   case DeclSpec::SCS_unspecified:    return SC_None;
3813   case DeclSpec::SCS_extern:
3814     if (DS.isExternInLinkageSpec())
3815       return SC_None;
3816     return SC_Extern;
3817   case DeclSpec::SCS_static:         return SC_Static;
3818   case DeclSpec::SCS_auto:           return SC_Auto;
3819   case DeclSpec::SCS_register:       return SC_Register;
3820   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3821     // Illegal SCSs map to None: error reporting is up to the caller.
3822   case DeclSpec::SCS_mutable:        // Fall through.
3823   case DeclSpec::SCS_typedef:        return SC_None;
3824   }
3825   llvm_unreachable("unknown storage class specifier");
3826 }
3827 
3828 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3829   assert(Record->hasInClassInitializer());
3830 
3831   for (const auto *I : Record->decls()) {
3832     const auto *FD = dyn_cast<FieldDecl>(I);
3833     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
3834       FD = IFD->getAnonField();
3835     if (FD && FD->hasInClassInitializer())
3836       return FD->getLocation();
3837   }
3838 
3839   llvm_unreachable("couldn't find in-class initializer");
3840 }
3841 
3842 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3843                                       SourceLocation DefaultInitLoc) {
3844   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3845     return;
3846 
3847   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3848   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3849 }
3850 
3851 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3852                                       CXXRecordDecl *AnonUnion) {
3853   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3854     return;
3855 
3856   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3857 }
3858 
3859 /// BuildAnonymousStructOrUnion - Handle the declaration of an
3860 /// anonymous structure or union. Anonymous unions are a C++ feature
3861 /// (C++ [class.union]) and a C11 feature; anonymous structures
3862 /// are a C11 feature and GNU C++ extension.
3863 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3864                                         AccessSpecifier AS,
3865                                         RecordDecl *Record,
3866                                         const PrintingPolicy &Policy) {
3867   DeclContext *Owner = Record->getDeclContext();
3868 
3869   // Diagnose whether this anonymous struct/union is an extension.
3870   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
3871     Diag(Record->getLocation(), diag::ext_anonymous_union);
3872   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
3873     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
3874   else if (!Record->isUnion() && !getLangOpts().C11)
3875     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
3876 
3877   // C and C++ require different kinds of checks for anonymous
3878   // structs/unions.
3879   bool Invalid = false;
3880   if (getLangOpts().CPlusPlus) {
3881     const char *PrevSpec = nullptr;
3882     unsigned DiagID;
3883     if (Record->isUnion()) {
3884       // C++ [class.union]p6:
3885       //   Anonymous unions declared in a named namespace or in the
3886       //   global namespace shall be declared static.
3887       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3888           (isa<TranslationUnitDecl>(Owner) ||
3889            (isa<NamespaceDecl>(Owner) &&
3890             cast<NamespaceDecl>(Owner)->getDeclName()))) {
3891         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3892           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3893 
3894         // Recover by adding 'static'.
3895         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3896                                PrevSpec, DiagID, Policy);
3897       }
3898       // C++ [class.union]p6:
3899       //   A storage class is not allowed in a declaration of an
3900       //   anonymous union in a class scope.
3901       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3902                isa<RecordDecl>(Owner)) {
3903         Diag(DS.getStorageClassSpecLoc(),
3904              diag::err_anonymous_union_with_storage_spec)
3905           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3906 
3907         // Recover by removing the storage specifier.
3908         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3909                                SourceLocation(),
3910                                PrevSpec, DiagID, Context.getPrintingPolicy());
3911       }
3912     }
3913 
3914     // Ignore const/volatile/restrict qualifiers.
3915     if (DS.getTypeQualifiers()) {
3916       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3917         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3918           << Record->isUnion() << "const"
3919           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3920       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3921         Diag(DS.getVolatileSpecLoc(),
3922              diag::ext_anonymous_struct_union_qualified)
3923           << Record->isUnion() << "volatile"
3924           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3925       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3926         Diag(DS.getRestrictSpecLoc(),
3927              diag::ext_anonymous_struct_union_qualified)
3928           << Record->isUnion() << "restrict"
3929           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3930       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3931         Diag(DS.getAtomicSpecLoc(),
3932              diag::ext_anonymous_struct_union_qualified)
3933           << Record->isUnion() << "_Atomic"
3934           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
3935 
3936       DS.ClearTypeQualifiers();
3937     }
3938 
3939     // C++ [class.union]p2:
3940     //   The member-specification of an anonymous union shall only
3941     //   define non-static data members. [Note: nested types and
3942     //   functions cannot be declared within an anonymous union. ]
3943     for (auto *Mem : Record->decls()) {
3944       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
3945         // C++ [class.union]p3:
3946         //   An anonymous union shall not have private or protected
3947         //   members (clause 11).
3948         assert(FD->getAccess() != AS_none);
3949         if (FD->getAccess() != AS_public) {
3950           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3951             << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3952           Invalid = true;
3953         }
3954 
3955         // C++ [class.union]p1
3956         //   An object of a class with a non-trivial constructor, a non-trivial
3957         //   copy constructor, a non-trivial destructor, or a non-trivial copy
3958         //   assignment operator cannot be a member of a union, nor can an
3959         //   array of such objects.
3960         if (CheckNontrivialField(FD))
3961           Invalid = true;
3962       } else if (Mem->isImplicit()) {
3963         // Any implicit members are fine.
3964       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
3965         // This is a type that showed up in an
3966         // elaborated-type-specifier inside the anonymous struct or
3967         // union, but which actually declares a type outside of the
3968         // anonymous struct or union. It's okay.
3969       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
3970         if (!MemRecord->isAnonymousStructOrUnion() &&
3971             MemRecord->getDeclName()) {
3972           // Visual C++ allows type definition in anonymous struct or union.
3973           if (getLangOpts().MicrosoftExt)
3974             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3975               << (int)Record->isUnion();
3976           else {
3977             // This is a nested type declaration.
3978             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3979               << (int)Record->isUnion();
3980             Invalid = true;
3981           }
3982         } else {
3983           // This is an anonymous type definition within another anonymous type.
3984           // This is a popular extension, provided by Plan9, MSVC and GCC, but
3985           // not part of standard C++.
3986           Diag(MemRecord->getLocation(),
3987                diag::ext_anonymous_record_with_anonymous_type)
3988             << (int)Record->isUnion();
3989         }
3990       } else if (isa<AccessSpecDecl>(Mem)) {
3991         // Any access specifier is fine.
3992       } else if (isa<StaticAssertDecl>(Mem)) {
3993         // In C++1z, static_assert declarations are also fine.
3994       } else {
3995         // We have something that isn't a non-static data
3996         // member. Complain about it.
3997         unsigned DK = diag::err_anonymous_record_bad_member;
3998         if (isa<TypeDecl>(Mem))
3999           DK = diag::err_anonymous_record_with_type;
4000         else if (isa<FunctionDecl>(Mem))
4001           DK = diag::err_anonymous_record_with_function;
4002         else if (isa<VarDecl>(Mem))
4003           DK = diag::err_anonymous_record_with_static;
4004 
4005         // Visual C++ allows type definition in anonymous struct or union.
4006         if (getLangOpts().MicrosoftExt &&
4007             DK == diag::err_anonymous_record_with_type)
4008           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4009             << (int)Record->isUnion();
4010         else {
4011           Diag(Mem->getLocation(), DK)
4012               << (int)Record->isUnion();
4013           Invalid = true;
4014         }
4015       }
4016     }
4017 
4018     // C++11 [class.union]p8 (DR1460):
4019     //   At most one variant member of a union may have a
4020     //   brace-or-equal-initializer.
4021     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4022         Owner->isRecord())
4023       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4024                                 cast<CXXRecordDecl>(Record));
4025   }
4026 
4027   if (!Record->isUnion() && !Owner->isRecord()) {
4028     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4029       << (int)getLangOpts().CPlusPlus;
4030     Invalid = true;
4031   }
4032 
4033   // Mock up a declarator.
4034   Declarator Dc(DS, Declarator::MemberContext);
4035   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4036   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4037 
4038   // Create a declaration for this anonymous struct/union.
4039   NamedDecl *Anon = nullptr;
4040   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4041     Anon = FieldDecl::Create(Context, OwningClass,
4042                              DS.getLocStart(),
4043                              Record->getLocation(),
4044                              /*IdentifierInfo=*/nullptr,
4045                              Context.getTypeDeclType(Record),
4046                              TInfo,
4047                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4048                              /*InitStyle=*/ICIS_NoInit);
4049     Anon->setAccess(AS);
4050     if (getLangOpts().CPlusPlus)
4051       FieldCollector->Add(cast<FieldDecl>(Anon));
4052   } else {
4053     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4054     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4055     if (SCSpec == DeclSpec::SCS_mutable) {
4056       // mutable can only appear on non-static class members, so it's always
4057       // an error here
4058       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4059       Invalid = true;
4060       SC = SC_None;
4061     }
4062 
4063     Anon = VarDecl::Create(Context, Owner,
4064                            DS.getLocStart(),
4065                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4066                            Context.getTypeDeclType(Record),
4067                            TInfo, SC);
4068 
4069     // Default-initialize the implicit variable. This initialization will be
4070     // trivial in almost all cases, except if a union member has an in-class
4071     // initializer:
4072     //   union { int n = 0; };
4073     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4074   }
4075   Anon->setImplicit();
4076 
4077   // Mark this as an anonymous struct/union type.
4078   Record->setAnonymousStructOrUnion(true);
4079 
4080   // Add the anonymous struct/union object to the current
4081   // context. We'll be referencing this object when we refer to one of
4082   // its members.
4083   Owner->addDecl(Anon);
4084 
4085   // Inject the members of the anonymous struct/union into the owning
4086   // context and into the identifier resolver chain for name lookup
4087   // purposes.
4088   SmallVector<NamedDecl*, 2> Chain;
4089   Chain.push_back(Anon);
4090 
4091   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
4092                                           Chain, false))
4093     Invalid = true;
4094 
4095   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4096     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4097       Decl *ManglingContextDecl;
4098       if (MangleNumberingContext *MCtx =
4099               getCurrentMangleNumberContext(NewVD->getDeclContext(),
4100                                             ManglingContextDecl)) {
4101         Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
4102         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4103       }
4104     }
4105   }
4106 
4107   if (Invalid)
4108     Anon->setInvalidDecl();
4109 
4110   return Anon;
4111 }
4112 
4113 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4114 /// Microsoft C anonymous structure.
4115 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4116 /// Example:
4117 ///
4118 /// struct A { int a; };
4119 /// struct B { struct A; int b; };
4120 ///
4121 /// void foo() {
4122 ///   B var;
4123 ///   var.a = 3;
4124 /// }
4125 ///
4126 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4127                                            RecordDecl *Record) {
4128   assert(Record && "expected a record!");
4129 
4130   // Mock up a declarator.
4131   Declarator Dc(DS, Declarator::TypeNameContext);
4132   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4133   assert(TInfo && "couldn't build declarator info for anonymous struct");
4134 
4135   auto *ParentDecl = cast<RecordDecl>(CurContext);
4136   QualType RecTy = Context.getTypeDeclType(Record);
4137 
4138   // Create a declaration for this anonymous struct.
4139   NamedDecl *Anon = FieldDecl::Create(Context,
4140                              ParentDecl,
4141                              DS.getLocStart(),
4142                              DS.getLocStart(),
4143                              /*IdentifierInfo=*/nullptr,
4144                              RecTy,
4145                              TInfo,
4146                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4147                              /*InitStyle=*/ICIS_NoInit);
4148   Anon->setImplicit();
4149 
4150   // Add the anonymous struct object to the current context.
4151   CurContext->addDecl(Anon);
4152 
4153   // Inject the members of the anonymous struct into the current
4154   // context and into the identifier resolver chain for name lookup
4155   // purposes.
4156   SmallVector<NamedDecl*, 2> Chain;
4157   Chain.push_back(Anon);
4158 
4159   RecordDecl *RecordDef = Record->getDefinition();
4160   if (RequireCompleteType(Anon->getLocation(), RecTy,
4161                           diag::err_field_incomplete) ||
4162       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4163                                           AS_none, Chain, true)) {
4164     Anon->setInvalidDecl();
4165     ParentDecl->setInvalidDecl();
4166   }
4167 
4168   return Anon;
4169 }
4170 
4171 /// GetNameForDeclarator - Determine the full declaration name for the
4172 /// given Declarator.
4173 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4174   return GetNameFromUnqualifiedId(D.getName());
4175 }
4176 
4177 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4178 DeclarationNameInfo
4179 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4180   DeclarationNameInfo NameInfo;
4181   NameInfo.setLoc(Name.StartLocation);
4182 
4183   switch (Name.getKind()) {
4184 
4185   case UnqualifiedId::IK_ImplicitSelfParam:
4186   case UnqualifiedId::IK_Identifier:
4187     NameInfo.setName(Name.Identifier);
4188     NameInfo.setLoc(Name.StartLocation);
4189     return NameInfo;
4190 
4191   case UnqualifiedId::IK_OperatorFunctionId:
4192     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4193                                            Name.OperatorFunctionId.Operator));
4194     NameInfo.setLoc(Name.StartLocation);
4195     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4196       = Name.OperatorFunctionId.SymbolLocations[0];
4197     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4198       = Name.EndLocation.getRawEncoding();
4199     return NameInfo;
4200 
4201   case UnqualifiedId::IK_LiteralOperatorId:
4202     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4203                                                            Name.Identifier));
4204     NameInfo.setLoc(Name.StartLocation);
4205     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4206     return NameInfo;
4207 
4208   case UnqualifiedId::IK_ConversionFunctionId: {
4209     TypeSourceInfo *TInfo;
4210     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4211     if (Ty.isNull())
4212       return DeclarationNameInfo();
4213     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4214                                                Context.getCanonicalType(Ty)));
4215     NameInfo.setLoc(Name.StartLocation);
4216     NameInfo.setNamedTypeInfo(TInfo);
4217     return NameInfo;
4218   }
4219 
4220   case UnqualifiedId::IK_ConstructorName: {
4221     TypeSourceInfo *TInfo;
4222     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4223     if (Ty.isNull())
4224       return DeclarationNameInfo();
4225     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4226                                               Context.getCanonicalType(Ty)));
4227     NameInfo.setLoc(Name.StartLocation);
4228     NameInfo.setNamedTypeInfo(TInfo);
4229     return NameInfo;
4230   }
4231 
4232   case UnqualifiedId::IK_ConstructorTemplateId: {
4233     // In well-formed code, we can only have a constructor
4234     // template-id that refers to the current context, so go there
4235     // to find the actual type being constructed.
4236     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4237     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4238       return DeclarationNameInfo();
4239 
4240     // Determine the type of the class being constructed.
4241     QualType CurClassType = Context.getTypeDeclType(CurClass);
4242 
4243     // FIXME: Check two things: that the template-id names the same type as
4244     // CurClassType, and that the template-id does not occur when the name
4245     // was qualified.
4246 
4247     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4248                                     Context.getCanonicalType(CurClassType)));
4249     NameInfo.setLoc(Name.StartLocation);
4250     // FIXME: should we retrieve TypeSourceInfo?
4251     NameInfo.setNamedTypeInfo(nullptr);
4252     return NameInfo;
4253   }
4254 
4255   case UnqualifiedId::IK_DestructorName: {
4256     TypeSourceInfo *TInfo;
4257     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4258     if (Ty.isNull())
4259       return DeclarationNameInfo();
4260     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4261                                               Context.getCanonicalType(Ty)));
4262     NameInfo.setLoc(Name.StartLocation);
4263     NameInfo.setNamedTypeInfo(TInfo);
4264     return NameInfo;
4265   }
4266 
4267   case UnqualifiedId::IK_TemplateId: {
4268     TemplateName TName = Name.TemplateId->Template.get();
4269     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4270     return Context.getNameForTemplate(TName, TNameLoc);
4271   }
4272 
4273   } // switch (Name.getKind())
4274 
4275   llvm_unreachable("Unknown name kind");
4276 }
4277 
4278 static QualType getCoreType(QualType Ty) {
4279   do {
4280     if (Ty->isPointerType() || Ty->isReferenceType())
4281       Ty = Ty->getPointeeType();
4282     else if (Ty->isArrayType())
4283       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4284     else
4285       return Ty.withoutLocalFastQualifiers();
4286   } while (true);
4287 }
4288 
4289 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4290 /// and Definition have "nearly" matching parameters. This heuristic is
4291 /// used to improve diagnostics in the case where an out-of-line function
4292 /// definition doesn't match any declaration within the class or namespace.
4293 /// Also sets Params to the list of indices to the parameters that differ
4294 /// between the declaration and the definition. If hasSimilarParameters
4295 /// returns true and Params is empty, then all of the parameters match.
4296 static bool hasSimilarParameters(ASTContext &Context,
4297                                      FunctionDecl *Declaration,
4298                                      FunctionDecl *Definition,
4299                                      SmallVectorImpl<unsigned> &Params) {
4300   Params.clear();
4301   if (Declaration->param_size() != Definition->param_size())
4302     return false;
4303   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4304     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4305     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4306 
4307     // The parameter types are identical
4308     if (Context.hasSameType(DefParamTy, DeclParamTy))
4309       continue;
4310 
4311     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4312     QualType DefParamBaseTy = getCoreType(DefParamTy);
4313     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4314     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4315 
4316     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4317         (DeclTyName && DeclTyName == DefTyName))
4318       Params.push_back(Idx);
4319     else  // The two parameters aren't even close
4320       return false;
4321   }
4322 
4323   return true;
4324 }
4325 
4326 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4327 /// declarator needs to be rebuilt in the current instantiation.
4328 /// Any bits of declarator which appear before the name are valid for
4329 /// consideration here.  That's specifically the type in the decl spec
4330 /// and the base type in any member-pointer chunks.
4331 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4332                                                     DeclarationName Name) {
4333   // The types we specifically need to rebuild are:
4334   //   - typenames, typeofs, and decltypes
4335   //   - types which will become injected class names
4336   // Of course, we also need to rebuild any type referencing such a
4337   // type.  It's safest to just say "dependent", but we call out a
4338   // few cases here.
4339 
4340   DeclSpec &DS = D.getMutableDeclSpec();
4341   switch (DS.getTypeSpecType()) {
4342   case DeclSpec::TST_typename:
4343   case DeclSpec::TST_typeofType:
4344   case DeclSpec::TST_underlyingType:
4345   case DeclSpec::TST_atomic: {
4346     // Grab the type from the parser.
4347     TypeSourceInfo *TSI = nullptr;
4348     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4349     if (T.isNull() || !T->isDependentType()) break;
4350 
4351     // Make sure there's a type source info.  This isn't really much
4352     // of a waste; most dependent types should have type source info
4353     // attached already.
4354     if (!TSI)
4355       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4356 
4357     // Rebuild the type in the current instantiation.
4358     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4359     if (!TSI) return true;
4360 
4361     // Store the new type back in the decl spec.
4362     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4363     DS.UpdateTypeRep(LocType);
4364     break;
4365   }
4366 
4367   case DeclSpec::TST_decltype:
4368   case DeclSpec::TST_typeofExpr: {
4369     Expr *E = DS.getRepAsExpr();
4370     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4371     if (Result.isInvalid()) return true;
4372     DS.UpdateExprRep(Result.get());
4373     break;
4374   }
4375 
4376   default:
4377     // Nothing to do for these decl specs.
4378     break;
4379   }
4380 
4381   // It doesn't matter what order we do this in.
4382   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4383     DeclaratorChunk &Chunk = D.getTypeObject(I);
4384 
4385     // The only type information in the declarator which can come
4386     // before the declaration name is the base type of a member
4387     // pointer.
4388     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4389       continue;
4390 
4391     // Rebuild the scope specifier in-place.
4392     CXXScopeSpec &SS = Chunk.Mem.Scope();
4393     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4394       return true;
4395   }
4396 
4397   return false;
4398 }
4399 
4400 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4401   D.setFunctionDefinitionKind(FDK_Declaration);
4402   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4403 
4404   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4405       Dcl && Dcl->getDeclContext()->isFileContext())
4406     Dcl->setTopLevelDeclInObjCContainer();
4407 
4408   return Dcl;
4409 }
4410 
4411 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4412 ///   If T is the name of a class, then each of the following shall have a
4413 ///   name different from T:
4414 ///     - every static data member of class T;
4415 ///     - every member function of class T
4416 ///     - every member of class T that is itself a type;
4417 /// \returns true if the declaration name violates these rules.
4418 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4419                                    DeclarationNameInfo NameInfo) {
4420   DeclarationName Name = NameInfo.getName();
4421 
4422   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4423     if (Record->getIdentifier() && Record->getDeclName() == Name) {
4424       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4425       return true;
4426     }
4427 
4428   return false;
4429 }
4430 
4431 /// \brief Diagnose a declaration whose declarator-id has the given
4432 /// nested-name-specifier.
4433 ///
4434 /// \param SS The nested-name-specifier of the declarator-id.
4435 ///
4436 /// \param DC The declaration context to which the nested-name-specifier
4437 /// resolves.
4438 ///
4439 /// \param Name The name of the entity being declared.
4440 ///
4441 /// \param Loc The location of the name of the entity being declared.
4442 ///
4443 /// \returns true if we cannot safely recover from this error, false otherwise.
4444 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4445                                         DeclarationName Name,
4446                                         SourceLocation Loc) {
4447   DeclContext *Cur = CurContext;
4448   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4449     Cur = Cur->getParent();
4450 
4451   // If the user provided a superfluous scope specifier that refers back to the
4452   // class in which the entity is already declared, diagnose and ignore it.
4453   //
4454   // class X {
4455   //   void X::f();
4456   // };
4457   //
4458   // Note, it was once ill-formed to give redundant qualification in all
4459   // contexts, but that rule was removed by DR482.
4460   if (Cur->Equals(DC)) {
4461     if (Cur->isRecord()) {
4462       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4463                                       : diag::err_member_extra_qualification)
4464         << Name << FixItHint::CreateRemoval(SS.getRange());
4465       SS.clear();
4466     } else {
4467       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4468     }
4469     return false;
4470   }
4471 
4472   // Check whether the qualifying scope encloses the scope of the original
4473   // declaration.
4474   if (!Cur->Encloses(DC)) {
4475     if (Cur->isRecord())
4476       Diag(Loc, diag::err_member_qualification)
4477         << Name << SS.getRange();
4478     else if (isa<TranslationUnitDecl>(DC))
4479       Diag(Loc, diag::err_invalid_declarator_global_scope)
4480         << Name << SS.getRange();
4481     else if (isa<FunctionDecl>(Cur))
4482       Diag(Loc, diag::err_invalid_declarator_in_function)
4483         << Name << SS.getRange();
4484     else if (isa<BlockDecl>(Cur))
4485       Diag(Loc, diag::err_invalid_declarator_in_block)
4486         << Name << SS.getRange();
4487     else
4488       Diag(Loc, diag::err_invalid_declarator_scope)
4489       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4490 
4491     return true;
4492   }
4493 
4494   if (Cur->isRecord()) {
4495     // Cannot qualify members within a class.
4496     Diag(Loc, diag::err_member_qualification)
4497       << Name << SS.getRange();
4498     SS.clear();
4499 
4500     // C++ constructors and destructors with incorrect scopes can break
4501     // our AST invariants by having the wrong underlying types. If
4502     // that's the case, then drop this declaration entirely.
4503     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4504          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4505         !Context.hasSameType(Name.getCXXNameType(),
4506                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4507       return true;
4508 
4509     return false;
4510   }
4511 
4512   // C++11 [dcl.meaning]p1:
4513   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4514   //   not begin with a decltype-specifer"
4515   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4516   while (SpecLoc.getPrefix())
4517     SpecLoc = SpecLoc.getPrefix();
4518   if (dyn_cast_or_null<DecltypeType>(
4519         SpecLoc.getNestedNameSpecifier()->getAsType()))
4520     Diag(Loc, diag::err_decltype_in_declarator)
4521       << SpecLoc.getTypeLoc().getSourceRange();
4522 
4523   return false;
4524 }
4525 
4526 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4527                                   MultiTemplateParamsArg TemplateParamLists) {
4528   // TODO: consider using NameInfo for diagnostic.
4529   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4530   DeclarationName Name = NameInfo.getName();
4531 
4532   // All of these full declarators require an identifier.  If it doesn't have
4533   // one, the ParsedFreeStandingDeclSpec action should be used.
4534   if (!Name) {
4535     if (!D.isInvalidType())  // Reject this if we think it is valid.
4536       Diag(D.getDeclSpec().getLocStart(),
4537            diag::err_declarator_need_ident)
4538         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4539     return nullptr;
4540   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4541     return nullptr;
4542 
4543   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4544   // we find one that is.
4545   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4546          (S->getFlags() & Scope::TemplateParamScope) != 0)
4547     S = S->getParent();
4548 
4549   DeclContext *DC = CurContext;
4550   if (D.getCXXScopeSpec().isInvalid())
4551     D.setInvalidType();
4552   else if (D.getCXXScopeSpec().isSet()) {
4553     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4554                                         UPPC_DeclarationQualifier))
4555       return nullptr;
4556 
4557     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4558     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4559     if (!DC || isa<EnumDecl>(DC)) {
4560       // If we could not compute the declaration context, it's because the
4561       // declaration context is dependent but does not refer to a class,
4562       // class template, or class template partial specialization. Complain
4563       // and return early, to avoid the coming semantic disaster.
4564       Diag(D.getIdentifierLoc(),
4565            diag::err_template_qualified_declarator_no_match)
4566         << D.getCXXScopeSpec().getScopeRep()
4567         << D.getCXXScopeSpec().getRange();
4568       return nullptr;
4569     }
4570     bool IsDependentContext = DC->isDependentContext();
4571 
4572     if (!IsDependentContext &&
4573         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4574       return nullptr;
4575 
4576     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4577       Diag(D.getIdentifierLoc(),
4578            diag::err_member_def_undefined_record)
4579         << Name << DC << D.getCXXScopeSpec().getRange();
4580       D.setInvalidType();
4581     } else if (!D.getDeclSpec().isFriendSpecified()) {
4582       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4583                                       Name, D.getIdentifierLoc())) {
4584         if (DC->isRecord())
4585           return nullptr;
4586 
4587         D.setInvalidType();
4588       }
4589     }
4590 
4591     // Check whether we need to rebuild the type of the given
4592     // declaration in the current instantiation.
4593     if (EnteringContext && IsDependentContext &&
4594         TemplateParamLists.size() != 0) {
4595       ContextRAII SavedContext(*this, DC);
4596       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4597         D.setInvalidType();
4598     }
4599   }
4600 
4601   if (DiagnoseClassNameShadow(DC, NameInfo))
4602     // If this is a typedef, we'll end up spewing multiple diagnostics.
4603     // Just return early; it's safer.
4604     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4605       return nullptr;
4606 
4607   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4608   QualType R = TInfo->getType();
4609 
4610   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4611                                       UPPC_DeclarationType))
4612     D.setInvalidType();
4613 
4614   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4615                         ForRedeclaration);
4616 
4617   // See if this is a redefinition of a variable in the same scope.
4618   if (!D.getCXXScopeSpec().isSet()) {
4619     bool IsLinkageLookup = false;
4620     bool CreateBuiltins = false;
4621 
4622     // If the declaration we're planning to build will be a function
4623     // or object with linkage, then look for another declaration with
4624     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4625     //
4626     // If the declaration we're planning to build will be declared with
4627     // external linkage in the translation unit, create any builtin with
4628     // the same name.
4629     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4630       /* Do nothing*/;
4631     else if (CurContext->isFunctionOrMethod() &&
4632              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4633               R->isFunctionType())) {
4634       IsLinkageLookup = true;
4635       CreateBuiltins =
4636           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4637     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4638                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4639       CreateBuiltins = true;
4640 
4641     if (IsLinkageLookup)
4642       Previous.clear(LookupRedeclarationWithLinkage);
4643 
4644     LookupName(Previous, S, CreateBuiltins);
4645   } else { // Something like "int foo::x;"
4646     LookupQualifiedName(Previous, DC);
4647 
4648     // C++ [dcl.meaning]p1:
4649     //   When the declarator-id is qualified, the declaration shall refer to a
4650     //  previously declared member of the class or namespace to which the
4651     //  qualifier refers (or, in the case of a namespace, of an element of the
4652     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4653     //  thereof; [...]
4654     //
4655     // Note that we already checked the context above, and that we do not have
4656     // enough information to make sure that Previous contains the declaration
4657     // we want to match. For example, given:
4658     //
4659     //   class X {
4660     //     void f();
4661     //     void f(float);
4662     //   };
4663     //
4664     //   void X::f(int) { } // ill-formed
4665     //
4666     // In this case, Previous will point to the overload set
4667     // containing the two f's declared in X, but neither of them
4668     // matches.
4669 
4670     // C++ [dcl.meaning]p1:
4671     //   [...] the member shall not merely have been introduced by a
4672     //   using-declaration in the scope of the class or namespace nominated by
4673     //   the nested-name-specifier of the declarator-id.
4674     RemoveUsingDecls(Previous);
4675   }
4676 
4677   if (Previous.isSingleResult() &&
4678       Previous.getFoundDecl()->isTemplateParameter()) {
4679     // Maybe we will complain about the shadowed template parameter.
4680     if (!D.isInvalidType())
4681       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4682                                       Previous.getFoundDecl());
4683 
4684     // Just pretend that we didn't see the previous declaration.
4685     Previous.clear();
4686   }
4687 
4688   // In C++, the previous declaration we find might be a tag type
4689   // (class or enum). In this case, the new declaration will hide the
4690   // tag type. Note that this does does not apply if we're declaring a
4691   // typedef (C++ [dcl.typedef]p4).
4692   if (Previous.isSingleTagDecl() &&
4693       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4694     Previous.clear();
4695 
4696   // Check that there are no default arguments other than in the parameters
4697   // of a function declaration (C++ only).
4698   if (getLangOpts().CPlusPlus)
4699     CheckExtraCXXDefaultArguments(D);
4700 
4701   NamedDecl *New;
4702 
4703   bool AddToScope = true;
4704   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4705     if (TemplateParamLists.size()) {
4706       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4707       return nullptr;
4708     }
4709 
4710     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4711   } else if (R->isFunctionType()) {
4712     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4713                                   TemplateParamLists,
4714                                   AddToScope);
4715   } else {
4716     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4717                                   AddToScope);
4718   }
4719 
4720   if (!New)
4721     return nullptr;
4722 
4723   // If this has an identifier and is not an invalid redeclaration or
4724   // function template specialization, add it to the scope stack.
4725   if (New->getDeclName() && AddToScope &&
4726        !(D.isRedeclaration() && New->isInvalidDecl())) {
4727     // Only make a locally-scoped extern declaration visible if it is the first
4728     // declaration of this entity. Qualified lookup for such an entity should
4729     // only find this declaration if there is no visible declaration of it.
4730     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4731     PushOnScopeChains(New, S, AddToContext);
4732     if (!AddToContext)
4733       CurContext->addHiddenDecl(New);
4734   }
4735 
4736   return New;
4737 }
4738 
4739 /// Helper method to turn variable array types into constant array
4740 /// types in certain situations which would otherwise be errors (for
4741 /// GCC compatibility).
4742 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4743                                                     ASTContext &Context,
4744                                                     bool &SizeIsNegative,
4745                                                     llvm::APSInt &Oversized) {
4746   // This method tries to turn a variable array into a constant
4747   // array even when the size isn't an ICE.  This is necessary
4748   // for compatibility with code that depends on gcc's buggy
4749   // constant expression folding, like struct {char x[(int)(char*)2];}
4750   SizeIsNegative = false;
4751   Oversized = 0;
4752 
4753   if (T->isDependentType())
4754     return QualType();
4755 
4756   QualifierCollector Qs;
4757   const Type *Ty = Qs.strip(T);
4758 
4759   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4760     QualType Pointee = PTy->getPointeeType();
4761     QualType FixedType =
4762         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4763                                             Oversized);
4764     if (FixedType.isNull()) return FixedType;
4765     FixedType = Context.getPointerType(FixedType);
4766     return Qs.apply(Context, FixedType);
4767   }
4768   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4769     QualType Inner = PTy->getInnerType();
4770     QualType FixedType =
4771         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4772                                             Oversized);
4773     if (FixedType.isNull()) return FixedType;
4774     FixedType = Context.getParenType(FixedType);
4775     return Qs.apply(Context, FixedType);
4776   }
4777 
4778   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
4779   if (!VLATy)
4780     return QualType();
4781   // FIXME: We should probably handle this case
4782   if (VLATy->getElementType()->isVariablyModifiedType())
4783     return QualType();
4784 
4785   llvm::APSInt Res;
4786   if (!VLATy->getSizeExpr() ||
4787       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
4788     return QualType();
4789 
4790   // Check whether the array size is negative.
4791   if (Res.isSigned() && Res.isNegative()) {
4792     SizeIsNegative = true;
4793     return QualType();
4794   }
4795 
4796   // Check whether the array is too large to be addressed.
4797   unsigned ActiveSizeBits
4798     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4799                                               Res);
4800   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4801     Oversized = Res;
4802     return QualType();
4803   }
4804 
4805   return Context.getConstantArrayType(VLATy->getElementType(),
4806                                       Res, ArrayType::Normal, 0);
4807 }
4808 
4809 static void
4810 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
4811   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4812     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4813     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4814                                       DstPTL.getPointeeLoc());
4815     DstPTL.setStarLoc(SrcPTL.getStarLoc());
4816     return;
4817   }
4818   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4819     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4820     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4821                                       DstPTL.getInnerLoc());
4822     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4823     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
4824     return;
4825   }
4826   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4827   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4828   TypeLoc SrcElemTL = SrcATL.getElementLoc();
4829   TypeLoc DstElemTL = DstATL.getElementLoc();
4830   DstElemTL.initializeFullCopy(SrcElemTL);
4831   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4832   DstATL.setSizeExpr(SrcATL.getSizeExpr());
4833   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
4834 }
4835 
4836 /// Helper method to turn variable array types into constant array
4837 /// types in certain situations which would otherwise be errors (for
4838 /// GCC compatibility).
4839 static TypeSourceInfo*
4840 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4841                                               ASTContext &Context,
4842                                               bool &SizeIsNegative,
4843                                               llvm::APSInt &Oversized) {
4844   QualType FixedTy
4845     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4846                                           SizeIsNegative, Oversized);
4847   if (FixedTy.isNull())
4848     return nullptr;
4849   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4850   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4851                                     FixedTInfo->getTypeLoc());
4852   return FixedTInfo;
4853 }
4854 
4855 /// \brief Register the given locally-scoped extern "C" declaration so
4856 /// that it can be found later for redeclarations. We include any extern "C"
4857 /// declaration that is not visible in the translation unit here, not just
4858 /// function-scope declarations.
4859 void
4860 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
4861   if (!getLangOpts().CPlusPlus &&
4862       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4863     // Don't need to track declarations in the TU in C.
4864     return;
4865 
4866   // Note that we have a locally-scoped external with this name.
4867   // FIXME: There can be multiple such declarations if they are functions marked
4868   // __attribute__((overloadable)) declared in function scope in C.
4869   LocallyScopedExternCDecls[ND->getDeclName()] = ND;
4870 }
4871 
4872 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
4873   if (ExternalSource) {
4874     // Load locally-scoped external decls from the external source.
4875     // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
4876     SmallVector<NamedDecl *, 4> Decls;
4877     ExternalSource->ReadLocallyScopedExternCDecls(Decls);
4878     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4879       llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4880         = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4881       if (Pos == LocallyScopedExternCDecls.end())
4882         LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
4883     }
4884   }
4885 
4886   NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
4887   return D ? D->getMostRecentDecl() : nullptr;
4888 }
4889 
4890 /// \brief Diagnose function specifiers on a declaration of an identifier that
4891 /// does not identify a function.
4892 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
4893   // FIXME: We should probably indicate the identifier in question to avoid
4894   // confusion for constructs like "inline int a(), b;"
4895   if (DS.isInlineSpecified())
4896     Diag(DS.getInlineSpecLoc(),
4897          diag::err_inline_non_function);
4898 
4899   if (DS.isVirtualSpecified())
4900     Diag(DS.getVirtualSpecLoc(),
4901          diag::err_virtual_non_function);
4902 
4903   if (DS.isExplicitSpecified())
4904     Diag(DS.getExplicitSpecLoc(),
4905          diag::err_explicit_non_function);
4906 
4907   if (DS.isNoreturnSpecified())
4908     Diag(DS.getNoreturnSpecLoc(),
4909          diag::err_noreturn_non_function);
4910 }
4911 
4912 NamedDecl*
4913 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4914                              TypeSourceInfo *TInfo, LookupResult &Previous) {
4915   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4916   if (D.getCXXScopeSpec().isSet()) {
4917     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4918       << D.getCXXScopeSpec().getRange();
4919     D.setInvalidType();
4920     // Pretend we didn't see the scope specifier.
4921     DC = CurContext;
4922     Previous.clear();
4923   }
4924 
4925   DiagnoseFunctionSpecifiers(D.getDeclSpec());
4926 
4927   if (D.getDeclSpec().isConstexprSpecified())
4928     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4929       << 1;
4930 
4931   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4932     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4933       << D.getName().getSourceRange();
4934     return nullptr;
4935   }
4936 
4937   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4938   if (!NewTD) return nullptr;
4939 
4940   // Handle attributes prior to checking for duplicates in MergeVarDecl
4941   ProcessDeclAttributes(S, NewTD, D);
4942 
4943   CheckTypedefForVariablyModifiedType(S, NewTD);
4944 
4945   bool Redeclaration = D.isRedeclaration();
4946   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4947   D.setRedeclaration(Redeclaration);
4948   return ND;
4949 }
4950 
4951 void
4952 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4953   // C99 6.7.7p2: If a typedef name specifies a variably modified type
4954   // then it shall have block scope.
4955   // Note that variably modified types must be fixed before merging the decl so
4956   // that redeclarations will match.
4957   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4958   QualType T = TInfo->getType();
4959   if (T->isVariablyModifiedType()) {
4960     getCurFunction()->setHasBranchProtectedScope();
4961 
4962     if (S->getFnParent() == nullptr) {
4963       bool SizeIsNegative;
4964       llvm::APSInt Oversized;
4965       TypeSourceInfo *FixedTInfo =
4966         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4967                                                       SizeIsNegative,
4968                                                       Oversized);
4969       if (FixedTInfo) {
4970         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4971         NewTD->setTypeSourceInfo(FixedTInfo);
4972       } else {
4973         if (SizeIsNegative)
4974           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4975         else if (T->isVariableArrayType())
4976           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4977         else if (Oversized.getBoolValue())
4978           Diag(NewTD->getLocation(), diag::err_array_too_large)
4979             << Oversized.toString(10);
4980         else
4981           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4982         NewTD->setInvalidDecl();
4983       }
4984     }
4985   }
4986 }
4987 
4988 
4989 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4990 /// declares a typedef-name, either using the 'typedef' type specifier or via
4991 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4992 NamedDecl*
4993 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4994                            LookupResult &Previous, bool &Redeclaration) {
4995   // Merge the decl with the existing one if appropriate. If the decl is
4996   // in an outer scope, it isn't the same thing.
4997   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4998                        /*AllowInlineNamespace*/false);
4999   filterNonConflictingPreviousTypedefDecls(Context, NewTD, Previous);
5000   if (!Previous.empty()) {
5001     Redeclaration = true;
5002     MergeTypedefNameDecl(NewTD, Previous);
5003   }
5004 
5005   // If this is the C FILE type, notify the AST context.
5006   if (IdentifierInfo *II = NewTD->getIdentifier())
5007     if (!NewTD->isInvalidDecl() &&
5008         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5009       if (II->isStr("FILE"))
5010         Context.setFILEDecl(NewTD);
5011       else if (II->isStr("jmp_buf"))
5012         Context.setjmp_bufDecl(NewTD);
5013       else if (II->isStr("sigjmp_buf"))
5014         Context.setsigjmp_bufDecl(NewTD);
5015       else if (II->isStr("ucontext_t"))
5016         Context.setucontext_tDecl(NewTD);
5017     }
5018 
5019   return NewTD;
5020 }
5021 
5022 /// \brief Determines whether the given declaration is an out-of-scope
5023 /// previous declaration.
5024 ///
5025 /// This routine should be invoked when name lookup has found a
5026 /// previous declaration (PrevDecl) that is not in the scope where a
5027 /// new declaration by the same name is being introduced. If the new
5028 /// declaration occurs in a local scope, previous declarations with
5029 /// linkage may still be considered previous declarations (C99
5030 /// 6.2.2p4-5, C++ [basic.link]p6).
5031 ///
5032 /// \param PrevDecl the previous declaration found by name
5033 /// lookup
5034 ///
5035 /// \param DC the context in which the new declaration is being
5036 /// declared.
5037 ///
5038 /// \returns true if PrevDecl is an out-of-scope previous declaration
5039 /// for a new delcaration with the same name.
5040 static bool
5041 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5042                                 ASTContext &Context) {
5043   if (!PrevDecl)
5044     return false;
5045 
5046   if (!PrevDecl->hasLinkage())
5047     return false;
5048 
5049   if (Context.getLangOpts().CPlusPlus) {
5050     // C++ [basic.link]p6:
5051     //   If there is a visible declaration of an entity with linkage
5052     //   having the same name and type, ignoring entities declared
5053     //   outside the innermost enclosing namespace scope, the block
5054     //   scope declaration declares that same entity and receives the
5055     //   linkage of the previous declaration.
5056     DeclContext *OuterContext = DC->getRedeclContext();
5057     if (!OuterContext->isFunctionOrMethod())
5058       // This rule only applies to block-scope declarations.
5059       return false;
5060 
5061     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5062     if (PrevOuterContext->isRecord())
5063       // We found a member function: ignore it.
5064       return false;
5065 
5066     // Find the innermost enclosing namespace for the new and
5067     // previous declarations.
5068     OuterContext = OuterContext->getEnclosingNamespaceContext();
5069     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5070 
5071     // The previous declaration is in a different namespace, so it
5072     // isn't the same function.
5073     if (!OuterContext->Equals(PrevOuterContext))
5074       return false;
5075   }
5076 
5077   return true;
5078 }
5079 
5080 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5081   CXXScopeSpec &SS = D.getCXXScopeSpec();
5082   if (!SS.isSet()) return;
5083   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5084 }
5085 
5086 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5087   QualType type = decl->getType();
5088   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5089   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5090     // Various kinds of declaration aren't allowed to be __autoreleasing.
5091     unsigned kind = -1U;
5092     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5093       if (var->hasAttr<BlocksAttr>())
5094         kind = 0; // __block
5095       else if (!var->hasLocalStorage())
5096         kind = 1; // global
5097     } else if (isa<ObjCIvarDecl>(decl)) {
5098       kind = 3; // ivar
5099     } else if (isa<FieldDecl>(decl)) {
5100       kind = 2; // field
5101     }
5102 
5103     if (kind != -1U) {
5104       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5105         << kind;
5106     }
5107   } else if (lifetime == Qualifiers::OCL_None) {
5108     // Try to infer lifetime.
5109     if (!type->isObjCLifetimeType())
5110       return false;
5111 
5112     lifetime = type->getObjCARCImplicitLifetime();
5113     type = Context.getLifetimeQualifiedType(type, lifetime);
5114     decl->setType(type);
5115   }
5116 
5117   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5118     // Thread-local variables cannot have lifetime.
5119     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5120         var->getTLSKind()) {
5121       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5122         << var->getType();
5123       return true;
5124     }
5125   }
5126 
5127   return false;
5128 }
5129 
5130 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5131   // Ensure that an auto decl is deduced otherwise the checks below might cache
5132   // the wrong linkage.
5133   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5134 
5135   // 'weak' only applies to declarations with external linkage.
5136   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5137     if (!ND.isExternallyVisible()) {
5138       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5139       ND.dropAttr<WeakAttr>();
5140     }
5141   }
5142   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5143     if (ND.isExternallyVisible()) {
5144       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5145       ND.dropAttr<WeakRefAttr>();
5146       ND.dropAttr<AliasAttr>();
5147     }
5148   }
5149 
5150   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5151     if (VD->hasInit()) {
5152       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5153         assert(VD->isThisDeclarationADefinition() &&
5154                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5155         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
5156         VD->dropAttr<AliasAttr>();
5157       }
5158     }
5159   }
5160 
5161   // 'selectany' only applies to externally visible varable declarations.
5162   // It does not apply to functions.
5163   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5164     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5165       S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
5166       ND.dropAttr<SelectAnyAttr>();
5167     }
5168   }
5169 
5170   // dll attributes require external linkage.
5171   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5172     if (!ND.isExternallyVisible()) {
5173       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5174         << &ND << Attr;
5175       ND.setInvalidDecl();
5176     }
5177   }
5178 }
5179 
5180 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5181                                            NamedDecl *NewDecl,
5182                                            bool IsSpecialization) {
5183   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5184     OldDecl = OldTD->getTemplatedDecl();
5185   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5186     NewDecl = NewTD->getTemplatedDecl();
5187 
5188   if (!OldDecl || !NewDecl)
5189     return;
5190 
5191   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5192   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5193   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5194   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5195 
5196   // dllimport and dllexport are inheritable attributes so we have to exclude
5197   // inherited attribute instances.
5198   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5199                     (NewExportAttr && !NewExportAttr->isInherited());
5200 
5201   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5202   // the only exception being explicit specializations.
5203   // Implicitly generated declarations are also excluded for now because there
5204   // is no other way to switch these to use dllimport or dllexport.
5205   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5206 
5207   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5208     // If the declaration hasn't been used yet, allow with a warning for
5209     // free functions and global variables.
5210     bool JustWarn = false;
5211     if (!OldDecl->isUsed() && !OldDecl->isCXXClassMember()) {
5212       auto *VD = dyn_cast<VarDecl>(OldDecl);
5213       if (VD && !VD->getDescribedVarTemplate())
5214         JustWarn = true;
5215       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5216       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5217         JustWarn = true;
5218     }
5219 
5220     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5221                                : diag::err_attribute_dll_redeclaration;
5222     S.Diag(NewDecl->getLocation(), DiagID)
5223         << NewDecl
5224         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5225     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5226     if (!JustWarn) {
5227       NewDecl->setInvalidDecl();
5228       return;
5229     }
5230   }
5231 
5232   // A redeclaration is not allowed to drop a dllimport attribute, the only
5233   // exceptions being inline function definitions, local extern declarations,
5234   // and qualified friend declarations.
5235   // NB: MSVC converts such a declaration to dllexport.
5236   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5237   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5238     // Ignore static data because out-of-line definitions are diagnosed
5239     // separately.
5240     IsStaticDataMember = VD->isStaticDataMember();
5241   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5242     IsInline = FD->isInlined();
5243     IsQualifiedFriend = FD->getQualifier() &&
5244                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5245   }
5246 
5247   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5248       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5249     S.Diag(NewDecl->getLocation(),
5250            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5251       << NewDecl << OldImportAttr;
5252     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5253     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5254     OldDecl->dropAttr<DLLImportAttr>();
5255     NewDecl->dropAttr<DLLImportAttr>();
5256   } else if (IsInline && OldImportAttr &&
5257              !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5258     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5259     OldDecl->dropAttr<DLLImportAttr>();
5260     NewDecl->dropAttr<DLLImportAttr>();
5261     S.Diag(NewDecl->getLocation(),
5262            diag::warn_dllimport_dropped_from_inline_function)
5263         << NewDecl << OldImportAttr;
5264   }
5265 }
5266 
5267 /// Given that we are within the definition of the given function,
5268 /// will that definition behave like C99's 'inline', where the
5269 /// definition is discarded except for optimization purposes?
5270 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5271   // Try to avoid calling GetGVALinkageForFunction.
5272 
5273   // All cases of this require the 'inline' keyword.
5274   if (!FD->isInlined()) return false;
5275 
5276   // This is only possible in C++ with the gnu_inline attribute.
5277   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5278     return false;
5279 
5280   // Okay, go ahead and call the relatively-more-expensive function.
5281 
5282 #ifndef NDEBUG
5283   // AST quite reasonably asserts that it's working on a function
5284   // definition.  We don't really have a way to tell it that we're
5285   // currently defining the function, so just lie to it in +Asserts
5286   // builds.  This is an awful hack.
5287   FD->setLazyBody(1);
5288 #endif
5289 
5290   bool isC99Inline =
5291       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5292 
5293 #ifndef NDEBUG
5294   FD->setLazyBody(0);
5295 #endif
5296 
5297   return isC99Inline;
5298 }
5299 
5300 /// Determine whether a variable is extern "C" prior to attaching
5301 /// an initializer. We can't just call isExternC() here, because that
5302 /// will also compute and cache whether the declaration is externally
5303 /// visible, which might change when we attach the initializer.
5304 ///
5305 /// This can only be used if the declaration is known to not be a
5306 /// redeclaration of an internal linkage declaration.
5307 ///
5308 /// For instance:
5309 ///
5310 ///   auto x = []{};
5311 ///
5312 /// Attaching the initializer here makes this declaration not externally
5313 /// visible, because its type has internal linkage.
5314 ///
5315 /// FIXME: This is a hack.
5316 template<typename T>
5317 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5318   if (S.getLangOpts().CPlusPlus) {
5319     // In C++, the overloadable attribute negates the effects of extern "C".
5320     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5321       return false;
5322   }
5323   return D->isExternC();
5324 }
5325 
5326 static bool shouldConsiderLinkage(const VarDecl *VD) {
5327   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5328   if (DC->isFunctionOrMethod())
5329     return VD->hasExternalStorage();
5330   if (DC->isFileContext())
5331     return true;
5332   if (DC->isRecord())
5333     return false;
5334   llvm_unreachable("Unexpected context");
5335 }
5336 
5337 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5338   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5339   if (DC->isFileContext() || DC->isFunctionOrMethod())
5340     return true;
5341   if (DC->isRecord())
5342     return false;
5343   llvm_unreachable("Unexpected context");
5344 }
5345 
5346 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5347                           AttributeList::Kind Kind) {
5348   for (const AttributeList *L = AttrList; L; L = L->getNext())
5349     if (L->getKind() == Kind)
5350       return true;
5351   return false;
5352 }
5353 
5354 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5355                           AttributeList::Kind Kind) {
5356   // Check decl attributes on the DeclSpec.
5357   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5358     return true;
5359 
5360   // Walk the declarator structure, checking decl attributes that were in a type
5361   // position to the decl itself.
5362   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5363     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5364       return true;
5365   }
5366 
5367   // Finally, check attributes on the decl itself.
5368   return hasParsedAttr(S, PD.getAttributes(), Kind);
5369 }
5370 
5371 /// Adjust the \c DeclContext for a function or variable that might be a
5372 /// function-local external declaration.
5373 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5374   if (!DC->isFunctionOrMethod())
5375     return false;
5376 
5377   // If this is a local extern function or variable declared within a function
5378   // template, don't add it into the enclosing namespace scope until it is
5379   // instantiated; it might have a dependent type right now.
5380   if (DC->isDependentContext())
5381     return true;
5382 
5383   // C++11 [basic.link]p7:
5384   //   When a block scope declaration of an entity with linkage is not found to
5385   //   refer to some other declaration, then that entity is a member of the
5386   //   innermost enclosing namespace.
5387   //
5388   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5389   // semantically-enclosing namespace, not a lexically-enclosing one.
5390   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5391     DC = DC->getParent();
5392   return true;
5393 }
5394 
5395 NamedDecl *
5396 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5397                               TypeSourceInfo *TInfo, LookupResult &Previous,
5398                               MultiTemplateParamsArg TemplateParamLists,
5399                               bool &AddToScope) {
5400   QualType R = TInfo->getType();
5401   DeclarationName Name = GetNameForDeclarator(D).getName();
5402 
5403   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5404   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5405 
5406   // dllimport globals without explicit storage class are treated as extern. We
5407   // have to change the storage class this early to get the right DeclContext.
5408   if (SC == SC_None && !DC->isRecord() &&
5409       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5410       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5411     SC = SC_Extern;
5412 
5413   DeclContext *OriginalDC = DC;
5414   bool IsLocalExternDecl = SC == SC_Extern &&
5415                            adjustContextForLocalExternDecl(DC);
5416 
5417   if (getLangOpts().OpenCL) {
5418     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5419     QualType NR = R;
5420     while (NR->isPointerType()) {
5421       if (NR->isFunctionPointerType()) {
5422         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5423         D.setInvalidType();
5424         break;
5425       }
5426       NR = NR->getPointeeType();
5427     }
5428 
5429     if (!getOpenCLOptions().cl_khr_fp16) {
5430       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5431       // half array type (unless the cl_khr_fp16 extension is enabled).
5432       if (Context.getBaseElementType(R)->isHalfType()) {
5433         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5434         D.setInvalidType();
5435       }
5436     }
5437   }
5438 
5439   if (SCSpec == DeclSpec::SCS_mutable) {
5440     // mutable can only appear on non-static class members, so it's always
5441     // an error here
5442     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5443     D.setInvalidType();
5444     SC = SC_None;
5445   }
5446 
5447   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5448       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5449                               D.getDeclSpec().getStorageClassSpecLoc())) {
5450     // In C++11, the 'register' storage class specifier is deprecated.
5451     // Suppress the warning in system macros, it's used in macros in some
5452     // popular C system headers, such as in glibc's htonl() macro.
5453     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5454          diag::warn_deprecated_register)
5455       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5456   }
5457 
5458   IdentifierInfo *II = Name.getAsIdentifierInfo();
5459   if (!II) {
5460     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5461       << Name;
5462     return nullptr;
5463   }
5464 
5465   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5466 
5467   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5468     // C99 6.9p2: The storage-class specifiers auto and register shall not
5469     // appear in the declaration specifiers in an external declaration.
5470     // Global Register+Asm is a GNU extension we support.
5471     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5472       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5473       D.setInvalidType();
5474     }
5475   }
5476 
5477   if (getLangOpts().OpenCL) {
5478     // Set up the special work-group-local storage class for variables in the
5479     // OpenCL __local address space.
5480     if (R.getAddressSpace() == LangAS::opencl_local) {
5481       SC = SC_OpenCLWorkGroupLocal;
5482     }
5483 
5484     // OpenCL v1.2 s6.9.b p4:
5485     // The sampler type cannot be used with the __local and __global address
5486     // space qualifiers.
5487     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5488       R.getAddressSpace() == LangAS::opencl_global)) {
5489       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5490     }
5491 
5492     // OpenCL 1.2 spec, p6.9 r:
5493     // The event type cannot be used to declare a program scope variable.
5494     // The event type cannot be used with the __local, __constant and __global
5495     // address space qualifiers.
5496     if (R->isEventT()) {
5497       if (S->getParent() == nullptr) {
5498         Diag(D.getLocStart(), diag::err_event_t_global_var);
5499         D.setInvalidType();
5500       }
5501 
5502       if (R.getAddressSpace()) {
5503         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5504         D.setInvalidType();
5505       }
5506     }
5507   }
5508 
5509   bool IsExplicitSpecialization = false;
5510   bool IsVariableTemplateSpecialization = false;
5511   bool IsPartialSpecialization = false;
5512   bool IsVariableTemplate = false;
5513   VarDecl *NewVD = nullptr;
5514   VarTemplateDecl *NewTemplate = nullptr;
5515   TemplateParameterList *TemplateParams = nullptr;
5516   if (!getLangOpts().CPlusPlus) {
5517     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5518                             D.getIdentifierLoc(), II,
5519                             R, TInfo, SC);
5520 
5521     if (D.isInvalidType())
5522       NewVD->setInvalidDecl();
5523   } else {
5524     bool Invalid = false;
5525 
5526     if (DC->isRecord() && !CurContext->isRecord()) {
5527       // This is an out-of-line definition of a static data member.
5528       switch (SC) {
5529       case SC_None:
5530         break;
5531       case SC_Static:
5532         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5533              diag::err_static_out_of_line)
5534           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5535         break;
5536       case SC_Auto:
5537       case SC_Register:
5538       case SC_Extern:
5539         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5540         // to names of variables declared in a block or to function parameters.
5541         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5542         // of class members
5543 
5544         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5545              diag::err_storage_class_for_static_member)
5546           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5547         break;
5548       case SC_PrivateExtern:
5549         llvm_unreachable("C storage class in c++!");
5550       case SC_OpenCLWorkGroupLocal:
5551         llvm_unreachable("OpenCL storage class in c++!");
5552       }
5553     }
5554 
5555     if (SC == SC_Static && CurContext->isRecord()) {
5556       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5557         if (RD->isLocalClass())
5558           Diag(D.getIdentifierLoc(),
5559                diag::err_static_data_member_not_allowed_in_local_class)
5560             << Name << RD->getDeclName();
5561 
5562         // C++98 [class.union]p1: If a union contains a static data member,
5563         // the program is ill-formed. C++11 drops this restriction.
5564         if (RD->isUnion())
5565           Diag(D.getIdentifierLoc(),
5566                getLangOpts().CPlusPlus11
5567                  ? diag::warn_cxx98_compat_static_data_member_in_union
5568                  : diag::ext_static_data_member_in_union) << Name;
5569         // We conservatively disallow static data members in anonymous structs.
5570         else if (!RD->getDeclName())
5571           Diag(D.getIdentifierLoc(),
5572                diag::err_static_data_member_not_allowed_in_anon_struct)
5573             << Name << RD->isUnion();
5574       }
5575     }
5576 
5577     // Match up the template parameter lists with the scope specifier, then
5578     // determine whether we have a template or a template specialization.
5579     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5580         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5581         D.getCXXScopeSpec(),
5582         D.getName().getKind() == UnqualifiedId::IK_TemplateId
5583             ? D.getName().TemplateId
5584             : nullptr,
5585         TemplateParamLists,
5586         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5587 
5588     if (TemplateParams) {
5589       if (!TemplateParams->size() &&
5590           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5591         // There is an extraneous 'template<>' for this variable. Complain
5592         // about it, but allow the declaration of the variable.
5593         Diag(TemplateParams->getTemplateLoc(),
5594              diag::err_template_variable_noparams)
5595           << II
5596           << SourceRange(TemplateParams->getTemplateLoc(),
5597                          TemplateParams->getRAngleLoc());
5598         TemplateParams = nullptr;
5599       } else {
5600         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5601           // This is an explicit specialization or a partial specialization.
5602           // FIXME: Check that we can declare a specialization here.
5603           IsVariableTemplateSpecialization = true;
5604           IsPartialSpecialization = TemplateParams->size() > 0;
5605         } else { // if (TemplateParams->size() > 0)
5606           // This is a template declaration.
5607           IsVariableTemplate = true;
5608 
5609           // Check that we can declare a template here.
5610           if (CheckTemplateDeclScope(S, TemplateParams))
5611             return nullptr;
5612 
5613           // Only C++1y supports variable templates (N3651).
5614           Diag(D.getIdentifierLoc(),
5615                getLangOpts().CPlusPlus14
5616                    ? diag::warn_cxx11_compat_variable_template
5617                    : diag::ext_variable_template);
5618         }
5619       }
5620     } else {
5621       assert(
5622           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5623           "should have a 'template<>' for this decl");
5624     }
5625 
5626     if (IsVariableTemplateSpecialization) {
5627       SourceLocation TemplateKWLoc =
5628           TemplateParamLists.size() > 0
5629               ? TemplateParamLists[0]->getTemplateLoc()
5630               : SourceLocation();
5631       DeclResult Res = ActOnVarTemplateSpecialization(
5632           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5633           IsPartialSpecialization);
5634       if (Res.isInvalid())
5635         return nullptr;
5636       NewVD = cast<VarDecl>(Res.get());
5637       AddToScope = false;
5638     } else
5639       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5640                               D.getIdentifierLoc(), II, R, TInfo, SC);
5641 
5642     // If this is supposed to be a variable template, create it as such.
5643     if (IsVariableTemplate) {
5644       NewTemplate =
5645           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5646                                   TemplateParams, NewVD);
5647       NewVD->setDescribedVarTemplate(NewTemplate);
5648     }
5649 
5650     // If this decl has an auto type in need of deduction, make a note of the
5651     // Decl so we can diagnose uses of it in its own initializer.
5652     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5653       ParsingInitForAutoVars.insert(NewVD);
5654 
5655     if (D.isInvalidType() || Invalid) {
5656       NewVD->setInvalidDecl();
5657       if (NewTemplate)
5658         NewTemplate->setInvalidDecl();
5659     }
5660 
5661     SetNestedNameSpecifier(NewVD, D);
5662 
5663     // If we have any template parameter lists that don't directly belong to
5664     // the variable (matching the scope specifier), store them.
5665     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5666     if (TemplateParamLists.size() > VDTemplateParamLists)
5667       NewVD->setTemplateParameterListsInfo(
5668           Context, TemplateParamLists.size() - VDTemplateParamLists,
5669           TemplateParamLists.data());
5670 
5671     if (D.getDeclSpec().isConstexprSpecified())
5672       NewVD->setConstexpr(true);
5673   }
5674 
5675   // Set the lexical context. If the declarator has a C++ scope specifier, the
5676   // lexical context will be different from the semantic context.
5677   NewVD->setLexicalDeclContext(CurContext);
5678   if (NewTemplate)
5679     NewTemplate->setLexicalDeclContext(CurContext);
5680 
5681   if (IsLocalExternDecl)
5682     NewVD->setLocalExternDecl();
5683 
5684   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5685     // C++11 [dcl.stc]p4:
5686     //   When thread_local is applied to a variable of block scope the
5687     //   storage-class-specifier static is implied if it does not appear
5688     //   explicitly.
5689     // Core issue: 'static' is not implied if the variable is declared
5690     //   'extern'.
5691     if (NewVD->hasLocalStorage() &&
5692         (SCSpec != DeclSpec::SCS_unspecified ||
5693          TSCS != DeclSpec::TSCS_thread_local ||
5694          !DC->isFunctionOrMethod()))
5695       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5696            diag::err_thread_non_global)
5697         << DeclSpec::getSpecifierName(TSCS);
5698     else if (!Context.getTargetInfo().isTLSSupported())
5699       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5700            diag::err_thread_unsupported);
5701     else
5702       NewVD->setTSCSpec(TSCS);
5703   }
5704 
5705   // C99 6.7.4p3
5706   //   An inline definition of a function with external linkage shall
5707   //   not contain a definition of a modifiable object with static or
5708   //   thread storage duration...
5709   // We only apply this when the function is required to be defined
5710   // elsewhere, i.e. when the function is not 'extern inline'.  Note
5711   // that a local variable with thread storage duration still has to
5712   // be marked 'static'.  Also note that it's possible to get these
5713   // semantics in C++ using __attribute__((gnu_inline)).
5714   if (SC == SC_Static && S->getFnParent() != nullptr &&
5715       !NewVD->getType().isConstQualified()) {
5716     FunctionDecl *CurFD = getCurFunctionDecl();
5717     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5718       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5719            diag::warn_static_local_in_extern_inline);
5720       MaybeSuggestAddingStaticToDecl(CurFD);
5721     }
5722   }
5723 
5724   if (D.getDeclSpec().isModulePrivateSpecified()) {
5725     if (IsVariableTemplateSpecialization)
5726       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5727           << (IsPartialSpecialization ? 1 : 0)
5728           << FixItHint::CreateRemoval(
5729                  D.getDeclSpec().getModulePrivateSpecLoc());
5730     else if (IsExplicitSpecialization)
5731       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5732         << 2
5733         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5734     else if (NewVD->hasLocalStorage())
5735       Diag(NewVD->getLocation(), diag::err_module_private_local)
5736         << 0 << NewVD->getDeclName()
5737         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5738         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5739     else {
5740       NewVD->setModulePrivate();
5741       if (NewTemplate)
5742         NewTemplate->setModulePrivate();
5743     }
5744   }
5745 
5746   // Handle attributes prior to checking for duplicates in MergeVarDecl
5747   ProcessDeclAttributes(S, NewVD, D);
5748 
5749   if (getLangOpts().CUDA) {
5750     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5751     // storage [duration]."
5752     if (SC == SC_None && S->getFnParent() != nullptr &&
5753         (NewVD->hasAttr<CUDASharedAttr>() ||
5754          NewVD->hasAttr<CUDAConstantAttr>())) {
5755       NewVD->setStorageClass(SC_Static);
5756     }
5757   }
5758 
5759   // Ensure that dllimport globals without explicit storage class are treated as
5760   // extern. The storage class is set above using parsed attributes. Now we can
5761   // check the VarDecl itself.
5762   assert(!NewVD->hasAttr<DLLImportAttr>() ||
5763          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
5764          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
5765 
5766   // In auto-retain/release, infer strong retension for variables of
5767   // retainable type.
5768   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5769     NewVD->setInvalidDecl();
5770 
5771   // Handle GNU asm-label extension (encoded as an attribute).
5772   if (Expr *E = (Expr*)D.getAsmLabel()) {
5773     // The parser guarantees this is a string.
5774     StringLiteral *SE = cast<StringLiteral>(E);
5775     StringRef Label = SE->getString();
5776     if (S->getFnParent() != nullptr) {
5777       switch (SC) {
5778       case SC_None:
5779       case SC_Auto:
5780         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5781         break;
5782       case SC_Register:
5783         // Local Named register
5784         if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5785           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5786         break;
5787       case SC_Static:
5788       case SC_Extern:
5789       case SC_PrivateExtern:
5790       case SC_OpenCLWorkGroupLocal:
5791         break;
5792       }
5793     } else if (SC == SC_Register) {
5794       // Global Named register
5795       if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5796         Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5797       if (!R->isIntegralType(Context) && !R->isPointerType()) {
5798         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
5799         NewVD->setInvalidDecl(true);
5800       }
5801     }
5802 
5803     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
5804                                                 Context, Label, 0));
5805   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5806     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5807       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5808     if (I != ExtnameUndeclaredIdentifiers.end()) {
5809       NewVD->addAttr(I->second);
5810       ExtnameUndeclaredIdentifiers.erase(I);
5811     }
5812   }
5813 
5814   // Diagnose shadowed variables before filtering for scope.
5815   if (D.getCXXScopeSpec().isEmpty())
5816     CheckShadow(S, NewVD, Previous);
5817 
5818   // Don't consider existing declarations that are in a different
5819   // scope and are out-of-semantic-context declarations (if the new
5820   // declaration has linkage).
5821   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5822                        D.getCXXScopeSpec().isNotEmpty() ||
5823                        IsExplicitSpecialization ||
5824                        IsVariableTemplateSpecialization);
5825 
5826   // Check whether the previous declaration is in the same block scope. This
5827   // affects whether we merge types with it, per C++11 [dcl.array]p3.
5828   if (getLangOpts().CPlusPlus &&
5829       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5830     NewVD->setPreviousDeclInSameBlockScope(
5831         Previous.isSingleResult() && !Previous.isShadowed() &&
5832         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
5833 
5834   if (!getLangOpts().CPlusPlus) {
5835     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5836   } else {
5837     // If this is an explicit specialization of a static data member, check it.
5838     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5839         CheckMemberSpecialization(NewVD, Previous))
5840       NewVD->setInvalidDecl();
5841 
5842     // Merge the decl with the existing one if appropriate.
5843     if (!Previous.empty()) {
5844       if (Previous.isSingleResult() &&
5845           isa<FieldDecl>(Previous.getFoundDecl()) &&
5846           D.getCXXScopeSpec().isSet()) {
5847         // The user tried to define a non-static data member
5848         // out-of-line (C++ [dcl.meaning]p1).
5849         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5850           << D.getCXXScopeSpec().getRange();
5851         Previous.clear();
5852         NewVD->setInvalidDecl();
5853       }
5854     } else if (D.getCXXScopeSpec().isSet()) {
5855       // No previous declaration in the qualifying scope.
5856       Diag(D.getIdentifierLoc(), diag::err_no_member)
5857         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
5858         << D.getCXXScopeSpec().getRange();
5859       NewVD->setInvalidDecl();
5860     }
5861 
5862     if (!IsVariableTemplateSpecialization)
5863       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5864 
5865     if (NewTemplate) {
5866       VarTemplateDecl *PrevVarTemplate =
5867           NewVD->getPreviousDecl()
5868               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5869               : nullptr;
5870 
5871       // Check the template parameter list of this declaration, possibly
5872       // merging in the template parameter list from the previous variable
5873       // template declaration.
5874       if (CheckTemplateParameterList(
5875               TemplateParams,
5876               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5877                               : nullptr,
5878               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5879                DC->isDependentContext())
5880                   ? TPC_ClassTemplateMember
5881                   : TPC_VarTemplate))
5882         NewVD->setInvalidDecl();
5883 
5884       // If we are providing an explicit specialization of a static variable
5885       // template, make a note of that.
5886       if (PrevVarTemplate &&
5887           PrevVarTemplate->getInstantiatedFromMemberTemplate())
5888         PrevVarTemplate->setMemberSpecialization();
5889     }
5890   }
5891 
5892   ProcessPragmaWeak(S, NewVD);
5893 
5894   // If this is the first declaration of an extern C variable, update
5895   // the map of such variables.
5896   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
5897       isIncompleteDeclExternC(*this, NewVD))
5898     RegisterLocallyScopedExternCDecl(NewVD, S);
5899 
5900   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5901     Decl *ManglingContextDecl;
5902     if (MangleNumberingContext *MCtx =
5903             getCurrentMangleNumberContext(NewVD->getDeclContext(),
5904                                           ManglingContextDecl)) {
5905       Context.setManglingNumber(
5906           NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
5907       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5908     }
5909   }
5910 
5911   if (D.isRedeclaration() && !Previous.empty()) {
5912     checkDLLAttributeRedeclaration(
5913         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
5914         IsExplicitSpecialization);
5915   }
5916 
5917   if (NewTemplate) {
5918     if (NewVD->isInvalidDecl())
5919       NewTemplate->setInvalidDecl();
5920     ActOnDocumentableDecl(NewTemplate);
5921     return NewTemplate;
5922   }
5923 
5924   return NewVD;
5925 }
5926 
5927 /// \brief Diagnose variable or built-in function shadowing.  Implements
5928 /// -Wshadow.
5929 ///
5930 /// This method is called whenever a VarDecl is added to a "useful"
5931 /// scope.
5932 ///
5933 /// \param S the scope in which the shadowing name is being declared
5934 /// \param R the lookup of the name
5935 ///
5936 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
5937   // Return if warning is ignored.
5938   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
5939     return;
5940 
5941   // Don't diagnose declarations at file scope.
5942   if (D->hasGlobalStorage())
5943     return;
5944 
5945   DeclContext *NewDC = D->getDeclContext();
5946 
5947   // Only diagnose if we're shadowing an unambiguous field or variable.
5948   if (R.getResultKind() != LookupResult::Found)
5949     return;
5950 
5951   NamedDecl* ShadowedDecl = R.getFoundDecl();
5952   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5953     return;
5954 
5955   // Fields are not shadowed by variables in C++ static methods.
5956   if (isa<FieldDecl>(ShadowedDecl))
5957     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5958       if (MD->isStatic())
5959         return;
5960 
5961   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5962     if (shadowedVar->isExternC()) {
5963       // For shadowing external vars, make sure that we point to the global
5964       // declaration, not a locally scoped extern declaration.
5965       for (auto I : shadowedVar->redecls())
5966         if (I->isFileVarDecl()) {
5967           ShadowedDecl = I;
5968           break;
5969         }
5970     }
5971 
5972   DeclContext *OldDC = ShadowedDecl->getDeclContext();
5973 
5974   // Only warn about certain kinds of shadowing for class members.
5975   if (NewDC && NewDC->isRecord()) {
5976     // In particular, don't warn about shadowing non-class members.
5977     if (!OldDC->isRecord())
5978       return;
5979 
5980     // TODO: should we warn about static data members shadowing
5981     // static data members from base classes?
5982 
5983     // TODO: don't diagnose for inaccessible shadowed members.
5984     // This is hard to do perfectly because we might friend the
5985     // shadowing context, but that's just a false negative.
5986   }
5987 
5988   // Determine what kind of declaration we're shadowing.
5989   unsigned Kind;
5990   if (isa<RecordDecl>(OldDC)) {
5991     if (isa<FieldDecl>(ShadowedDecl))
5992       Kind = 3; // field
5993     else
5994       Kind = 2; // static data member
5995   } else if (OldDC->isFileContext())
5996     Kind = 1; // global
5997   else
5998     Kind = 0; // local
5999 
6000   DeclarationName Name = R.getLookupName();
6001 
6002   // Emit warning and note.
6003   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6004     return;
6005   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6006   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6007 }
6008 
6009 /// \brief Check -Wshadow without the advantage of a previous lookup.
6010 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6011   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6012     return;
6013 
6014   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6015                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6016   LookupName(R, S);
6017   CheckShadow(S, D, R);
6018 }
6019 
6020 /// Check for conflict between this global or extern "C" declaration and
6021 /// previous global or extern "C" declarations. This is only used in C++.
6022 template<typename T>
6023 static bool checkGlobalOrExternCConflict(
6024     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6025   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6026   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6027 
6028   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6029     // The common case: this global doesn't conflict with any extern "C"
6030     // declaration.
6031     return false;
6032   }
6033 
6034   if (Prev) {
6035     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6036       // Both the old and new declarations have C language linkage. This is a
6037       // redeclaration.
6038       Previous.clear();
6039       Previous.addDecl(Prev);
6040       return true;
6041     }
6042 
6043     // This is a global, non-extern "C" declaration, and there is a previous
6044     // non-global extern "C" declaration. Diagnose if this is a variable
6045     // declaration.
6046     if (!isa<VarDecl>(ND))
6047       return false;
6048   } else {
6049     // The declaration is extern "C". Check for any declaration in the
6050     // translation unit which might conflict.
6051     if (IsGlobal) {
6052       // We have already performed the lookup into the translation unit.
6053       IsGlobal = false;
6054       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6055            I != E; ++I) {
6056         if (isa<VarDecl>(*I)) {
6057           Prev = *I;
6058           break;
6059         }
6060       }
6061     } else {
6062       DeclContext::lookup_result R =
6063           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6064       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6065            I != E; ++I) {
6066         if (isa<VarDecl>(*I)) {
6067           Prev = *I;
6068           break;
6069         }
6070         // FIXME: If we have any other entity with this name in global scope,
6071         // the declaration is ill-formed, but that is a defect: it breaks the
6072         // 'stat' hack, for instance. Only variables can have mangled name
6073         // clashes with extern "C" declarations, so only they deserve a
6074         // diagnostic.
6075       }
6076     }
6077 
6078     if (!Prev)
6079       return false;
6080   }
6081 
6082   // Use the first declaration's location to ensure we point at something which
6083   // is lexically inside an extern "C" linkage-spec.
6084   assert(Prev && "should have found a previous declaration to diagnose");
6085   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6086     Prev = FD->getFirstDecl();
6087   else
6088     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6089 
6090   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6091     << IsGlobal << ND;
6092   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6093     << IsGlobal;
6094   return false;
6095 }
6096 
6097 /// Apply special rules for handling extern "C" declarations. Returns \c true
6098 /// if we have found that this is a redeclaration of some prior entity.
6099 ///
6100 /// Per C++ [dcl.link]p6:
6101 ///   Two declarations [for a function or variable] with C language linkage
6102 ///   with the same name that appear in different scopes refer to the same
6103 ///   [entity]. An entity with C language linkage shall not be declared with
6104 ///   the same name as an entity in global scope.
6105 template<typename T>
6106 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6107                                                   LookupResult &Previous) {
6108   if (!S.getLangOpts().CPlusPlus) {
6109     // In C, when declaring a global variable, look for a corresponding 'extern'
6110     // variable declared in function scope. We don't need this in C++, because
6111     // we find local extern decls in the surrounding file-scope DeclContext.
6112     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6113       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6114         Previous.clear();
6115         Previous.addDecl(Prev);
6116         return true;
6117       }
6118     }
6119     return false;
6120   }
6121 
6122   // A declaration in the translation unit can conflict with an extern "C"
6123   // declaration.
6124   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6125     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6126 
6127   // An extern "C" declaration can conflict with a declaration in the
6128   // translation unit or can be a redeclaration of an extern "C" declaration
6129   // in another scope.
6130   if (isIncompleteDeclExternC(S,ND))
6131     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6132 
6133   // Neither global nor extern "C": nothing to do.
6134   return false;
6135 }
6136 
6137 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6138   // If the decl is already known invalid, don't check it.
6139   if (NewVD->isInvalidDecl())
6140     return;
6141 
6142   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6143   QualType T = TInfo->getType();
6144 
6145   // Defer checking an 'auto' type until its initializer is attached.
6146   if (T->isUndeducedType())
6147     return;
6148 
6149   if (NewVD->hasAttrs())
6150     CheckAlignasUnderalignment(NewVD);
6151 
6152   if (T->isObjCObjectType()) {
6153     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6154       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6155     T = Context.getObjCObjectPointerType(T);
6156     NewVD->setType(T);
6157   }
6158 
6159   // Emit an error if an address space was applied to decl with local storage.
6160   // This includes arrays of objects with address space qualifiers, but not
6161   // automatic variables that point to other address spaces.
6162   // ISO/IEC TR 18037 S5.1.2
6163   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6164     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6165     NewVD->setInvalidDecl();
6166     return;
6167   }
6168 
6169   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6170   // __constant address space.
6171   if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
6172       && T.getAddressSpace() != LangAS::opencl_constant
6173       && !T->isSamplerT()){
6174     Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
6175     NewVD->setInvalidDecl();
6176     return;
6177   }
6178 
6179   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6180   // scope.
6181   if ((getLangOpts().OpenCLVersion >= 120)
6182       && NewVD->isStaticLocal()) {
6183     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6184     NewVD->setInvalidDecl();
6185     return;
6186   }
6187 
6188   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6189       && !NewVD->hasAttr<BlocksAttr>()) {
6190     if (getLangOpts().getGC() != LangOptions::NonGC)
6191       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6192     else {
6193       assert(!getLangOpts().ObjCAutoRefCount);
6194       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6195     }
6196   }
6197 
6198   bool isVM = T->isVariablyModifiedType();
6199   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6200       NewVD->hasAttr<BlocksAttr>())
6201     getCurFunction()->setHasBranchProtectedScope();
6202 
6203   if ((isVM && NewVD->hasLinkage()) ||
6204       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6205     bool SizeIsNegative;
6206     llvm::APSInt Oversized;
6207     TypeSourceInfo *FixedTInfo =
6208       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6209                                                     SizeIsNegative, Oversized);
6210     if (!FixedTInfo && T->isVariableArrayType()) {
6211       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6212       // FIXME: This won't give the correct result for
6213       // int a[10][n];
6214       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6215 
6216       if (NewVD->isFileVarDecl())
6217         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6218         << SizeRange;
6219       else if (NewVD->isStaticLocal())
6220         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6221         << SizeRange;
6222       else
6223         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6224         << SizeRange;
6225       NewVD->setInvalidDecl();
6226       return;
6227     }
6228 
6229     if (!FixedTInfo) {
6230       if (NewVD->isFileVarDecl())
6231         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6232       else
6233         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6234       NewVD->setInvalidDecl();
6235       return;
6236     }
6237 
6238     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6239     NewVD->setType(FixedTInfo->getType());
6240     NewVD->setTypeSourceInfo(FixedTInfo);
6241   }
6242 
6243   if (T->isVoidType()) {
6244     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6245     //                    of objects and functions.
6246     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6247       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6248         << T;
6249       NewVD->setInvalidDecl();
6250       return;
6251     }
6252   }
6253 
6254   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6255     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6256     NewVD->setInvalidDecl();
6257     return;
6258   }
6259 
6260   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6261     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6262     NewVD->setInvalidDecl();
6263     return;
6264   }
6265 
6266   if (NewVD->isConstexpr() && !T->isDependentType() &&
6267       RequireLiteralType(NewVD->getLocation(), T,
6268                          diag::err_constexpr_var_non_literal)) {
6269     NewVD->setInvalidDecl();
6270     return;
6271   }
6272 }
6273 
6274 /// \brief Perform semantic checking on a newly-created variable
6275 /// declaration.
6276 ///
6277 /// This routine performs all of the type-checking required for a
6278 /// variable declaration once it has been built. It is used both to
6279 /// check variables after they have been parsed and their declarators
6280 /// have been translated into a declaration, and to check variables
6281 /// that have been instantiated from a template.
6282 ///
6283 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6284 ///
6285 /// Returns true if the variable declaration is a redeclaration.
6286 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6287   CheckVariableDeclarationType(NewVD);
6288 
6289   // If the decl is already known invalid, don't check it.
6290   if (NewVD->isInvalidDecl())
6291     return false;
6292 
6293   // If we did not find anything by this name, look for a non-visible
6294   // extern "C" declaration with the same name.
6295   if (Previous.empty() &&
6296       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6297     Previous.setShadowed();
6298 
6299   // Filter out any non-conflicting previous declarations.
6300   filterNonConflictingPreviousDecls(Context, NewVD, Previous);
6301 
6302   if (!Previous.empty()) {
6303     MergeVarDecl(NewVD, Previous);
6304     return true;
6305   }
6306   return false;
6307 }
6308 
6309 /// \brief Data used with FindOverriddenMethod
6310 struct FindOverriddenMethodData {
6311   Sema *S;
6312   CXXMethodDecl *Method;
6313 };
6314 
6315 /// \brief Member lookup function that determines whether a given C++
6316 /// method overrides a method in a base class, to be used with
6317 /// CXXRecordDecl::lookupInBases().
6318 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
6319                                  CXXBasePath &Path,
6320                                  void *UserData) {
6321   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6322 
6323   FindOverriddenMethodData *Data
6324     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
6325 
6326   DeclarationName Name = Data->Method->getDeclName();
6327 
6328   // FIXME: Do we care about other names here too?
6329   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6330     // We really want to find the base class destructor here.
6331     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
6332     CanQualType CT = Data->S->Context.getCanonicalType(T);
6333 
6334     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
6335   }
6336 
6337   for (Path.Decls = BaseRecord->lookup(Name);
6338        !Path.Decls.empty();
6339        Path.Decls = Path.Decls.slice(1)) {
6340     NamedDecl *D = Path.Decls.front();
6341     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6342       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
6343         return true;
6344     }
6345   }
6346 
6347   return false;
6348 }
6349 
6350 namespace {
6351   enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6352 }
6353 /// \brief Report an error regarding overriding, along with any relevant
6354 /// overriden methods.
6355 ///
6356 /// \param DiagID the primary error to report.
6357 /// \param MD the overriding method.
6358 /// \param OEK which overrides to include as notes.
6359 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6360                             OverrideErrorKind OEK = OEK_All) {
6361   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6362   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6363                                       E = MD->end_overridden_methods();
6364        I != E; ++I) {
6365     // This check (& the OEK parameter) could be replaced by a predicate, but
6366     // without lambdas that would be overkill. This is still nicer than writing
6367     // out the diag loop 3 times.
6368     if ((OEK == OEK_All) ||
6369         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6370         (OEK == OEK_Deleted && (*I)->isDeleted()))
6371       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6372   }
6373 }
6374 
6375 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6376 /// and if so, check that it's a valid override and remember it.
6377 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6378   // Look for methods in base classes that this method might override.
6379   CXXBasePaths Paths;
6380   FindOverriddenMethodData Data;
6381   Data.Method = MD;
6382   Data.S = this;
6383   bool hasDeletedOverridenMethods = false;
6384   bool hasNonDeletedOverridenMethods = false;
6385   bool AddedAny = false;
6386   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
6387     for (auto *I : Paths.found_decls()) {
6388       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6389         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6390         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6391             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6392             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6393             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6394           hasDeletedOverridenMethods |= OldMD->isDeleted();
6395           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6396           AddedAny = true;
6397         }
6398       }
6399     }
6400   }
6401 
6402   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6403     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6404   }
6405   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6406     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6407   }
6408 
6409   return AddedAny;
6410 }
6411 
6412 namespace {
6413   // Struct for holding all of the extra arguments needed by
6414   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6415   struct ActOnFDArgs {
6416     Scope *S;
6417     Declarator &D;
6418     MultiTemplateParamsArg TemplateParamLists;
6419     bool AddToScope;
6420   };
6421 }
6422 
6423 namespace {
6424 
6425 // Callback to only accept typo corrections that have a non-zero edit distance.
6426 // Also only accept corrections that have the same parent decl.
6427 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6428  public:
6429   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6430                             CXXRecordDecl *Parent)
6431       : Context(Context), OriginalFD(TypoFD),
6432         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6433 
6434   bool ValidateCandidate(const TypoCorrection &candidate) override {
6435     if (candidate.getEditDistance() == 0)
6436       return false;
6437 
6438     SmallVector<unsigned, 1> MismatchedParams;
6439     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6440                                           CDeclEnd = candidate.end();
6441          CDecl != CDeclEnd; ++CDecl) {
6442       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6443 
6444       if (FD && !FD->hasBody() &&
6445           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6446         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6447           CXXRecordDecl *Parent = MD->getParent();
6448           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6449             return true;
6450         } else if (!ExpectedParent) {
6451           return true;
6452         }
6453       }
6454     }
6455 
6456     return false;
6457   }
6458 
6459  private:
6460   ASTContext &Context;
6461   FunctionDecl *OriginalFD;
6462   CXXRecordDecl *ExpectedParent;
6463 };
6464 
6465 }
6466 
6467 /// \brief Generate diagnostics for an invalid function redeclaration.
6468 ///
6469 /// This routine handles generating the diagnostic messages for an invalid
6470 /// function redeclaration, including finding possible similar declarations
6471 /// or performing typo correction if there are no previous declarations with
6472 /// the same name.
6473 ///
6474 /// Returns a NamedDecl iff typo correction was performed and substituting in
6475 /// the new declaration name does not cause new errors.
6476 static NamedDecl *DiagnoseInvalidRedeclaration(
6477     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6478     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6479   DeclarationName Name = NewFD->getDeclName();
6480   DeclContext *NewDC = NewFD->getDeclContext();
6481   SmallVector<unsigned, 1> MismatchedParams;
6482   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6483   TypoCorrection Correction;
6484   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6485   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6486                                    : diag::err_member_decl_does_not_match;
6487   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6488                     IsLocalFriend ? Sema::LookupLocalFriendName
6489                                   : Sema::LookupOrdinaryName,
6490                     Sema::ForRedeclaration);
6491 
6492   NewFD->setInvalidDecl();
6493   if (IsLocalFriend)
6494     SemaRef.LookupName(Prev, S);
6495   else
6496     SemaRef.LookupQualifiedName(Prev, NewDC);
6497   assert(!Prev.isAmbiguous() &&
6498          "Cannot have an ambiguity in previous-declaration lookup");
6499   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6500   if (!Prev.empty()) {
6501     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6502          Func != FuncEnd; ++Func) {
6503       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6504       if (FD &&
6505           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6506         // Add 1 to the index so that 0 can mean the mismatch didn't
6507         // involve a parameter
6508         unsigned ParamNum =
6509             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6510         NearMatches.push_back(std::make_pair(FD, ParamNum));
6511       }
6512     }
6513   // If the qualified name lookup yielded nothing, try typo correction
6514   } else if ((Correction = SemaRef.CorrectTypo(
6515                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6516                   &ExtraArgs.D.getCXXScopeSpec(),
6517                   llvm::make_unique<DifferentNameValidatorCCC>(
6518                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
6519                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6520     // Set up everything for the call to ActOnFunctionDeclarator
6521     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6522                               ExtraArgs.D.getIdentifierLoc());
6523     Previous.clear();
6524     Previous.setLookupName(Correction.getCorrection());
6525     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6526                                     CDeclEnd = Correction.end();
6527          CDecl != CDeclEnd; ++CDecl) {
6528       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6529       if (FD && !FD->hasBody() &&
6530           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6531         Previous.addDecl(FD);
6532       }
6533     }
6534     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6535 
6536     NamedDecl *Result;
6537     // Retry building the function declaration with the new previous
6538     // declarations, and with errors suppressed.
6539     {
6540       // Trap errors.
6541       Sema::SFINAETrap Trap(SemaRef);
6542 
6543       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6544       // pieces need to verify the typo-corrected C++ declaration and hopefully
6545       // eliminate the need for the parameter pack ExtraArgs.
6546       Result = SemaRef.ActOnFunctionDeclarator(
6547           ExtraArgs.S, ExtraArgs.D,
6548           Correction.getCorrectionDecl()->getDeclContext(),
6549           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6550           ExtraArgs.AddToScope);
6551 
6552       if (Trap.hasErrorOccurred())
6553         Result = nullptr;
6554     }
6555 
6556     if (Result) {
6557       // Determine which correction we picked.
6558       Decl *Canonical = Result->getCanonicalDecl();
6559       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6560            I != E; ++I)
6561         if ((*I)->getCanonicalDecl() == Canonical)
6562           Correction.setCorrectionDecl(*I);
6563 
6564       SemaRef.diagnoseTypo(
6565           Correction,
6566           SemaRef.PDiag(IsLocalFriend
6567                           ? diag::err_no_matching_local_friend_suggest
6568                           : diag::err_member_decl_does_not_match_suggest)
6569             << Name << NewDC << IsDefinition);
6570       return Result;
6571     }
6572 
6573     // Pretend the typo correction never occurred
6574     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6575                               ExtraArgs.D.getIdentifierLoc());
6576     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6577     Previous.clear();
6578     Previous.setLookupName(Name);
6579   }
6580 
6581   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6582       << Name << NewDC << IsDefinition << NewFD->getLocation();
6583 
6584   bool NewFDisConst = false;
6585   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6586     NewFDisConst = NewMD->isConst();
6587 
6588   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6589        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6590        NearMatch != NearMatchEnd; ++NearMatch) {
6591     FunctionDecl *FD = NearMatch->first;
6592     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6593     bool FDisConst = MD && MD->isConst();
6594     bool IsMember = MD || !IsLocalFriend;
6595 
6596     // FIXME: These notes are poorly worded for the local friend case.
6597     if (unsigned Idx = NearMatch->second) {
6598       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6599       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6600       if (Loc.isInvalid()) Loc = FD->getLocation();
6601       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6602                                  : diag::note_local_decl_close_param_match)
6603         << Idx << FDParam->getType()
6604         << NewFD->getParamDecl(Idx - 1)->getType();
6605     } else if (FDisConst != NewFDisConst) {
6606       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6607           << NewFDisConst << FD->getSourceRange().getEnd();
6608     } else
6609       SemaRef.Diag(FD->getLocation(),
6610                    IsMember ? diag::note_member_def_close_match
6611                             : diag::note_local_decl_close_match);
6612   }
6613   return nullptr;
6614 }
6615 
6616 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
6617   switch (D.getDeclSpec().getStorageClassSpec()) {
6618   default: llvm_unreachable("Unknown storage class!");
6619   case DeclSpec::SCS_auto:
6620   case DeclSpec::SCS_register:
6621   case DeclSpec::SCS_mutable:
6622     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6623                  diag::err_typecheck_sclass_func);
6624     D.setInvalidType();
6625     break;
6626   case DeclSpec::SCS_unspecified: break;
6627   case DeclSpec::SCS_extern:
6628     if (D.getDeclSpec().isExternInLinkageSpec())
6629       return SC_None;
6630     return SC_Extern;
6631   case DeclSpec::SCS_static: {
6632     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6633       // C99 6.7.1p5:
6634       //   The declaration of an identifier for a function that has
6635       //   block scope shall have no explicit storage-class specifier
6636       //   other than extern
6637       // See also (C++ [dcl.stc]p4).
6638       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6639                    diag::err_static_block_func);
6640       break;
6641     } else
6642       return SC_Static;
6643   }
6644   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6645   }
6646 
6647   // No explicit storage class has already been returned
6648   return SC_None;
6649 }
6650 
6651 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6652                                            DeclContext *DC, QualType &R,
6653                                            TypeSourceInfo *TInfo,
6654                                            StorageClass SC,
6655                                            bool &IsVirtualOkay) {
6656   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6657   DeclarationName Name = NameInfo.getName();
6658 
6659   FunctionDecl *NewFD = nullptr;
6660   bool isInline = D.getDeclSpec().isInlineSpecified();
6661 
6662   if (!SemaRef.getLangOpts().CPlusPlus) {
6663     // Determine whether the function was written with a
6664     // prototype. This true when:
6665     //   - there is a prototype in the declarator, or
6666     //   - the type R of the function is some kind of typedef or other reference
6667     //     to a type name (which eventually refers to a function type).
6668     bool HasPrototype =
6669       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6670       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6671 
6672     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6673                                  D.getLocStart(), NameInfo, R,
6674                                  TInfo, SC, isInline,
6675                                  HasPrototype, false);
6676     if (D.isInvalidType())
6677       NewFD->setInvalidDecl();
6678 
6679     return NewFD;
6680   }
6681 
6682   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6683   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6684 
6685   // Check that the return type is not an abstract class type.
6686   // For record types, this is done by the AbstractClassUsageDiagnoser once
6687   // the class has been completely parsed.
6688   if (!DC->isRecord() &&
6689       SemaRef.RequireNonAbstractType(
6690           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6691           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
6692     D.setInvalidType();
6693 
6694   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6695     // This is a C++ constructor declaration.
6696     assert(DC->isRecord() &&
6697            "Constructors can only be declared in a member context");
6698 
6699     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6700     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6701                                       D.getLocStart(), NameInfo,
6702                                       R, TInfo, isExplicit, isInline,
6703                                       /*isImplicitlyDeclared=*/false,
6704                                       isConstexpr);
6705 
6706   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6707     // This is a C++ destructor declaration.
6708     if (DC->isRecord()) {
6709       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6710       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6711       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6712                                         SemaRef.Context, Record,
6713                                         D.getLocStart(),
6714                                         NameInfo, R, TInfo, isInline,
6715                                         /*isImplicitlyDeclared=*/false);
6716 
6717       // If the class is complete, then we now create the implicit exception
6718       // specification. If the class is incomplete or dependent, we can't do
6719       // it yet.
6720       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6721           Record->getDefinition() && !Record->isBeingDefined() &&
6722           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6723         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6724       }
6725 
6726       IsVirtualOkay = true;
6727       return NewDD;
6728 
6729     } else {
6730       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6731       D.setInvalidType();
6732 
6733       // Create a FunctionDecl to satisfy the function definition parsing
6734       // code path.
6735       return FunctionDecl::Create(SemaRef.Context, DC,
6736                                   D.getLocStart(),
6737                                   D.getIdentifierLoc(), Name, R, TInfo,
6738                                   SC, isInline,
6739                                   /*hasPrototype=*/true, isConstexpr);
6740     }
6741 
6742   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6743     if (!DC->isRecord()) {
6744       SemaRef.Diag(D.getIdentifierLoc(),
6745            diag::err_conv_function_not_member);
6746       return nullptr;
6747     }
6748 
6749     SemaRef.CheckConversionDeclarator(D, R, SC);
6750     IsVirtualOkay = true;
6751     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6752                                      D.getLocStart(), NameInfo,
6753                                      R, TInfo, isInline, isExplicit,
6754                                      isConstexpr, SourceLocation());
6755 
6756   } else if (DC->isRecord()) {
6757     // If the name of the function is the same as the name of the record,
6758     // then this must be an invalid constructor that has a return type.
6759     // (The parser checks for a return type and makes the declarator a
6760     // constructor if it has no return type).
6761     if (Name.getAsIdentifierInfo() &&
6762         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6763       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6764         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6765         << SourceRange(D.getIdentifierLoc());
6766       return nullptr;
6767     }
6768 
6769     // This is a C++ method declaration.
6770     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6771                                                cast<CXXRecordDecl>(DC),
6772                                                D.getLocStart(), NameInfo, R,
6773                                                TInfo, SC, isInline,
6774                                                isConstexpr, SourceLocation());
6775     IsVirtualOkay = !Ret->isStatic();
6776     return Ret;
6777   } else {
6778     bool isFriend =
6779         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
6780     if (!isFriend && SemaRef.CurContext->isRecord())
6781       return nullptr;
6782 
6783     // Determine whether the function was written with a
6784     // prototype. This true when:
6785     //   - we're in C++ (where every function has a prototype),
6786     return FunctionDecl::Create(SemaRef.Context, DC,
6787                                 D.getLocStart(),
6788                                 NameInfo, R, TInfo, SC, isInline,
6789                                 true/*HasPrototype*/, isConstexpr);
6790   }
6791 }
6792 
6793 enum OpenCLParamType {
6794   ValidKernelParam,
6795   PtrPtrKernelParam,
6796   PtrKernelParam,
6797   PrivatePtrKernelParam,
6798   InvalidKernelParam,
6799   RecordKernelParam
6800 };
6801 
6802 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6803   if (PT->isPointerType()) {
6804     QualType PointeeType = PT->getPointeeType();
6805     if (PointeeType->isPointerType())
6806       return PtrPtrKernelParam;
6807     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
6808                                               : PtrKernelParam;
6809   }
6810 
6811   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6812   // be used as builtin types.
6813 
6814   if (PT->isImageType())
6815     return PtrKernelParam;
6816 
6817   if (PT->isBooleanType())
6818     return InvalidKernelParam;
6819 
6820   if (PT->isEventT())
6821     return InvalidKernelParam;
6822 
6823   if (PT->isHalfType())
6824     return InvalidKernelParam;
6825 
6826   if (PT->isRecordType())
6827     return RecordKernelParam;
6828 
6829   return ValidKernelParam;
6830 }
6831 
6832 static void checkIsValidOpenCLKernelParameter(
6833   Sema &S,
6834   Declarator &D,
6835   ParmVarDecl *Param,
6836   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
6837   QualType PT = Param->getType();
6838 
6839   // Cache the valid types we encounter to avoid rechecking structs that are
6840   // used again
6841   if (ValidTypes.count(PT.getTypePtr()))
6842     return;
6843 
6844   switch (getOpenCLKernelParameterType(PT)) {
6845   case PtrPtrKernelParam:
6846     // OpenCL v1.2 s6.9.a:
6847     // A kernel function argument cannot be declared as a
6848     // pointer to a pointer type.
6849     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6850     D.setInvalidType();
6851     return;
6852 
6853   case PrivatePtrKernelParam:
6854     // OpenCL v1.2 s6.9.a:
6855     // A kernel function argument cannot be declared as a
6856     // pointer to the private address space.
6857     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
6858     D.setInvalidType();
6859     return;
6860 
6861     // OpenCL v1.2 s6.9.k:
6862     // Arguments to kernel functions in a program cannot be declared with the
6863     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6864     // uintptr_t or a struct and/or union that contain fields declared to be
6865     // one of these built-in scalar types.
6866 
6867   case InvalidKernelParam:
6868     // OpenCL v1.2 s6.8 n:
6869     // A kernel function argument cannot be declared
6870     // of event_t type.
6871     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6872     D.setInvalidType();
6873     return;
6874 
6875   case PtrKernelParam:
6876   case ValidKernelParam:
6877     ValidTypes.insert(PT.getTypePtr());
6878     return;
6879 
6880   case RecordKernelParam:
6881     break;
6882   }
6883 
6884   // Track nested structs we will inspect
6885   SmallVector<const Decl *, 4> VisitStack;
6886 
6887   // Track where we are in the nested structs. Items will migrate from
6888   // VisitStack to HistoryStack as we do the DFS for bad field.
6889   SmallVector<const FieldDecl *, 4> HistoryStack;
6890   HistoryStack.push_back(nullptr);
6891 
6892   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6893   VisitStack.push_back(PD);
6894 
6895   assert(VisitStack.back() && "First decl null?");
6896 
6897   do {
6898     const Decl *Next = VisitStack.pop_back_val();
6899     if (!Next) {
6900       assert(!HistoryStack.empty());
6901       // Found a marker, we have gone up a level
6902       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6903         ValidTypes.insert(Hist->getType().getTypePtr());
6904 
6905       continue;
6906     }
6907 
6908     // Adds everything except the original parameter declaration (which is not a
6909     // field itself) to the history stack.
6910     const RecordDecl *RD;
6911     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6912       HistoryStack.push_back(Field);
6913       RD = Field->getType()->castAs<RecordType>()->getDecl();
6914     } else {
6915       RD = cast<RecordDecl>(Next);
6916     }
6917 
6918     // Add a null marker so we know when we've gone back up a level
6919     VisitStack.push_back(nullptr);
6920 
6921     for (const auto *FD : RD->fields()) {
6922       QualType QT = FD->getType();
6923 
6924       if (ValidTypes.count(QT.getTypePtr()))
6925         continue;
6926 
6927       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6928       if (ParamType == ValidKernelParam)
6929         continue;
6930 
6931       if (ParamType == RecordKernelParam) {
6932         VisitStack.push_back(FD);
6933         continue;
6934       }
6935 
6936       // OpenCL v1.2 s6.9.p:
6937       // Arguments to kernel functions that are declared to be a struct or union
6938       // do not allow OpenCL objects to be passed as elements of the struct or
6939       // union.
6940       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
6941           ParamType == PrivatePtrKernelParam) {
6942         S.Diag(Param->getLocation(),
6943                diag::err_record_with_pointers_kernel_param)
6944           << PT->isUnionType()
6945           << PT;
6946       } else {
6947         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6948       }
6949 
6950       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6951         << PD->getDeclName();
6952 
6953       // We have an error, now let's go back up through history and show where
6954       // the offending field came from
6955       for (ArrayRef<const FieldDecl *>::const_iterator
6956                I = HistoryStack.begin() + 1,
6957                E = HistoryStack.end();
6958            I != E; ++I) {
6959         const FieldDecl *OuterField = *I;
6960         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6961           << OuterField->getType();
6962       }
6963 
6964       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6965         << QT->isPointerType()
6966         << QT;
6967       D.setInvalidType();
6968       return;
6969     }
6970   } while (!VisitStack.empty());
6971 }
6972 
6973 NamedDecl*
6974 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
6975                               TypeSourceInfo *TInfo, LookupResult &Previous,
6976                               MultiTemplateParamsArg TemplateParamLists,
6977                               bool &AddToScope) {
6978   QualType R = TInfo->getType();
6979 
6980   assert(R.getTypePtr()->isFunctionType());
6981 
6982   // TODO: consider using NameInfo for diagnostic.
6983   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6984   DeclarationName Name = NameInfo.getName();
6985   StorageClass SC = getFunctionStorageClass(*this, D);
6986 
6987   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6988     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6989          diag::err_invalid_thread)
6990       << DeclSpec::getSpecifierName(TSCS);
6991 
6992   if (D.isFirstDeclarationOfMember())
6993     adjustMemberFunctionCC(R, D.isStaticMember());
6994 
6995   bool isFriend = false;
6996   FunctionTemplateDecl *FunctionTemplate = nullptr;
6997   bool isExplicitSpecialization = false;
6998   bool isFunctionTemplateSpecialization = false;
6999 
7000   bool isDependentClassScopeExplicitSpecialization = false;
7001   bool HasExplicitTemplateArgs = false;
7002   TemplateArgumentListInfo TemplateArgs;
7003 
7004   bool isVirtualOkay = false;
7005 
7006   DeclContext *OriginalDC = DC;
7007   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7008 
7009   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7010                                               isVirtualOkay);
7011   if (!NewFD) return nullptr;
7012 
7013   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7014     NewFD->setTopLevelDeclInObjCContainer();
7015 
7016   // Set the lexical context. If this is a function-scope declaration, or has a
7017   // C++ scope specifier, or is the object of a friend declaration, the lexical
7018   // context will be different from the semantic context.
7019   NewFD->setLexicalDeclContext(CurContext);
7020 
7021   if (IsLocalExternDecl)
7022     NewFD->setLocalExternDecl();
7023 
7024   if (getLangOpts().CPlusPlus) {
7025     bool isInline = D.getDeclSpec().isInlineSpecified();
7026     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7027     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7028     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7029     isFriend = D.getDeclSpec().isFriendSpecified();
7030     if (isFriend && !isInline && D.isFunctionDefinition()) {
7031       // C++ [class.friend]p5
7032       //   A function can be defined in a friend declaration of a
7033       //   class . . . . Such a function is implicitly inline.
7034       NewFD->setImplicitlyInline();
7035     }
7036 
7037     // If this is a method defined in an __interface, and is not a constructor
7038     // or an overloaded operator, then set the pure flag (isVirtual will already
7039     // return true).
7040     if (const CXXRecordDecl *Parent =
7041           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7042       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7043         NewFD->setPure(true);
7044     }
7045 
7046     SetNestedNameSpecifier(NewFD, D);
7047     isExplicitSpecialization = false;
7048     isFunctionTemplateSpecialization = false;
7049     if (D.isInvalidType())
7050       NewFD->setInvalidDecl();
7051 
7052     // Match up the template parameter lists with the scope specifier, then
7053     // determine whether we have a template or a template specialization.
7054     bool Invalid = false;
7055     if (TemplateParameterList *TemplateParams =
7056             MatchTemplateParametersToScopeSpecifier(
7057                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7058                 D.getCXXScopeSpec(),
7059                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7060                     ? D.getName().TemplateId
7061                     : nullptr,
7062                 TemplateParamLists, isFriend, isExplicitSpecialization,
7063                 Invalid)) {
7064       if (TemplateParams->size() > 0) {
7065         // This is a function template
7066 
7067         // Check that we can declare a template here.
7068         if (CheckTemplateDeclScope(S, TemplateParams))
7069           NewFD->setInvalidDecl();
7070 
7071         // A destructor cannot be a template.
7072         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7073           Diag(NewFD->getLocation(), diag::err_destructor_template);
7074           NewFD->setInvalidDecl();
7075         }
7076 
7077         // If we're adding a template to a dependent context, we may need to
7078         // rebuilding some of the types used within the template parameter list,
7079         // now that we know what the current instantiation is.
7080         if (DC->isDependentContext()) {
7081           ContextRAII SavedContext(*this, DC);
7082           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7083             Invalid = true;
7084         }
7085 
7086 
7087         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7088                                                         NewFD->getLocation(),
7089                                                         Name, TemplateParams,
7090                                                         NewFD);
7091         FunctionTemplate->setLexicalDeclContext(CurContext);
7092         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7093 
7094         // For source fidelity, store the other template param lists.
7095         if (TemplateParamLists.size() > 1) {
7096           NewFD->setTemplateParameterListsInfo(Context,
7097                                                TemplateParamLists.size() - 1,
7098                                                TemplateParamLists.data());
7099         }
7100       } else {
7101         // This is a function template specialization.
7102         isFunctionTemplateSpecialization = true;
7103         // For source fidelity, store all the template param lists.
7104         if (TemplateParamLists.size() > 0)
7105           NewFD->setTemplateParameterListsInfo(Context,
7106                                                TemplateParamLists.size(),
7107                                                TemplateParamLists.data());
7108 
7109         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7110         if (isFriend) {
7111           // We want to remove the "template<>", found here.
7112           SourceRange RemoveRange = TemplateParams->getSourceRange();
7113 
7114           // If we remove the template<> and the name is not a
7115           // template-id, we're actually silently creating a problem:
7116           // the friend declaration will refer to an untemplated decl,
7117           // and clearly the user wants a template specialization.  So
7118           // we need to insert '<>' after the name.
7119           SourceLocation InsertLoc;
7120           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7121             InsertLoc = D.getName().getSourceRange().getEnd();
7122             InsertLoc = getLocForEndOfToken(InsertLoc);
7123           }
7124 
7125           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7126             << Name << RemoveRange
7127             << FixItHint::CreateRemoval(RemoveRange)
7128             << FixItHint::CreateInsertion(InsertLoc, "<>");
7129         }
7130       }
7131     }
7132     else {
7133       // All template param lists were matched against the scope specifier:
7134       // this is NOT (an explicit specialization of) a template.
7135       if (TemplateParamLists.size() > 0)
7136         // For source fidelity, store all the template param lists.
7137         NewFD->setTemplateParameterListsInfo(Context,
7138                                              TemplateParamLists.size(),
7139                                              TemplateParamLists.data());
7140     }
7141 
7142     if (Invalid) {
7143       NewFD->setInvalidDecl();
7144       if (FunctionTemplate)
7145         FunctionTemplate->setInvalidDecl();
7146     }
7147 
7148     // C++ [dcl.fct.spec]p5:
7149     //   The virtual specifier shall only be used in declarations of
7150     //   nonstatic class member functions that appear within a
7151     //   member-specification of a class declaration; see 10.3.
7152     //
7153     if (isVirtual && !NewFD->isInvalidDecl()) {
7154       if (!isVirtualOkay) {
7155         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7156              diag::err_virtual_non_function);
7157       } else if (!CurContext->isRecord()) {
7158         // 'virtual' was specified outside of the class.
7159         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7160              diag::err_virtual_out_of_class)
7161           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7162       } else if (NewFD->getDescribedFunctionTemplate()) {
7163         // C++ [temp.mem]p3:
7164         //  A member function template shall not be virtual.
7165         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7166              diag::err_virtual_member_function_template)
7167           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7168       } else {
7169         // Okay: Add virtual to the method.
7170         NewFD->setVirtualAsWritten(true);
7171       }
7172 
7173       if (getLangOpts().CPlusPlus14 &&
7174           NewFD->getReturnType()->isUndeducedType())
7175         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7176     }
7177 
7178     if (getLangOpts().CPlusPlus14 &&
7179         (NewFD->isDependentContext() ||
7180          (isFriend && CurContext->isDependentContext())) &&
7181         NewFD->getReturnType()->isUndeducedType()) {
7182       // If the function template is referenced directly (for instance, as a
7183       // member of the current instantiation), pretend it has a dependent type.
7184       // This is not really justified by the standard, but is the only sane
7185       // thing to do.
7186       // FIXME: For a friend function, we have not marked the function as being
7187       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7188       const FunctionProtoType *FPT =
7189           NewFD->getType()->castAs<FunctionProtoType>();
7190       QualType Result =
7191           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7192       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7193                                              FPT->getExtProtoInfo()));
7194     }
7195 
7196     // C++ [dcl.fct.spec]p3:
7197     //  The inline specifier shall not appear on a block scope function
7198     //  declaration.
7199     if (isInline && !NewFD->isInvalidDecl()) {
7200       if (CurContext->isFunctionOrMethod()) {
7201         // 'inline' is not allowed on block scope function declaration.
7202         Diag(D.getDeclSpec().getInlineSpecLoc(),
7203              diag::err_inline_declaration_block_scope) << Name
7204           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7205       }
7206     }
7207 
7208     // C++ [dcl.fct.spec]p6:
7209     //  The explicit specifier shall be used only in the declaration of a
7210     //  constructor or conversion function within its class definition;
7211     //  see 12.3.1 and 12.3.2.
7212     if (isExplicit && !NewFD->isInvalidDecl()) {
7213       if (!CurContext->isRecord()) {
7214         // 'explicit' was specified outside of the class.
7215         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7216              diag::err_explicit_out_of_class)
7217           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7218       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7219                  !isa<CXXConversionDecl>(NewFD)) {
7220         // 'explicit' was specified on a function that wasn't a constructor
7221         // or conversion function.
7222         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7223              diag::err_explicit_non_ctor_or_conv_function)
7224           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7225       }
7226     }
7227 
7228     if (isConstexpr) {
7229       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7230       // are implicitly inline.
7231       NewFD->setImplicitlyInline();
7232 
7233       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7234       // be either constructors or to return a literal type. Therefore,
7235       // destructors cannot be declared constexpr.
7236       if (isa<CXXDestructorDecl>(NewFD))
7237         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7238     }
7239 
7240     // If __module_private__ was specified, mark the function accordingly.
7241     if (D.getDeclSpec().isModulePrivateSpecified()) {
7242       if (isFunctionTemplateSpecialization) {
7243         SourceLocation ModulePrivateLoc
7244           = D.getDeclSpec().getModulePrivateSpecLoc();
7245         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7246           << 0
7247           << FixItHint::CreateRemoval(ModulePrivateLoc);
7248       } else {
7249         NewFD->setModulePrivate();
7250         if (FunctionTemplate)
7251           FunctionTemplate->setModulePrivate();
7252       }
7253     }
7254 
7255     if (isFriend) {
7256       if (FunctionTemplate) {
7257         FunctionTemplate->setObjectOfFriendDecl();
7258         FunctionTemplate->setAccess(AS_public);
7259       }
7260       NewFD->setObjectOfFriendDecl();
7261       NewFD->setAccess(AS_public);
7262     }
7263 
7264     // If a function is defined as defaulted or deleted, mark it as such now.
7265     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7266     // definition kind to FDK_Definition.
7267     switch (D.getFunctionDefinitionKind()) {
7268       case FDK_Declaration:
7269       case FDK_Definition:
7270         break;
7271 
7272       case FDK_Defaulted:
7273         NewFD->setDefaulted();
7274         break;
7275 
7276       case FDK_Deleted:
7277         NewFD->setDeletedAsWritten();
7278         break;
7279     }
7280 
7281     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7282         D.isFunctionDefinition()) {
7283       // C++ [class.mfct]p2:
7284       //   A member function may be defined (8.4) in its class definition, in
7285       //   which case it is an inline member function (7.1.2)
7286       NewFD->setImplicitlyInline();
7287     }
7288 
7289     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7290         !CurContext->isRecord()) {
7291       // C++ [class.static]p1:
7292       //   A data or function member of a class may be declared static
7293       //   in a class definition, in which case it is a static member of
7294       //   the class.
7295 
7296       // Complain about the 'static' specifier if it's on an out-of-line
7297       // member function definition.
7298       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7299            diag::err_static_out_of_line)
7300         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7301     }
7302 
7303     // C++11 [except.spec]p15:
7304     //   A deallocation function with no exception-specification is treated
7305     //   as if it were specified with noexcept(true).
7306     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7307     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7308          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7309         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7310       NewFD->setType(Context.getFunctionType(
7311           FPT->getReturnType(), FPT->getParamTypes(),
7312           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7313   }
7314 
7315   // Filter out previous declarations that don't match the scope.
7316   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7317                        D.getCXXScopeSpec().isNotEmpty() ||
7318                        isExplicitSpecialization ||
7319                        isFunctionTemplateSpecialization);
7320 
7321   // Handle GNU asm-label extension (encoded as an attribute).
7322   if (Expr *E = (Expr*) D.getAsmLabel()) {
7323     // The parser guarantees this is a string.
7324     StringLiteral *SE = cast<StringLiteral>(E);
7325     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7326                                                 SE->getString(), 0));
7327   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7328     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7329       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7330     if (I != ExtnameUndeclaredIdentifiers.end()) {
7331       NewFD->addAttr(I->second);
7332       ExtnameUndeclaredIdentifiers.erase(I);
7333     }
7334   }
7335 
7336   // Copy the parameter declarations from the declarator D to the function
7337   // declaration NewFD, if they are available.  First scavenge them into Params.
7338   SmallVector<ParmVarDecl*, 16> Params;
7339   if (D.isFunctionDeclarator()) {
7340     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7341 
7342     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7343     // function that takes no arguments, not a function that takes a
7344     // single void argument.
7345     // We let through "const void" here because Sema::GetTypeForDeclarator
7346     // already checks for that case.
7347     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7348       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7349         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7350         assert(Param->getDeclContext() != NewFD && "Was set before ?");
7351         Param->setDeclContext(NewFD);
7352         Params.push_back(Param);
7353 
7354         if (Param->isInvalidDecl())
7355           NewFD->setInvalidDecl();
7356       }
7357     }
7358 
7359   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7360     // When we're declaring a function with a typedef, typeof, etc as in the
7361     // following example, we'll need to synthesize (unnamed)
7362     // parameters for use in the declaration.
7363     //
7364     // @code
7365     // typedef void fn(int);
7366     // fn f;
7367     // @endcode
7368 
7369     // Synthesize a parameter for each argument type.
7370     for (const auto &AI : FT->param_types()) {
7371       ParmVarDecl *Param =
7372           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7373       Param->setScopeInfo(0, Params.size());
7374       Params.push_back(Param);
7375     }
7376   } else {
7377     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7378            "Should not need args for typedef of non-prototype fn");
7379   }
7380 
7381   // Finally, we know we have the right number of parameters, install them.
7382   NewFD->setParams(Params);
7383 
7384   // Find all anonymous symbols defined during the declaration of this function
7385   // and add to NewFD. This lets us track decls such 'enum Y' in:
7386   //
7387   //   void f(enum Y {AA} x) {}
7388   //
7389   // which would otherwise incorrectly end up in the translation unit scope.
7390   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7391   DeclsInPrototypeScope.clear();
7392 
7393   if (D.getDeclSpec().isNoreturnSpecified())
7394     NewFD->addAttr(
7395         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7396                                        Context, 0));
7397 
7398   // Functions returning a variably modified type violate C99 6.7.5.2p2
7399   // because all functions have linkage.
7400   if (!NewFD->isInvalidDecl() &&
7401       NewFD->getReturnType()->isVariablyModifiedType()) {
7402     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7403     NewFD->setInvalidDecl();
7404   }
7405 
7406   if (D.isFunctionDefinition() && CodeSegStack.CurrentValue &&
7407       !NewFD->hasAttr<SectionAttr>()) {
7408     NewFD->addAttr(
7409         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7410                                     CodeSegStack.CurrentValue->getString(),
7411                                     CodeSegStack.CurrentPragmaLocation));
7412     if (UnifySection(CodeSegStack.CurrentValue->getString(),
7413                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
7414                          ASTContext::PSF_Read,
7415                      NewFD))
7416       NewFD->dropAttr<SectionAttr>();
7417   }
7418 
7419   // Handle attributes.
7420   ProcessDeclAttributes(S, NewFD, D);
7421 
7422   QualType RetType = NewFD->getReturnType();
7423   const CXXRecordDecl *Ret = RetType->isRecordType() ?
7424       RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
7425   if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
7426       Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
7427     const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7428     // Attach WarnUnusedResult to functions returning types with that attribute.
7429     // Don't apply the attribute to that type's own non-static member functions
7430     // (to avoid warning on things like assignment operators)
7431     if (!MD || MD->getParent() != Ret)
7432       NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
7433   }
7434 
7435   if (getLangOpts().OpenCL) {
7436     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7437     // type declaration will generate a compilation error.
7438     unsigned AddressSpace = RetType.getAddressSpace();
7439     if (AddressSpace == LangAS::opencl_local ||
7440         AddressSpace == LangAS::opencl_global ||
7441         AddressSpace == LangAS::opencl_constant) {
7442       Diag(NewFD->getLocation(),
7443            diag::err_opencl_return_value_with_address_space);
7444       NewFD->setInvalidDecl();
7445     }
7446   }
7447 
7448   if (!getLangOpts().CPlusPlus) {
7449     // Perform semantic checking on the function declaration.
7450     bool isExplicitSpecialization=false;
7451     if (!NewFD->isInvalidDecl() && NewFD->isMain())
7452       CheckMain(NewFD, D.getDeclSpec());
7453 
7454     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7455       CheckMSVCRTEntryPoint(NewFD);
7456 
7457     if (!NewFD->isInvalidDecl())
7458       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7459                                                   isExplicitSpecialization));
7460     else if (!Previous.empty())
7461       // Recover gracefully from an invalid redeclaration.
7462       D.setRedeclaration(true);
7463     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7464             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7465            "previous declaration set still overloaded");
7466 
7467     // Diagnose no-prototype function declarations with calling conventions that
7468     // don't support variadic calls. Only do this in C and do it after merging
7469     // possibly prototyped redeclarations.
7470     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
7471     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
7472       CallingConv CC = FT->getExtInfo().getCC();
7473       if (!supportsVariadicCall(CC)) {
7474         // Windows system headers sometimes accidentally use stdcall without
7475         // (void) parameters, so we relax this to a warning.
7476         int DiagID =
7477             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
7478         Diag(NewFD->getLocation(), DiagID)
7479             << FunctionType::getNameForCallConv(CC);
7480       }
7481     }
7482   } else {
7483     // C++11 [replacement.functions]p3:
7484     //  The program's definitions shall not be specified as inline.
7485     //
7486     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7487     //
7488     // Suppress the diagnostic if the function is __attribute__((used)), since
7489     // that forces an external definition to be emitted.
7490     if (D.getDeclSpec().isInlineSpecified() &&
7491         NewFD->isReplaceableGlobalAllocationFunction() &&
7492         !NewFD->hasAttr<UsedAttr>())
7493       Diag(D.getDeclSpec().getInlineSpecLoc(),
7494            diag::ext_operator_new_delete_declared_inline)
7495         << NewFD->getDeclName();
7496 
7497     // If the declarator is a template-id, translate the parser's template
7498     // argument list into our AST format.
7499     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7500       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7501       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7502       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7503       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7504                                          TemplateId->NumArgs);
7505       translateTemplateArguments(TemplateArgsPtr,
7506                                  TemplateArgs);
7507 
7508       HasExplicitTemplateArgs = true;
7509 
7510       if (NewFD->isInvalidDecl()) {
7511         HasExplicitTemplateArgs = false;
7512       } else if (FunctionTemplate) {
7513         // Function template with explicit template arguments.
7514         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7515           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7516 
7517         HasExplicitTemplateArgs = false;
7518       } else {
7519         assert((isFunctionTemplateSpecialization ||
7520                 D.getDeclSpec().isFriendSpecified()) &&
7521                "should have a 'template<>' for this decl");
7522         // "friend void foo<>(int);" is an implicit specialization decl.
7523         isFunctionTemplateSpecialization = true;
7524       }
7525     } else if (isFriend && isFunctionTemplateSpecialization) {
7526       // This combination is only possible in a recovery case;  the user
7527       // wrote something like:
7528       //   template <> friend void foo(int);
7529       // which we're recovering from as if the user had written:
7530       //   friend void foo<>(int);
7531       // Go ahead and fake up a template id.
7532       HasExplicitTemplateArgs = true;
7533       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7534       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7535     }
7536 
7537     // If it's a friend (and only if it's a friend), it's possible
7538     // that either the specialized function type or the specialized
7539     // template is dependent, and therefore matching will fail.  In
7540     // this case, don't check the specialization yet.
7541     bool InstantiationDependent = false;
7542     if (isFunctionTemplateSpecialization && isFriend &&
7543         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7544          TemplateSpecializationType::anyDependentTemplateArguments(
7545             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7546             InstantiationDependent))) {
7547       assert(HasExplicitTemplateArgs &&
7548              "friend function specialization without template args");
7549       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7550                                                        Previous))
7551         NewFD->setInvalidDecl();
7552     } else if (isFunctionTemplateSpecialization) {
7553       if (CurContext->isDependentContext() && CurContext->isRecord()
7554           && !isFriend) {
7555         isDependentClassScopeExplicitSpecialization = true;
7556         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7557           diag::ext_function_specialization_in_class :
7558           diag::err_function_specialization_in_class)
7559           << NewFD->getDeclName();
7560       } else if (CheckFunctionTemplateSpecialization(NewFD,
7561                                   (HasExplicitTemplateArgs ? &TemplateArgs
7562                                                            : nullptr),
7563                                                      Previous))
7564         NewFD->setInvalidDecl();
7565 
7566       // C++ [dcl.stc]p1:
7567       //   A storage-class-specifier shall not be specified in an explicit
7568       //   specialization (14.7.3)
7569       FunctionTemplateSpecializationInfo *Info =
7570           NewFD->getTemplateSpecializationInfo();
7571       if (Info && SC != SC_None) {
7572         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7573           Diag(NewFD->getLocation(),
7574                diag::err_explicit_specialization_inconsistent_storage_class)
7575             << SC
7576             << FixItHint::CreateRemoval(
7577                                       D.getDeclSpec().getStorageClassSpecLoc());
7578 
7579         else
7580           Diag(NewFD->getLocation(),
7581                diag::ext_explicit_specialization_storage_class)
7582             << FixItHint::CreateRemoval(
7583                                       D.getDeclSpec().getStorageClassSpecLoc());
7584       }
7585 
7586     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7587       if (CheckMemberSpecialization(NewFD, Previous))
7588           NewFD->setInvalidDecl();
7589     }
7590 
7591     // Perform semantic checking on the function declaration.
7592     if (!isDependentClassScopeExplicitSpecialization) {
7593       if (!NewFD->isInvalidDecl() && NewFD->isMain())
7594         CheckMain(NewFD, D.getDeclSpec());
7595 
7596       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7597         CheckMSVCRTEntryPoint(NewFD);
7598 
7599       if (!NewFD->isInvalidDecl())
7600         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7601                                                     isExplicitSpecialization));
7602       else if (!Previous.empty())
7603         // Recover gracefully from an invalid redeclaration.
7604         D.setRedeclaration(true);
7605     }
7606 
7607     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7608             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7609            "previous declaration set still overloaded");
7610 
7611     NamedDecl *PrincipalDecl = (FunctionTemplate
7612                                 ? cast<NamedDecl>(FunctionTemplate)
7613                                 : NewFD);
7614 
7615     if (isFriend && D.isRedeclaration()) {
7616       AccessSpecifier Access = AS_public;
7617       if (!NewFD->isInvalidDecl())
7618         Access = NewFD->getPreviousDecl()->getAccess();
7619 
7620       NewFD->setAccess(Access);
7621       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7622     }
7623 
7624     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7625         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7626       PrincipalDecl->setNonMemberOperator();
7627 
7628     // If we have a function template, check the template parameter
7629     // list. This will check and merge default template arguments.
7630     if (FunctionTemplate) {
7631       FunctionTemplateDecl *PrevTemplate =
7632                                      FunctionTemplate->getPreviousDecl();
7633       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7634                        PrevTemplate ? PrevTemplate->getTemplateParameters()
7635                                     : nullptr,
7636                             D.getDeclSpec().isFriendSpecified()
7637                               ? (D.isFunctionDefinition()
7638                                    ? TPC_FriendFunctionTemplateDefinition
7639                                    : TPC_FriendFunctionTemplate)
7640                               : (D.getCXXScopeSpec().isSet() &&
7641                                  DC && DC->isRecord() &&
7642                                  DC->isDependentContext())
7643                                   ? TPC_ClassTemplateMember
7644                                   : TPC_FunctionTemplate);
7645     }
7646 
7647     if (NewFD->isInvalidDecl()) {
7648       // Ignore all the rest of this.
7649     } else if (!D.isRedeclaration()) {
7650       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7651                                        AddToScope };
7652       // Fake up an access specifier if it's supposed to be a class member.
7653       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7654         NewFD->setAccess(AS_public);
7655 
7656       // Qualified decls generally require a previous declaration.
7657       if (D.getCXXScopeSpec().isSet()) {
7658         // ...with the major exception of templated-scope or
7659         // dependent-scope friend declarations.
7660 
7661         // TODO: we currently also suppress this check in dependent
7662         // contexts because (1) the parameter depth will be off when
7663         // matching friend templates and (2) we might actually be
7664         // selecting a friend based on a dependent factor.  But there
7665         // are situations where these conditions don't apply and we
7666         // can actually do this check immediately.
7667         if (isFriend &&
7668             (TemplateParamLists.size() ||
7669              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7670              CurContext->isDependentContext())) {
7671           // ignore these
7672         } else {
7673           // The user tried to provide an out-of-line definition for a
7674           // function that is a member of a class or namespace, but there
7675           // was no such member function declared (C++ [class.mfct]p2,
7676           // C++ [namespace.memdef]p2). For example:
7677           //
7678           // class X {
7679           //   void f() const;
7680           // };
7681           //
7682           // void X::f() { } // ill-formed
7683           //
7684           // Complain about this problem, and attempt to suggest close
7685           // matches (e.g., those that differ only in cv-qualifiers and
7686           // whether the parameter types are references).
7687 
7688           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7689                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
7690             AddToScope = ExtraArgs.AddToScope;
7691             return Result;
7692           }
7693         }
7694 
7695         // Unqualified local friend declarations are required to resolve
7696         // to something.
7697       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7698         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7699                 *this, Previous, NewFD, ExtraArgs, true, S)) {
7700           AddToScope = ExtraArgs.AddToScope;
7701           return Result;
7702         }
7703       }
7704 
7705     } else if (!D.isFunctionDefinition() &&
7706                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
7707                !isFriend && !isFunctionTemplateSpecialization &&
7708                !isExplicitSpecialization) {
7709       // An out-of-line member function declaration must also be a
7710       // definition (C++ [class.mfct]p2).
7711       // Note that this is not the case for explicit specializations of
7712       // function templates or member functions of class templates, per
7713       // C++ [temp.expl.spec]p2. We also allow these declarations as an
7714       // extension for compatibility with old SWIG code which likes to
7715       // generate them.
7716       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7717         << D.getCXXScopeSpec().getRange();
7718     }
7719   }
7720 
7721   ProcessPragmaWeak(S, NewFD);
7722   checkAttributesAfterMerging(*this, *NewFD);
7723 
7724   AddKnownFunctionAttributes(NewFD);
7725 
7726   if (NewFD->hasAttr<OverloadableAttr>() &&
7727       !NewFD->getType()->getAs<FunctionProtoType>()) {
7728     Diag(NewFD->getLocation(),
7729          diag::err_attribute_overloadable_no_prototype)
7730       << NewFD;
7731 
7732     // Turn this into a variadic function with no parameters.
7733     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7734     FunctionProtoType::ExtProtoInfo EPI(
7735         Context.getDefaultCallingConvention(true, false));
7736     EPI.Variadic = true;
7737     EPI.ExtInfo = FT->getExtInfo();
7738 
7739     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
7740     NewFD->setType(R);
7741   }
7742 
7743   // If there's a #pragma GCC visibility in scope, and this isn't a class
7744   // member, set the visibility of this function.
7745   if (!DC->isRecord() && NewFD->isExternallyVisible())
7746     AddPushedVisibilityAttribute(NewFD);
7747 
7748   // If there's a #pragma clang arc_cf_code_audited in scope, consider
7749   // marking the function.
7750   AddCFAuditedAttribute(NewFD);
7751 
7752   // If this is a function definition, check if we have to apply optnone due to
7753   // a pragma.
7754   if(D.isFunctionDefinition())
7755     AddRangeBasedOptnone(NewFD);
7756 
7757   // If this is the first declaration of an extern C variable, update
7758   // the map of such variables.
7759   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
7760       isIncompleteDeclExternC(*this, NewFD))
7761     RegisterLocallyScopedExternCDecl(NewFD, S);
7762 
7763   // Set this FunctionDecl's range up to the right paren.
7764   NewFD->setRangeEnd(D.getSourceRange().getEnd());
7765 
7766   if (D.isRedeclaration() && !Previous.empty()) {
7767     checkDLLAttributeRedeclaration(
7768         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
7769         isExplicitSpecialization || isFunctionTemplateSpecialization);
7770   }
7771 
7772   if (getLangOpts().CPlusPlus) {
7773     if (FunctionTemplate) {
7774       if (NewFD->isInvalidDecl())
7775         FunctionTemplate->setInvalidDecl();
7776       return FunctionTemplate;
7777     }
7778   }
7779 
7780   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
7781     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7782     if ((getLangOpts().OpenCLVersion >= 120)
7783         && (SC == SC_Static)) {
7784       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7785       D.setInvalidType();
7786     }
7787 
7788     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7789     if (!NewFD->getReturnType()->isVoidType()) {
7790       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
7791       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
7792           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
7793                                 : FixItHint());
7794       D.setInvalidType();
7795     }
7796 
7797     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
7798     for (auto Param : NewFD->params())
7799       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
7800   }
7801 
7802   MarkUnusedFileScopedDecl(NewFD);
7803 
7804   if (getLangOpts().CUDA)
7805     if (IdentifierInfo *II = NewFD->getIdentifier())
7806       if (!NewFD->isInvalidDecl() &&
7807           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7808         if (II->isStr("cudaConfigureCall")) {
7809           if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
7810             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7811 
7812           Context.setcudaConfigureCallDecl(NewFD);
7813         }
7814       }
7815 
7816   // Here we have an function template explicit specialization at class scope.
7817   // The actually specialization will be postponed to template instatiation
7818   // time via the ClassScopeFunctionSpecializationDecl node.
7819   if (isDependentClassScopeExplicitSpecialization) {
7820     ClassScopeFunctionSpecializationDecl *NewSpec =
7821                          ClassScopeFunctionSpecializationDecl::Create(
7822                                 Context, CurContext, SourceLocation(),
7823                                 cast<CXXMethodDecl>(NewFD),
7824                                 HasExplicitTemplateArgs, TemplateArgs);
7825     CurContext->addDecl(NewSpec);
7826     AddToScope = false;
7827   }
7828 
7829   return NewFD;
7830 }
7831 
7832 /// \brief Perform semantic checking of a new function declaration.
7833 ///
7834 /// Performs semantic analysis of the new function declaration
7835 /// NewFD. This routine performs all semantic checking that does not
7836 /// require the actual declarator involved in the declaration, and is
7837 /// used both for the declaration of functions as they are parsed
7838 /// (called via ActOnDeclarator) and for the declaration of functions
7839 /// that have been instantiated via C++ template instantiation (called
7840 /// via InstantiateDecl).
7841 ///
7842 /// \param IsExplicitSpecialization whether this new function declaration is
7843 /// an explicit specialization of the previous declaration.
7844 ///
7845 /// This sets NewFD->isInvalidDecl() to true if there was an error.
7846 ///
7847 /// \returns true if the function declaration is a redeclaration.
7848 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
7849                                     LookupResult &Previous,
7850                                     bool IsExplicitSpecialization) {
7851   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7852          "Variably modified return types are not handled here");
7853 
7854   // Determine whether the type of this function should be merged with
7855   // a previous visible declaration. This never happens for functions in C++,
7856   // and always happens in C if the previous declaration was visible.
7857   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7858                                !Previous.isShadowed();
7859 
7860   // Filter out any non-conflicting previous declarations.
7861   filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7862 
7863   bool Redeclaration = false;
7864   NamedDecl *OldDecl = nullptr;
7865 
7866   // Merge or overload the declaration with an existing declaration of
7867   // the same name, if appropriate.
7868   if (!Previous.empty()) {
7869     // Determine whether NewFD is an overload of PrevDecl or
7870     // a declaration that requires merging. If it's an overload,
7871     // there's no more work to do here; we'll just add the new
7872     // function to the scope.
7873     if (!AllowOverloadingOfFunction(Previous, Context)) {
7874       NamedDecl *Candidate = Previous.getFoundDecl();
7875       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7876         Redeclaration = true;
7877         OldDecl = Candidate;
7878       }
7879     } else {
7880       switch (CheckOverload(S, NewFD, Previous, OldDecl,
7881                             /*NewIsUsingDecl*/ false)) {
7882       case Ovl_Match:
7883         Redeclaration = true;
7884         break;
7885 
7886       case Ovl_NonFunction:
7887         Redeclaration = true;
7888         break;
7889 
7890       case Ovl_Overload:
7891         Redeclaration = false;
7892         break;
7893       }
7894 
7895       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7896         // If a function name is overloadable in C, then every function
7897         // with that name must be marked "overloadable".
7898         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7899           << Redeclaration << NewFD;
7900         NamedDecl *OverloadedDecl = nullptr;
7901         if (Redeclaration)
7902           OverloadedDecl = OldDecl;
7903         else if (!Previous.empty())
7904           OverloadedDecl = Previous.getRepresentativeDecl();
7905         if (OverloadedDecl)
7906           Diag(OverloadedDecl->getLocation(),
7907                diag::note_attribute_overloadable_prev_overload);
7908         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7909       }
7910     }
7911   }
7912 
7913   // Check for a previous extern "C" declaration with this name.
7914   if (!Redeclaration &&
7915       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7916     filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7917     if (!Previous.empty()) {
7918       // This is an extern "C" declaration with the same name as a previous
7919       // declaration, and thus redeclares that entity...
7920       Redeclaration = true;
7921       OldDecl = Previous.getFoundDecl();
7922       MergeTypeWithPrevious = false;
7923 
7924       // ... except in the presence of __attribute__((overloadable)).
7925       if (OldDecl->hasAttr<OverloadableAttr>()) {
7926         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7927           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7928             << Redeclaration << NewFD;
7929           Diag(Previous.getFoundDecl()->getLocation(),
7930                diag::note_attribute_overloadable_prev_overload);
7931           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7932         }
7933         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7934           Redeclaration = false;
7935           OldDecl = nullptr;
7936         }
7937       }
7938     }
7939   }
7940 
7941   // C++11 [dcl.constexpr]p8:
7942   //   A constexpr specifier for a non-static member function that is not
7943   //   a constructor declares that member function to be const.
7944   //
7945   // This needs to be delayed until we know whether this is an out-of-line
7946   // definition of a static member function.
7947   //
7948   // This rule is not present in C++1y, so we produce a backwards
7949   // compatibility warning whenever it happens in C++11.
7950   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7951   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
7952       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
7953       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7954     CXXMethodDecl *OldMD = nullptr;
7955     if (OldDecl)
7956       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
7957     if (!OldMD || !OldMD->isStatic()) {
7958       const FunctionProtoType *FPT =
7959         MD->getType()->castAs<FunctionProtoType>();
7960       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7961       EPI.TypeQuals |= Qualifiers::Const;
7962       MD->setType(Context.getFunctionType(FPT->getReturnType(),
7963                                           FPT->getParamTypes(), EPI));
7964 
7965       // Warn that we did this, if we're not performing template instantiation.
7966       // In that case, we'll have warned already when the template was defined.
7967       if (ActiveTemplateInstantiations.empty()) {
7968         SourceLocation AddConstLoc;
7969         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7970                 .IgnoreParens().getAs<FunctionTypeLoc>())
7971           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
7972 
7973         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
7974           << FixItHint::CreateInsertion(AddConstLoc, " const");
7975       }
7976     }
7977   }
7978 
7979   if (Redeclaration) {
7980     // NewFD and OldDecl represent declarations that need to be
7981     // merged.
7982     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
7983       NewFD->setInvalidDecl();
7984       return Redeclaration;
7985     }
7986 
7987     Previous.clear();
7988     Previous.addDecl(OldDecl);
7989 
7990     if (FunctionTemplateDecl *OldTemplateDecl
7991                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7992       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7993       FunctionTemplateDecl *NewTemplateDecl
7994         = NewFD->getDescribedFunctionTemplate();
7995       assert(NewTemplateDecl && "Template/non-template mismatch");
7996       if (CXXMethodDecl *Method
7997             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7998         Method->setAccess(OldTemplateDecl->getAccess());
7999         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8000       }
8001 
8002       // If this is an explicit specialization of a member that is a function
8003       // template, mark it as a member specialization.
8004       if (IsExplicitSpecialization &&
8005           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8006         NewTemplateDecl->setMemberSpecialization();
8007         assert(OldTemplateDecl->isMemberSpecialization());
8008       }
8009 
8010     } else {
8011       // This needs to happen first so that 'inline' propagates.
8012       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8013 
8014       if (isa<CXXMethodDecl>(NewFD))
8015         NewFD->setAccess(OldDecl->getAccess());
8016     }
8017   }
8018 
8019   // Semantic checking for this function declaration (in isolation).
8020 
8021   if (getLangOpts().CPlusPlus) {
8022     // C++-specific checks.
8023     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8024       CheckConstructor(Constructor);
8025     } else if (CXXDestructorDecl *Destructor =
8026                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8027       CXXRecordDecl *Record = Destructor->getParent();
8028       QualType ClassType = Context.getTypeDeclType(Record);
8029 
8030       // FIXME: Shouldn't we be able to perform this check even when the class
8031       // type is dependent? Both gcc and edg can handle that.
8032       if (!ClassType->isDependentType()) {
8033         DeclarationName Name
8034           = Context.DeclarationNames.getCXXDestructorName(
8035                                         Context.getCanonicalType(ClassType));
8036         if (NewFD->getDeclName() != Name) {
8037           Diag(NewFD->getLocation(), diag::err_destructor_name);
8038           NewFD->setInvalidDecl();
8039           return Redeclaration;
8040         }
8041       }
8042     } else if (CXXConversionDecl *Conversion
8043                = dyn_cast<CXXConversionDecl>(NewFD)) {
8044       ActOnConversionDeclarator(Conversion);
8045     }
8046 
8047     // Find any virtual functions that this function overrides.
8048     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8049       if (!Method->isFunctionTemplateSpecialization() &&
8050           !Method->getDescribedFunctionTemplate() &&
8051           Method->isCanonicalDecl()) {
8052         if (AddOverriddenMethods(Method->getParent(), Method)) {
8053           // If the function was marked as "static", we have a problem.
8054           if (NewFD->getStorageClass() == SC_Static) {
8055             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8056           }
8057         }
8058       }
8059 
8060       if (Method->isStatic())
8061         checkThisInStaticMemberFunctionType(Method);
8062     }
8063 
8064     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8065     if (NewFD->isOverloadedOperator() &&
8066         CheckOverloadedOperatorDeclaration(NewFD)) {
8067       NewFD->setInvalidDecl();
8068       return Redeclaration;
8069     }
8070 
8071     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8072     if (NewFD->getLiteralIdentifier() &&
8073         CheckLiteralOperatorDeclaration(NewFD)) {
8074       NewFD->setInvalidDecl();
8075       return Redeclaration;
8076     }
8077 
8078     // In C++, check default arguments now that we have merged decls. Unless
8079     // the lexical context is the class, because in this case this is done
8080     // during delayed parsing anyway.
8081     if (!CurContext->isRecord())
8082       CheckCXXDefaultArguments(NewFD);
8083 
8084     // If this function declares a builtin function, check the type of this
8085     // declaration against the expected type for the builtin.
8086     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8087       ASTContext::GetBuiltinTypeError Error;
8088       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8089       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8090       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8091         // The type of this function differs from the type of the builtin,
8092         // so forget about the builtin entirely.
8093         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
8094       }
8095     }
8096 
8097     // If this function is declared as being extern "C", then check to see if
8098     // the function returns a UDT (class, struct, or union type) that is not C
8099     // compatible, and if it does, warn the user.
8100     // But, issue any diagnostic on the first declaration only.
8101     if (Previous.empty() && NewFD->isExternC()) {
8102       QualType R = NewFD->getReturnType();
8103       if (R->isIncompleteType() && !R->isVoidType())
8104         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8105             << NewFD << R;
8106       else if (!R.isPODType(Context) && !R->isVoidType() &&
8107                !R->isObjCObjectPointerType())
8108         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8109     }
8110   }
8111   return Redeclaration;
8112 }
8113 
8114 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8115   // C++11 [basic.start.main]p3:
8116   //   A program that [...] declares main to be inline, static or
8117   //   constexpr is ill-formed.
8118   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8119   //   appear in a declaration of main.
8120   // static main is not an error under C99, but we should warn about it.
8121   // We accept _Noreturn main as an extension.
8122   if (FD->getStorageClass() == SC_Static)
8123     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8124          ? diag::err_static_main : diag::warn_static_main)
8125       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8126   if (FD->isInlineSpecified())
8127     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8128       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8129   if (DS.isNoreturnSpecified()) {
8130     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8131     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8132     Diag(NoreturnLoc, diag::ext_noreturn_main);
8133     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8134       << FixItHint::CreateRemoval(NoreturnRange);
8135   }
8136   if (FD->isConstexpr()) {
8137     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8138       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8139     FD->setConstexpr(false);
8140   }
8141 
8142   if (getLangOpts().OpenCL) {
8143     Diag(FD->getLocation(), diag::err_opencl_no_main)
8144         << FD->hasAttr<OpenCLKernelAttr>();
8145     FD->setInvalidDecl();
8146     return;
8147   }
8148 
8149   QualType T = FD->getType();
8150   assert(T->isFunctionType() && "function decl is not of function type");
8151   const FunctionType* FT = T->castAs<FunctionType>();
8152 
8153   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8154     // In C with GNU extensions we allow main() to have non-integer return
8155     // type, but we should warn about the extension, and we disable the
8156     // implicit-return-zero rule.
8157 
8158     // GCC in C mode accepts qualified 'int'.
8159     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8160       FD->setHasImplicitReturnZero(true);
8161     else {
8162       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8163       SourceRange RTRange = FD->getReturnTypeSourceRange();
8164       if (RTRange.isValid())
8165         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8166             << FixItHint::CreateReplacement(RTRange, "int");
8167     }
8168   } else {
8169     // In C and C++, main magically returns 0 if you fall off the end;
8170     // set the flag which tells us that.
8171     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8172 
8173     // All the standards say that main() should return 'int'.
8174     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8175       FD->setHasImplicitReturnZero(true);
8176     else {
8177       // Otherwise, this is just a flat-out error.
8178       SourceRange RTRange = FD->getReturnTypeSourceRange();
8179       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8180           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8181                                 : FixItHint());
8182       FD->setInvalidDecl(true);
8183     }
8184   }
8185 
8186   // Treat protoless main() as nullary.
8187   if (isa<FunctionNoProtoType>(FT)) return;
8188 
8189   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8190   unsigned nparams = FTP->getNumParams();
8191   assert(FD->getNumParams() == nparams);
8192 
8193   bool HasExtraParameters = (nparams > 3);
8194 
8195   // Darwin passes an undocumented fourth argument of type char**.  If
8196   // other platforms start sprouting these, the logic below will start
8197   // getting shifty.
8198   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8199     HasExtraParameters = false;
8200 
8201   if (HasExtraParameters) {
8202     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8203     FD->setInvalidDecl(true);
8204     nparams = 3;
8205   }
8206 
8207   // FIXME: a lot of the following diagnostics would be improved
8208   // if we had some location information about types.
8209 
8210   QualType CharPP =
8211     Context.getPointerType(Context.getPointerType(Context.CharTy));
8212   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8213 
8214   for (unsigned i = 0; i < nparams; ++i) {
8215     QualType AT = FTP->getParamType(i);
8216 
8217     bool mismatch = true;
8218 
8219     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8220       mismatch = false;
8221     else if (Expected[i] == CharPP) {
8222       // As an extension, the following forms are okay:
8223       //   char const **
8224       //   char const * const *
8225       //   char * const *
8226 
8227       QualifierCollector qs;
8228       const PointerType* PT;
8229       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8230           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8231           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8232                               Context.CharTy)) {
8233         qs.removeConst();
8234         mismatch = !qs.empty();
8235       }
8236     }
8237 
8238     if (mismatch) {
8239       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8240       // TODO: suggest replacing given type with expected type
8241       FD->setInvalidDecl(true);
8242     }
8243   }
8244 
8245   if (nparams == 1 && !FD->isInvalidDecl()) {
8246     Diag(FD->getLocation(), diag::warn_main_one_arg);
8247   }
8248 
8249   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8250     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8251     FD->setInvalidDecl();
8252   }
8253 }
8254 
8255 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8256   QualType T = FD->getType();
8257   assert(T->isFunctionType() && "function decl is not of function type");
8258   const FunctionType *FT = T->castAs<FunctionType>();
8259 
8260   // Set an implicit return of 'zero' if the function can return some integral,
8261   // enumeration, pointer or nullptr type.
8262   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8263       FT->getReturnType()->isAnyPointerType() ||
8264       FT->getReturnType()->isNullPtrType())
8265     // DllMain is exempt because a return value of zero means it failed.
8266     if (FD->getName() != "DllMain")
8267       FD->setHasImplicitReturnZero(true);
8268 
8269   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8270     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8271     FD->setInvalidDecl();
8272   }
8273 }
8274 
8275 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8276   // FIXME: Need strict checking.  In C89, we need to check for
8277   // any assignment, increment, decrement, function-calls, or
8278   // commas outside of a sizeof.  In C99, it's the same list,
8279   // except that the aforementioned are allowed in unevaluated
8280   // expressions.  Everything else falls under the
8281   // "may accept other forms of constant expressions" exception.
8282   // (We never end up here for C++, so the constant expression
8283   // rules there don't matter.)
8284   const Expr *Culprit;
8285   if (Init->isConstantInitializer(Context, false, &Culprit))
8286     return false;
8287   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8288     << Culprit->getSourceRange();
8289   return true;
8290 }
8291 
8292 namespace {
8293   // Visits an initialization expression to see if OrigDecl is evaluated in
8294   // its own initialization and throws a warning if it does.
8295   class SelfReferenceChecker
8296       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8297     Sema &S;
8298     Decl *OrigDecl;
8299     bool isRecordType;
8300     bool isPODType;
8301     bool isReferenceType;
8302 
8303     bool isInitList;
8304     llvm::SmallVector<unsigned, 4> InitFieldIndex;
8305   public:
8306     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8307 
8308     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8309                                                     S(S), OrigDecl(OrigDecl) {
8310       isPODType = false;
8311       isRecordType = false;
8312       isReferenceType = false;
8313       isInitList = false;
8314       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8315         isPODType = VD->getType().isPODType(S.Context);
8316         isRecordType = VD->getType()->isRecordType();
8317         isReferenceType = VD->getType()->isReferenceType();
8318       }
8319     }
8320 
8321     // For most expressions, just call the visitor.  For initializer lists,
8322     // track the index of the field being initialized since fields are
8323     // initialized in order allowing use of previously initialized fields.
8324     void CheckExpr(Expr *E) {
8325       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8326       if (!InitList) {
8327         Visit(E);
8328         return;
8329       }
8330 
8331       // Track and increment the index here.
8332       isInitList = true;
8333       InitFieldIndex.push_back(0);
8334       for (auto Child : InitList->children()) {
8335         CheckExpr(cast<Expr>(Child));
8336         ++InitFieldIndex.back();
8337       }
8338       InitFieldIndex.pop_back();
8339     }
8340 
8341     // Returns true if MemberExpr is checked and no futher checking is needed.
8342     // Returns false if additional checking is required.
8343     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8344       llvm::SmallVector<FieldDecl*, 4> Fields;
8345       Expr *Base = E;
8346       bool ReferenceField = false;
8347 
8348       // Get the field memebers used.
8349       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8350         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8351         if (!FD)
8352           return false;
8353         Fields.push_back(FD);
8354         if (FD->getType()->isReferenceType())
8355           ReferenceField = true;
8356         Base = ME->getBase()->IgnoreParenImpCasts();
8357       }
8358 
8359       // Keep checking only if the base Decl is the same.
8360       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8361       if (!DRE || DRE->getDecl() != OrigDecl)
8362         return false;
8363 
8364       // A reference field can be bound to an unininitialized field.
8365       if (CheckReference && !ReferenceField)
8366         return true;
8367 
8368       // Convert FieldDecls to their index number.
8369       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8370       for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) {
8371         UsedFieldIndex.push_back((*I)->getFieldIndex());
8372       }
8373 
8374       // See if a warning is needed by checking the first difference in index
8375       // numbers.  If field being used has index less than the field being
8376       // initialized, then the use is safe.
8377       for (auto UsedIter = UsedFieldIndex.begin(),
8378                 UsedEnd = UsedFieldIndex.end(),
8379                 OrigIter = InitFieldIndex.begin(),
8380                 OrigEnd = InitFieldIndex.end();
8381            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8382         if (*UsedIter < *OrigIter)
8383           return true;
8384         if (*UsedIter > *OrigIter)
8385           break;
8386       }
8387 
8388       // TODO: Add a different warning which will print the field names.
8389       HandleDeclRefExpr(DRE);
8390       return true;
8391     }
8392 
8393     // For most expressions, the cast is directly above the DeclRefExpr.
8394     // For conditional operators, the cast can be outside the conditional
8395     // operator if both expressions are DeclRefExpr's.
8396     void HandleValue(Expr *E) {
8397       E = E->IgnoreParens();
8398       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8399         HandleDeclRefExpr(DRE);
8400         return;
8401       }
8402 
8403       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8404         Visit(CO->getCond());
8405         HandleValue(CO->getTrueExpr());
8406         HandleValue(CO->getFalseExpr());
8407         return;
8408       }
8409 
8410       if (BinaryConditionalOperator *BCO =
8411               dyn_cast<BinaryConditionalOperator>(E)) {
8412         Visit(BCO->getCond());
8413         HandleValue(BCO->getFalseExpr());
8414         return;
8415       }
8416 
8417       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8418         HandleValue(OVE->getSourceExpr());
8419         return;
8420       }
8421 
8422       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8423         if (BO->getOpcode() == BO_Comma) {
8424           Visit(BO->getLHS());
8425           HandleValue(BO->getRHS());
8426           return;
8427         }
8428       }
8429 
8430       if (isa<MemberExpr>(E)) {
8431         if (isInitList) {
8432           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
8433                                       false /*CheckReference*/))
8434             return;
8435         }
8436 
8437         Expr *Base = E->IgnoreParenImpCasts();
8438         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8439           // Check for static member variables and don't warn on them.
8440           if (!isa<FieldDecl>(ME->getMemberDecl()))
8441             return;
8442           Base = ME->getBase()->IgnoreParenImpCasts();
8443         }
8444         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8445           HandleDeclRefExpr(DRE);
8446         return;
8447       }
8448 
8449       Visit(E);
8450     }
8451 
8452     // Reference types not handled in HandleValue are handled here since all
8453     // uses of references are bad, not just r-value uses.
8454     void VisitDeclRefExpr(DeclRefExpr *E) {
8455       if (isReferenceType)
8456         HandleDeclRefExpr(E);
8457     }
8458 
8459     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8460       if (E->getCastKind() == CK_LValueToRValue) {
8461         HandleValue(E->getSubExpr());
8462         return;
8463       }
8464 
8465       Inherited::VisitImplicitCastExpr(E);
8466     }
8467 
8468     void VisitMemberExpr(MemberExpr *E) {
8469       if (isInitList) {
8470         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
8471           return;
8472       }
8473 
8474       // Don't warn on arrays since they can be treated as pointers.
8475       if (E->getType()->canDecayToPointerType()) return;
8476 
8477       // Warn when a non-static method call is followed by non-static member
8478       // field accesses, which is followed by a DeclRefExpr.
8479       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8480       bool Warn = (MD && !MD->isStatic());
8481       Expr *Base = E->getBase()->IgnoreParenImpCasts();
8482       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8483         if (!isa<FieldDecl>(ME->getMemberDecl()))
8484           Warn = false;
8485         Base = ME->getBase()->IgnoreParenImpCasts();
8486       }
8487 
8488       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8489         if (Warn)
8490           HandleDeclRefExpr(DRE);
8491         return;
8492       }
8493 
8494       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8495       // Visit that expression.
8496       Visit(Base);
8497     }
8498 
8499     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8500       Expr *Callee = E->getCallee();
8501 
8502       if (isa<UnresolvedLookupExpr>(Callee))
8503         return Inherited::VisitCXXOperatorCallExpr(E);
8504 
8505       Visit(Callee);
8506       for (auto Arg: E->arguments())
8507         HandleValue(Arg->IgnoreParenImpCasts());
8508     }
8509 
8510     void VisitUnaryOperator(UnaryOperator *E) {
8511       // For POD record types, addresses of its own members are well-defined.
8512       if (E->getOpcode() == UO_AddrOf && isRecordType &&
8513           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8514         if (!isPODType)
8515           HandleValue(E->getSubExpr());
8516         return;
8517       }
8518 
8519       if (E->isIncrementDecrementOp()) {
8520         HandleValue(E->getSubExpr());
8521         return;
8522       }
8523 
8524       Inherited::VisitUnaryOperator(E);
8525     }
8526 
8527     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8528 
8529     void VisitCXXConstructExpr(CXXConstructExpr *E) {
8530       if (E->getConstructor()->isCopyConstructor()) {
8531         Expr *ArgExpr = E->getArg(0);
8532         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
8533           if (ILE->getNumInits() == 1)
8534             ArgExpr = ILE->getInit(0);
8535         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8536           if (ICE->getCastKind() == CK_NoOp)
8537             ArgExpr = ICE->getSubExpr();
8538         HandleValue(ArgExpr);
8539         return;
8540       }
8541       Inherited::VisitCXXConstructExpr(E);
8542     }
8543 
8544     void VisitCallExpr(CallExpr *E) {
8545       // Treat std::move as a use.
8546       if (E->getNumArgs() == 1) {
8547         if (FunctionDecl *FD = E->getDirectCallee()) {
8548           if (FD->isInStdNamespace() && FD->getIdentifier() &&
8549               FD->getIdentifier()->isStr("move")) {
8550             HandleValue(E->getArg(0));
8551             return;
8552           }
8553         }
8554       }
8555 
8556       Inherited::VisitCallExpr(E);
8557     }
8558 
8559     void VisitBinaryOperator(BinaryOperator *E) {
8560       if (E->isCompoundAssignmentOp()) {
8561         HandleValue(E->getLHS());
8562         Visit(E->getRHS());
8563         return;
8564       }
8565 
8566       Inherited::VisitBinaryOperator(E);
8567     }
8568 
8569     // A custom visitor for BinaryConditionalOperator is needed because the
8570     // regular visitor would check the condition and true expression separately
8571     // but both point to the same place giving duplicate diagnostics.
8572     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
8573       Visit(E->getCond());
8574       Visit(E->getFalseExpr());
8575     }
8576 
8577     void HandleDeclRefExpr(DeclRefExpr *DRE) {
8578       Decl* ReferenceDecl = DRE->getDecl();
8579       if (OrigDecl != ReferenceDecl) return;
8580       unsigned diag;
8581       if (isReferenceType) {
8582         diag = diag::warn_uninit_self_reference_in_reference_init;
8583       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8584         diag = diag::warn_static_self_reference_in_init;
8585       } else {
8586         diag = diag::warn_uninit_self_reference_in_init;
8587       }
8588 
8589       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
8590                             S.PDiag(diag)
8591                               << DRE->getNameInfo().getName()
8592                               << OrigDecl->getLocation()
8593                               << DRE->getSourceRange());
8594     }
8595   };
8596 
8597   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8598   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8599                                  bool DirectInit) {
8600     // Parameters arguments are occassionially constructed with itself,
8601     // for instance, in recursive functions.  Skip them.
8602     if (isa<ParmVarDecl>(OrigDecl))
8603       return;
8604 
8605     E = E->IgnoreParens();
8606 
8607     // Skip checking T a = a where T is not a record or reference type.
8608     // Doing so is a way to silence uninitialized warnings.
8609     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8610       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8611         if (ICE->getCastKind() == CK_LValueToRValue)
8612           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8613             if (DRE->getDecl() == OrigDecl)
8614               return;
8615 
8616     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
8617   }
8618 }
8619 
8620 /// AddInitializerToDecl - Adds the initializer Init to the
8621 /// declaration dcl. If DirectInit is true, this is C++ direct
8622 /// initialization rather than copy initialization.
8623 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8624                                 bool DirectInit, bool TypeMayContainAuto) {
8625   // If there is no declaration, there was an error parsing it.  Just ignore
8626   // the initializer.
8627   if (!RealDecl || RealDecl->isInvalidDecl()) {
8628     CorrectDelayedTyposInExpr(Init);
8629     return;
8630   }
8631 
8632   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8633     // With declarators parsed the way they are, the parser cannot
8634     // distinguish between a normal initializer and a pure-specifier.
8635     // Thus this grotesque test.
8636     IntegerLiteral *IL;
8637     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
8638         Context.getCanonicalType(IL->getType()) == Context.IntTy)
8639       CheckPureMethod(Method, Init->getSourceRange());
8640     else {
8641       Diag(Method->getLocation(), diag::err_member_function_initialization)
8642         << Method->getDeclName() << Init->getSourceRange();
8643       Method->setInvalidDecl();
8644     }
8645     return;
8646   }
8647 
8648   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8649   if (!VDecl) {
8650     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8651     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8652     RealDecl->setInvalidDecl();
8653     return;
8654   }
8655   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8656 
8657   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8658   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
8659     Expr *DeduceInit = Init;
8660     // Initializer could be a C++ direct-initializer. Deduction only works if it
8661     // contains exactly one expression.
8662     if (CXXDirectInit) {
8663       if (CXXDirectInit->getNumExprs() == 0) {
8664         // It isn't possible to write this directly, but it is possible to
8665         // end up in this situation with "auto x(some_pack...);"
8666         Diag(CXXDirectInit->getLocStart(),
8667              VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8668                                     : diag::err_auto_var_init_no_expression)
8669           << VDecl->getDeclName() << VDecl->getType()
8670           << VDecl->getSourceRange();
8671         RealDecl->setInvalidDecl();
8672         return;
8673       } else if (CXXDirectInit->getNumExprs() > 1) {
8674         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
8675              VDecl->isInitCapture()
8676                  ? diag::err_init_capture_multiple_expressions
8677                  : diag::err_auto_var_init_multiple_expressions)
8678           << VDecl->getDeclName() << VDecl->getType()
8679           << VDecl->getSourceRange();
8680         RealDecl->setInvalidDecl();
8681         return;
8682       } else {
8683         DeduceInit = CXXDirectInit->getExpr(0);
8684         if (isa<InitListExpr>(DeduceInit))
8685           Diag(CXXDirectInit->getLocStart(),
8686                diag::err_auto_var_init_paren_braces)
8687             << VDecl->getDeclName() << VDecl->getType()
8688             << VDecl->getSourceRange();
8689       }
8690     }
8691 
8692     // Expressions default to 'id' when we're in a debugger.
8693     bool DefaultedToAuto = false;
8694     if (getLangOpts().DebuggerCastResultToId &&
8695         Init->getType() == Context.UnknownAnyTy) {
8696       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8697       if (Result.isInvalid()) {
8698         VDecl->setInvalidDecl();
8699         return;
8700       }
8701       Init = Result.get();
8702       DefaultedToAuto = true;
8703     }
8704 
8705     QualType DeducedType;
8706     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8707             DAR_Failed)
8708       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8709     if (DeducedType.isNull()) {
8710       RealDecl->setInvalidDecl();
8711       return;
8712     }
8713     VDecl->setType(DeducedType);
8714     assert(VDecl->isLinkageValid());
8715 
8716     // In ARC, infer lifetime.
8717     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8718       VDecl->setInvalidDecl();
8719 
8720     // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8721     // 'id' instead of a specific object type prevents most of our usual checks.
8722     // We only want to warn outside of template instantiations, though:
8723     // inside a template, the 'id' could have come from a parameter.
8724     if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8725         DeducedType->isObjCIdType()) {
8726       SourceLocation Loc =
8727           VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
8728       Diag(Loc, diag::warn_auto_var_is_id)
8729         << VDecl->getDeclName() << DeduceInit->getSourceRange();
8730     }
8731 
8732     // If this is a redeclaration, check that the type we just deduced matches
8733     // the previously declared type.
8734     if (VarDecl *Old = VDecl->getPreviousDecl()) {
8735       // We never need to merge the type, because we cannot form an incomplete
8736       // array of auto, nor deduce such a type.
8737       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8738     }
8739 
8740     // Check the deduced type is valid for a variable declaration.
8741     CheckVariableDeclarationType(VDecl);
8742     if (VDecl->isInvalidDecl())
8743       return;
8744 
8745     // If all looks well, warn if this is a case that will change meaning when
8746     // we implement N3922.
8747     if (DirectInit && !CXXDirectInit && isa<InitListExpr>(Init)) {
8748       Diag(Init->getLocStart(),
8749            diag::warn_auto_var_direct_list_init)
8750         << FixItHint::CreateInsertion(Init->getLocStart(), "=");
8751     }
8752   }
8753 
8754   // dllimport cannot be used on variable definitions.
8755   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8756     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8757     VDecl->setInvalidDecl();
8758     return;
8759   }
8760 
8761   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8762     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8763     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8764     VDecl->setInvalidDecl();
8765     return;
8766   }
8767 
8768   if (!VDecl->getType()->isDependentType()) {
8769     // A definition must end up with a complete type, which means it must be
8770     // complete with the restriction that an array type might be completed by
8771     // the initializer; note that later code assumes this restriction.
8772     QualType BaseDeclType = VDecl->getType();
8773     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8774       BaseDeclType = Array->getElementType();
8775     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8776                             diag::err_typecheck_decl_incomplete_type)) {
8777       RealDecl->setInvalidDecl();
8778       return;
8779     }
8780 
8781     // The variable can not have an abstract class type.
8782     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8783                                diag::err_abstract_type_in_decl,
8784                                AbstractVariableType))
8785       VDecl->setInvalidDecl();
8786   }
8787 
8788   const VarDecl *Def;
8789   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8790     Diag(VDecl->getLocation(), diag::err_redefinition)
8791       << VDecl->getDeclName();
8792     Diag(Def->getLocation(), diag::note_previous_definition);
8793     VDecl->setInvalidDecl();
8794     return;
8795   }
8796 
8797   const VarDecl *PrevInit = nullptr;
8798   if (getLangOpts().CPlusPlus) {
8799     // C++ [class.static.data]p4
8800     //   If a static data member is of const integral or const
8801     //   enumeration type, its declaration in the class definition can
8802     //   specify a constant-initializer which shall be an integral
8803     //   constant expression (5.19). In that case, the member can appear
8804     //   in integral constant expressions. The member shall still be
8805     //   defined in a namespace scope if it is used in the program and the
8806     //   namespace scope definition shall not contain an initializer.
8807     //
8808     // We already performed a redefinition check above, but for static
8809     // data members we also need to check whether there was an in-class
8810     // declaration with an initializer.
8811     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8812       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8813           << VDecl->getDeclName();
8814       Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
8815       return;
8816     }
8817 
8818     if (VDecl->hasLocalStorage())
8819       getCurFunction()->setHasBranchProtectedScope();
8820 
8821     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8822       VDecl->setInvalidDecl();
8823       return;
8824     }
8825   }
8826 
8827   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8828   // a kernel function cannot be initialized."
8829   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8830     Diag(VDecl->getLocation(), diag::err_local_cant_init);
8831     VDecl->setInvalidDecl();
8832     return;
8833   }
8834 
8835   // Get the decls type and save a reference for later, since
8836   // CheckInitializerTypes may change it.
8837   QualType DclT = VDecl->getType(), SavT = DclT;
8838 
8839   // Expressions default to 'id' when we're in a debugger
8840   // and we are assigning it to a variable of Objective-C pointer type.
8841   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8842       Init->getType() == Context.UnknownAnyTy) {
8843     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8844     if (Result.isInvalid()) {
8845       VDecl->setInvalidDecl();
8846       return;
8847     }
8848     Init = Result.get();
8849   }
8850 
8851   // Perform the initialization.
8852   if (!VDecl->isInvalidDecl()) {
8853     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8854     InitializationKind Kind
8855       = DirectInit ?
8856           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8857                                                            Init->getLocStart(),
8858                                                            Init->getLocEnd())
8859                         : InitializationKind::CreateDirectList(
8860                                                           VDecl->getLocation())
8861                    : InitializationKind::CreateCopy(VDecl->getLocation(),
8862                                                     Init->getLocStart());
8863 
8864     MultiExprArg Args = Init;
8865     if (CXXDirectInit)
8866       Args = MultiExprArg(CXXDirectInit->getExprs(),
8867                           CXXDirectInit->getNumExprs());
8868 
8869     // Try to correct any TypoExprs in the initialization arguments.
8870     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
8871       ExprResult Res =
8872           CorrectDelayedTyposInExpr(Args[Idx], [this, Entity, Kind](Expr *E) {
8873             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
8874             return Init.Failed() ? ExprError() : E;
8875           });
8876       if (Res.isInvalid()) {
8877         VDecl->setInvalidDecl();
8878       } else if (Res.get() != Args[Idx]) {
8879         Args[Idx] = Res.get();
8880       }
8881     }
8882     if (VDecl->isInvalidDecl())
8883       return;
8884 
8885     InitializationSequence InitSeq(*this, Entity, Kind, Args);
8886     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
8887     if (Result.isInvalid()) {
8888       VDecl->setInvalidDecl();
8889       return;
8890     }
8891 
8892     Init = Result.getAs<Expr>();
8893   }
8894 
8895   // Check for self-references within variable initializers.
8896   // Variables declared within a function/method body (except for references)
8897   // are handled by a dataflow analysis.
8898   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8899       VDecl->getType()->isReferenceType()) {
8900     CheckSelfReference(*this, RealDecl, Init, DirectInit);
8901   }
8902 
8903   // If the type changed, it means we had an incomplete type that was
8904   // completed by the initializer. For example:
8905   //   int ary[] = { 1, 3, 5 };
8906   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
8907   if (!VDecl->isInvalidDecl() && (DclT != SavT))
8908     VDecl->setType(DclT);
8909 
8910   if (!VDecl->isInvalidDecl()) {
8911     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8912 
8913     if (VDecl->hasAttr<BlocksAttr>())
8914       checkRetainCycles(VDecl, Init);
8915 
8916     // It is safe to assign a weak reference into a strong variable.
8917     // Although this code can still have problems:
8918     //   id x = self.weakProp;
8919     //   id y = self.weakProp;
8920     // we do not warn to warn spuriously when 'x' and 'y' are on separate
8921     // paths through the function. This should be revisited if
8922     // -Wrepeated-use-of-weak is made flow-sensitive.
8923     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
8924         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
8925                          Init->getLocStart()))
8926         getCurFunction()->markSafeWeakUse(Init);
8927   }
8928 
8929   // The initialization is usually a full-expression.
8930   //
8931   // FIXME: If this is a braced initialization of an aggregate, it is not
8932   // an expression, and each individual field initializer is a separate
8933   // full-expression. For instance, in:
8934   //
8935   //   struct Temp { ~Temp(); };
8936   //   struct S { S(Temp); };
8937   //   struct T { S a, b; } t = { Temp(), Temp() }
8938   //
8939   // we should destroy the first Temp before constructing the second.
8940   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8941                                           false,
8942                                           VDecl->isConstexpr());
8943   if (Result.isInvalid()) {
8944     VDecl->setInvalidDecl();
8945     return;
8946   }
8947   Init = Result.get();
8948 
8949   // Attach the initializer to the decl.
8950   VDecl->setInit(Init);
8951 
8952   if (VDecl->isLocalVarDecl()) {
8953     // C99 6.7.8p4: All the expressions in an initializer for an object that has
8954     // static storage duration shall be constant expressions or string literals.
8955     // C++ does not have this restriction.
8956     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8957       const Expr *Culprit;
8958       if (VDecl->getStorageClass() == SC_Static)
8959         CheckForConstantInitializer(Init, DclT);
8960       // C89 is stricter than C99 for non-static aggregate types.
8961       // C89 6.5.7p3: All the expressions [...] in an initializer list
8962       // for an object that has aggregate or union type shall be
8963       // constant expressions.
8964       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
8965                isa<InitListExpr>(Init) &&
8966                !Init->isConstantInitializer(Context, false, &Culprit))
8967         Diag(Culprit->getExprLoc(),
8968              diag::ext_aggregate_init_not_constant)
8969           << Culprit->getSourceRange();
8970     }
8971   } else if (VDecl->isStaticDataMember() &&
8972              VDecl->getLexicalDeclContext()->isRecord()) {
8973     // This is an in-class initialization for a static data member, e.g.,
8974     //
8975     // struct S {
8976     //   static const int value = 17;
8977     // };
8978 
8979     // C++ [class.mem]p4:
8980     //   A member-declarator can contain a constant-initializer only
8981     //   if it declares a static member (9.4) of const integral or
8982     //   const enumeration type, see 9.4.2.
8983     //
8984     // C++11 [class.static.data]p3:
8985     //   If a non-volatile const static data member is of integral or
8986     //   enumeration type, its declaration in the class definition can
8987     //   specify a brace-or-equal-initializer in which every initalizer-clause
8988     //   that is an assignment-expression is a constant expression. A static
8989     //   data member of literal type can be declared in the class definition
8990     //   with the constexpr specifier; if so, its declaration shall specify a
8991     //   brace-or-equal-initializer in which every initializer-clause that is
8992     //   an assignment-expression is a constant expression.
8993 
8994     // Do nothing on dependent types.
8995     if (DclT->isDependentType()) {
8996 
8997     // Allow any 'static constexpr' members, whether or not they are of literal
8998     // type. We separately check that every constexpr variable is of literal
8999     // type.
9000     } else if (VDecl->isConstexpr()) {
9001 
9002     // Require constness.
9003     } else if (!DclT.isConstQualified()) {
9004       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9005         << Init->getSourceRange();
9006       VDecl->setInvalidDecl();
9007 
9008     // We allow integer constant expressions in all cases.
9009     } else if (DclT->isIntegralOrEnumerationType()) {
9010       // Check whether the expression is a constant expression.
9011       SourceLocation Loc;
9012       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9013         // In C++11, a non-constexpr const static data member with an
9014         // in-class initializer cannot be volatile.
9015         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9016       else if (Init->isValueDependent())
9017         ; // Nothing to check.
9018       else if (Init->isIntegerConstantExpr(Context, &Loc))
9019         ; // Ok, it's an ICE!
9020       else if (Init->isEvaluatable(Context)) {
9021         // If we can constant fold the initializer through heroics, accept it,
9022         // but report this as a use of an extension for -pedantic.
9023         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9024           << Init->getSourceRange();
9025       } else {
9026         // Otherwise, this is some crazy unknown case.  Report the issue at the
9027         // location provided by the isIntegerConstantExpr failed check.
9028         Diag(Loc, diag::err_in_class_initializer_non_constant)
9029           << Init->getSourceRange();
9030         VDecl->setInvalidDecl();
9031       }
9032 
9033     // We allow foldable floating-point constants as an extension.
9034     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9035       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9036       // it anyway and provide a fixit to add the 'constexpr'.
9037       if (getLangOpts().CPlusPlus11) {
9038         Diag(VDecl->getLocation(),
9039              diag::ext_in_class_initializer_float_type_cxx11)
9040             << DclT << Init->getSourceRange();
9041         Diag(VDecl->getLocStart(),
9042              diag::note_in_class_initializer_float_type_cxx11)
9043             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9044       } else {
9045         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9046           << DclT << Init->getSourceRange();
9047 
9048         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9049           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9050             << Init->getSourceRange();
9051           VDecl->setInvalidDecl();
9052         }
9053       }
9054 
9055     // Suggest adding 'constexpr' in C++11 for literal types.
9056     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9057       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9058         << DclT << Init->getSourceRange()
9059         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9060       VDecl->setConstexpr(true);
9061 
9062     } else {
9063       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9064         << DclT << Init->getSourceRange();
9065       VDecl->setInvalidDecl();
9066     }
9067   } else if (VDecl->isFileVarDecl()) {
9068     if (VDecl->getStorageClass() == SC_Extern &&
9069         (!getLangOpts().CPlusPlus ||
9070          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9071            VDecl->isExternC())) &&
9072         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9073       Diag(VDecl->getLocation(), diag::warn_extern_init);
9074 
9075     // C99 6.7.8p4. All file scoped initializers need to be constant.
9076     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9077       CheckForConstantInitializer(Init, DclT);
9078   }
9079 
9080   // We will represent direct-initialization similarly to copy-initialization:
9081   //    int x(1);  -as-> int x = 1;
9082   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9083   //
9084   // Clients that want to distinguish between the two forms, can check for
9085   // direct initializer using VarDecl::getInitStyle().
9086   // A major benefit is that clients that don't particularly care about which
9087   // exactly form was it (like the CodeGen) can handle both cases without
9088   // special case code.
9089 
9090   // C++ 8.5p11:
9091   // The form of initialization (using parentheses or '=') is generally
9092   // insignificant, but does matter when the entity being initialized has a
9093   // class type.
9094   if (CXXDirectInit) {
9095     assert(DirectInit && "Call-style initializer must be direct init.");
9096     VDecl->setInitStyle(VarDecl::CallInit);
9097   } else if (DirectInit) {
9098     // This must be list-initialization. No other way is direct-initialization.
9099     VDecl->setInitStyle(VarDecl::ListInit);
9100   }
9101 
9102   CheckCompleteVariableDeclaration(VDecl);
9103 }
9104 
9105 /// ActOnInitializerError - Given that there was an error parsing an
9106 /// initializer for the given declaration, try to return to some form
9107 /// of sanity.
9108 void Sema::ActOnInitializerError(Decl *D) {
9109   // Our main concern here is re-establishing invariants like "a
9110   // variable's type is either dependent or complete".
9111   if (!D || D->isInvalidDecl()) return;
9112 
9113   VarDecl *VD = dyn_cast<VarDecl>(D);
9114   if (!VD) return;
9115 
9116   // Auto types are meaningless if we can't make sense of the initializer.
9117   if (ParsingInitForAutoVars.count(D)) {
9118     D->setInvalidDecl();
9119     return;
9120   }
9121 
9122   QualType Ty = VD->getType();
9123   if (Ty->isDependentType()) return;
9124 
9125   // Require a complete type.
9126   if (RequireCompleteType(VD->getLocation(),
9127                           Context.getBaseElementType(Ty),
9128                           diag::err_typecheck_decl_incomplete_type)) {
9129     VD->setInvalidDecl();
9130     return;
9131   }
9132 
9133   // Require a non-abstract type.
9134   if (RequireNonAbstractType(VD->getLocation(), Ty,
9135                              diag::err_abstract_type_in_decl,
9136                              AbstractVariableType)) {
9137     VD->setInvalidDecl();
9138     return;
9139   }
9140 
9141   // Don't bother complaining about constructors or destructors,
9142   // though.
9143 }
9144 
9145 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9146                                   bool TypeMayContainAuto) {
9147   // If there is no declaration, there was an error parsing it. Just ignore it.
9148   if (!RealDecl)
9149     return;
9150 
9151   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9152     QualType Type = Var->getType();
9153 
9154     // C++11 [dcl.spec.auto]p3
9155     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9156       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9157         << Var->getDeclName() << Type;
9158       Var->setInvalidDecl();
9159       return;
9160     }
9161 
9162     // C++11 [class.static.data]p3: A static data member can be declared with
9163     // the constexpr specifier; if so, its declaration shall specify
9164     // a brace-or-equal-initializer.
9165     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9166     // the definition of a variable [...] or the declaration of a static data
9167     // member.
9168     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9169       if (Var->isStaticDataMember())
9170         Diag(Var->getLocation(),
9171              diag::err_constexpr_static_mem_var_requires_init)
9172           << Var->getDeclName();
9173       else
9174         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9175       Var->setInvalidDecl();
9176       return;
9177     }
9178 
9179     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9180     // be initialized.
9181     if (!Var->isInvalidDecl() &&
9182         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9183         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9184       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9185       Var->setInvalidDecl();
9186       return;
9187     }
9188 
9189     switch (Var->isThisDeclarationADefinition()) {
9190     case VarDecl::Definition:
9191       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9192         break;
9193 
9194       // We have an out-of-line definition of a static data member
9195       // that has an in-class initializer, so we type-check this like
9196       // a declaration.
9197       //
9198       // Fall through
9199 
9200     case VarDecl::DeclarationOnly:
9201       // It's only a declaration.
9202 
9203       // Block scope. C99 6.7p7: If an identifier for an object is
9204       // declared with no linkage (C99 6.2.2p6), the type for the
9205       // object shall be complete.
9206       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9207           !Var->hasLinkage() && !Var->isInvalidDecl() &&
9208           RequireCompleteType(Var->getLocation(), Type,
9209                               diag::err_typecheck_decl_incomplete_type))
9210         Var->setInvalidDecl();
9211 
9212       // Make sure that the type is not abstract.
9213       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9214           RequireNonAbstractType(Var->getLocation(), Type,
9215                                  diag::err_abstract_type_in_decl,
9216                                  AbstractVariableType))
9217         Var->setInvalidDecl();
9218       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9219           Var->getStorageClass() == SC_PrivateExtern) {
9220         Diag(Var->getLocation(), diag::warn_private_extern);
9221         Diag(Var->getLocation(), diag::note_private_extern);
9222       }
9223 
9224       return;
9225 
9226     case VarDecl::TentativeDefinition:
9227       // File scope. C99 6.9.2p2: A declaration of an identifier for an
9228       // object that has file scope without an initializer, and without a
9229       // storage-class specifier or with the storage-class specifier "static",
9230       // constitutes a tentative definition. Note: A tentative definition with
9231       // external linkage is valid (C99 6.2.2p5).
9232       if (!Var->isInvalidDecl()) {
9233         if (const IncompleteArrayType *ArrayT
9234                                     = Context.getAsIncompleteArrayType(Type)) {
9235           if (RequireCompleteType(Var->getLocation(),
9236                                   ArrayT->getElementType(),
9237                                   diag::err_illegal_decl_array_incomplete_type))
9238             Var->setInvalidDecl();
9239         } else if (Var->getStorageClass() == SC_Static) {
9240           // C99 6.9.2p3: If the declaration of an identifier for an object is
9241           // a tentative definition and has internal linkage (C99 6.2.2p3), the
9242           // declared type shall not be an incomplete type.
9243           // NOTE: code such as the following
9244           //     static struct s;
9245           //     struct s { int a; };
9246           // is accepted by gcc. Hence here we issue a warning instead of
9247           // an error and we do not invalidate the static declaration.
9248           // NOTE: to avoid multiple warnings, only check the first declaration.
9249           if (Var->isFirstDecl())
9250             RequireCompleteType(Var->getLocation(), Type,
9251                                 diag::ext_typecheck_decl_incomplete_type);
9252         }
9253       }
9254 
9255       // Record the tentative definition; we're done.
9256       if (!Var->isInvalidDecl())
9257         TentativeDefinitions.push_back(Var);
9258       return;
9259     }
9260 
9261     // Provide a specific diagnostic for uninitialized variable
9262     // definitions with incomplete array type.
9263     if (Type->isIncompleteArrayType()) {
9264       Diag(Var->getLocation(),
9265            diag::err_typecheck_incomplete_array_needs_initializer);
9266       Var->setInvalidDecl();
9267       return;
9268     }
9269 
9270     // Provide a specific diagnostic for uninitialized variable
9271     // definitions with reference type.
9272     if (Type->isReferenceType()) {
9273       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9274         << Var->getDeclName()
9275         << SourceRange(Var->getLocation(), Var->getLocation());
9276       Var->setInvalidDecl();
9277       return;
9278     }
9279 
9280     // Do not attempt to type-check the default initializer for a
9281     // variable with dependent type.
9282     if (Type->isDependentType())
9283       return;
9284 
9285     if (Var->isInvalidDecl())
9286       return;
9287 
9288     if (!Var->hasAttr<AliasAttr>()) {
9289       if (RequireCompleteType(Var->getLocation(),
9290                               Context.getBaseElementType(Type),
9291                               diag::err_typecheck_decl_incomplete_type)) {
9292         Var->setInvalidDecl();
9293         return;
9294       }
9295     } else {
9296       return;
9297     }
9298 
9299     // The variable can not have an abstract class type.
9300     if (RequireNonAbstractType(Var->getLocation(), Type,
9301                                diag::err_abstract_type_in_decl,
9302                                AbstractVariableType)) {
9303       Var->setInvalidDecl();
9304       return;
9305     }
9306 
9307     // Check for jumps past the implicit initializer.  C++0x
9308     // clarifies that this applies to a "variable with automatic
9309     // storage duration", not a "local variable".
9310     // C++11 [stmt.dcl]p3
9311     //   A program that jumps from a point where a variable with automatic
9312     //   storage duration is not in scope to a point where it is in scope is
9313     //   ill-formed unless the variable has scalar type, class type with a
9314     //   trivial default constructor and a trivial destructor, a cv-qualified
9315     //   version of one of these types, or an array of one of the preceding
9316     //   types and is declared without an initializer.
9317     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9318       if (const RecordType *Record
9319             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
9320         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9321         // Mark the function for further checking even if the looser rules of
9322         // C++11 do not require such checks, so that we can diagnose
9323         // incompatibilities with C++98.
9324         if (!CXXRecord->isPOD())
9325           getCurFunction()->setHasBranchProtectedScope();
9326       }
9327     }
9328 
9329     // C++03 [dcl.init]p9:
9330     //   If no initializer is specified for an object, and the
9331     //   object is of (possibly cv-qualified) non-POD class type (or
9332     //   array thereof), the object shall be default-initialized; if
9333     //   the object is of const-qualified type, the underlying class
9334     //   type shall have a user-declared default
9335     //   constructor. Otherwise, if no initializer is specified for
9336     //   a non- static object, the object and its subobjects, if
9337     //   any, have an indeterminate initial value); if the object
9338     //   or any of its subobjects are of const-qualified type, the
9339     //   program is ill-formed.
9340     // C++0x [dcl.init]p11:
9341     //   If no initializer is specified for an object, the object is
9342     //   default-initialized; [...].
9343     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
9344     InitializationKind Kind
9345       = InitializationKind::CreateDefault(Var->getLocation());
9346 
9347     InitializationSequence InitSeq(*this, Entity, Kind, None);
9348     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
9349     if (Init.isInvalid())
9350       Var->setInvalidDecl();
9351     else if (Init.get()) {
9352       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
9353       // This is important for template substitution.
9354       Var->setInitStyle(VarDecl::CallInit);
9355     }
9356 
9357     CheckCompleteVariableDeclaration(Var);
9358   }
9359 }
9360 
9361 void Sema::ActOnCXXForRangeDecl(Decl *D) {
9362   VarDecl *VD = dyn_cast<VarDecl>(D);
9363   if (!VD) {
9364     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9365     D->setInvalidDecl();
9366     return;
9367   }
9368 
9369   VD->setCXXForRangeDecl(true);
9370 
9371   // for-range-declaration cannot be given a storage class specifier.
9372   int Error = -1;
9373   switch (VD->getStorageClass()) {
9374   case SC_None:
9375     break;
9376   case SC_Extern:
9377     Error = 0;
9378     break;
9379   case SC_Static:
9380     Error = 1;
9381     break;
9382   case SC_PrivateExtern:
9383     Error = 2;
9384     break;
9385   case SC_Auto:
9386     Error = 3;
9387     break;
9388   case SC_Register:
9389     Error = 4;
9390     break;
9391   case SC_OpenCLWorkGroupLocal:
9392     llvm_unreachable("Unexpected storage class");
9393   }
9394   if (Error != -1) {
9395     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
9396       << VD->getDeclName() << Error;
9397     D->setInvalidDecl();
9398   }
9399 }
9400 
9401 StmtResult
9402 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
9403                                  IdentifierInfo *Ident,
9404                                  ParsedAttributes &Attrs,
9405                                  SourceLocation AttrEnd) {
9406   // C++1y [stmt.iter]p1:
9407   //   A range-based for statement of the form
9408   //      for ( for-range-identifier : for-range-initializer ) statement
9409   //   is equivalent to
9410   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
9411   DeclSpec DS(Attrs.getPool().getFactory());
9412 
9413   const char *PrevSpec;
9414   unsigned DiagID;
9415   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
9416                      getPrintingPolicy());
9417 
9418   Declarator D(DS, Declarator::ForContext);
9419   D.SetIdentifier(Ident, IdentLoc);
9420   D.takeAttributes(Attrs, AttrEnd);
9421 
9422   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
9423   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
9424                 EmptyAttrs, IdentLoc);
9425   Decl *Var = ActOnDeclarator(S, D);
9426   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
9427   FinalizeDeclaration(Var);
9428   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
9429                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
9430 }
9431 
9432 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
9433   if (var->isInvalidDecl()) return;
9434 
9435   // In ARC, don't allow jumps past the implicit initialization of a
9436   // local retaining variable.
9437   if (getLangOpts().ObjCAutoRefCount &&
9438       var->hasLocalStorage()) {
9439     switch (var->getType().getObjCLifetime()) {
9440     case Qualifiers::OCL_None:
9441     case Qualifiers::OCL_ExplicitNone:
9442     case Qualifiers::OCL_Autoreleasing:
9443       break;
9444 
9445     case Qualifiers::OCL_Weak:
9446     case Qualifiers::OCL_Strong:
9447       getCurFunction()->setHasBranchProtectedScope();
9448       break;
9449     }
9450   }
9451 
9452   // Warn about externally-visible variables being defined without a
9453   // prior declaration.  We only want to do this for global
9454   // declarations, but we also specifically need to avoid doing it for
9455   // class members because the linkage of an anonymous class can
9456   // change if it's later given a typedef name.
9457   if (var->isThisDeclarationADefinition() &&
9458       var->getDeclContext()->getRedeclContext()->isFileContext() &&
9459       var->isExternallyVisible() && var->hasLinkage() &&
9460       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
9461                                   var->getLocation())) {
9462     // Find a previous declaration that's not a definition.
9463     VarDecl *prev = var->getPreviousDecl();
9464     while (prev && prev->isThisDeclarationADefinition())
9465       prev = prev->getPreviousDecl();
9466 
9467     if (!prev)
9468       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
9469   }
9470 
9471   if (var->getTLSKind() == VarDecl::TLS_Static) {
9472     const Expr *Culprit;
9473     if (var->getType().isDestructedType()) {
9474       // GNU C++98 edits for __thread, [basic.start.term]p3:
9475       //   The type of an object with thread storage duration shall not
9476       //   have a non-trivial destructor.
9477       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
9478       if (getLangOpts().CPlusPlus11)
9479         Diag(var->getLocation(), diag::note_use_thread_local);
9480     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
9481                !var->getInit()->isConstantInitializer(
9482                    Context, var->getType()->isReferenceType(), &Culprit)) {
9483       // GNU C++98 edits for __thread, [basic.start.init]p4:
9484       //   An object of thread storage duration shall not require dynamic
9485       //   initialization.
9486       // FIXME: Need strict checking here.
9487       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
9488         << Culprit->getSourceRange();
9489       if (getLangOpts().CPlusPlus11)
9490         Diag(var->getLocation(), diag::note_use_thread_local);
9491     }
9492 
9493   }
9494 
9495   if (var->isThisDeclarationADefinition() &&
9496       ActiveTemplateInstantiations.empty()) {
9497     PragmaStack<StringLiteral *> *Stack = nullptr;
9498     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
9499     if (var->getType().isConstQualified())
9500       Stack = &ConstSegStack;
9501     else if (!var->getInit()) {
9502       Stack = &BSSSegStack;
9503       SectionFlags |= ASTContext::PSF_Write;
9504     } else {
9505       Stack = &DataSegStack;
9506       SectionFlags |= ASTContext::PSF_Write;
9507     }
9508     if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue)
9509       var->addAttr(
9510           SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
9511                                       Stack->CurrentValue->getString(),
9512                                       Stack->CurrentPragmaLocation));
9513     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
9514       if (UnifySection(SA->getName(), SectionFlags, var))
9515         var->dropAttr<SectionAttr>();
9516 
9517     // Apply the init_seg attribute if this has an initializer.  If the
9518     // initializer turns out to not be dynamic, we'll end up ignoring this
9519     // attribute.
9520     if (CurInitSeg && var->getInit())
9521       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
9522                                                CurInitSegLoc));
9523   }
9524 
9525   // All the following checks are C++ only.
9526   if (!getLangOpts().CPlusPlus) return;
9527 
9528   QualType type = var->getType();
9529   if (type->isDependentType()) return;
9530 
9531   // __block variables might require us to capture a copy-initializer.
9532   if (var->hasAttr<BlocksAttr>()) {
9533     // It's currently invalid to ever have a __block variable with an
9534     // array type; should we diagnose that here?
9535 
9536     // Regardless, we don't want to ignore array nesting when
9537     // constructing this copy.
9538     if (type->isStructureOrClassType()) {
9539       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
9540       SourceLocation poi = var->getLocation();
9541       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
9542       ExprResult result
9543         = PerformMoveOrCopyInitialization(
9544             InitializedEntity::InitializeBlock(poi, type, false),
9545             var, var->getType(), varRef, /*AllowNRVO=*/true);
9546       if (!result.isInvalid()) {
9547         result = MaybeCreateExprWithCleanups(result);
9548         Expr *init = result.getAs<Expr>();
9549         Context.setBlockVarCopyInits(var, init);
9550       }
9551     }
9552   }
9553 
9554   Expr *Init = var->getInit();
9555   bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
9556   QualType baseType = Context.getBaseElementType(type);
9557 
9558   if (!var->getDeclContext()->isDependentContext() &&
9559       Init && !Init->isValueDependent()) {
9560     if (IsGlobal && !var->isConstexpr() &&
9561         !getDiagnostics().isIgnored(diag::warn_global_constructor,
9562                                     var->getLocation())) {
9563       // Warn about globals which don't have a constant initializer.  Don't
9564       // warn about globals with a non-trivial destructor because we already
9565       // warned about them.
9566       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
9567       if (!(RD && !RD->hasTrivialDestructor()) &&
9568           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
9569         Diag(var->getLocation(), diag::warn_global_constructor)
9570           << Init->getSourceRange();
9571     }
9572 
9573     if (var->isConstexpr()) {
9574       SmallVector<PartialDiagnosticAt, 8> Notes;
9575       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
9576         SourceLocation DiagLoc = var->getLocation();
9577         // If the note doesn't add any useful information other than a source
9578         // location, fold it into the primary diagnostic.
9579         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9580               diag::note_invalid_subexpr_in_const_expr) {
9581           DiagLoc = Notes[0].first;
9582           Notes.clear();
9583         }
9584         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
9585           << var << Init->getSourceRange();
9586         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9587           Diag(Notes[I].first, Notes[I].second);
9588       }
9589     } else if (var->isUsableInConstantExpressions(Context)) {
9590       // Check whether the initializer of a const variable of integral or
9591       // enumeration type is an ICE now, since we can't tell whether it was
9592       // initialized by a constant expression if we check later.
9593       var->checkInitIsICE();
9594     }
9595   }
9596 
9597   // Require the destructor.
9598   if (const RecordType *recordType = baseType->getAs<RecordType>())
9599     FinalizeVarWithDestructor(var, recordType);
9600 }
9601 
9602 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
9603 /// any semantic actions necessary after any initializer has been attached.
9604 void
9605 Sema::FinalizeDeclaration(Decl *ThisDecl) {
9606   // Note that we are no longer parsing the initializer for this declaration.
9607   ParsingInitForAutoVars.erase(ThisDecl);
9608 
9609   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
9610   if (!VD)
9611     return;
9612 
9613   checkAttributesAfterMerging(*this, *VD);
9614 
9615   // Static locals inherit dll attributes from their function.
9616   if (VD->isStaticLocal()) {
9617     if (FunctionDecl *FD =
9618             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
9619       if (Attr *A = getDLLAttr(FD)) {
9620         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
9621         NewAttr->setInherited(true);
9622         VD->addAttr(NewAttr);
9623       }
9624     }
9625   }
9626 
9627   // Grab the dllimport or dllexport attribute off of the VarDecl.
9628   const InheritableAttr *DLLAttr = getDLLAttr(VD);
9629 
9630   // Imported static data members cannot be defined out-of-line.
9631   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
9632     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
9633         VD->isThisDeclarationADefinition()) {
9634       // We allow definitions of dllimport class template static data members
9635       // with a warning.
9636       CXXRecordDecl *Context =
9637         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
9638       bool IsClassTemplateMember =
9639           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
9640           Context->getDescribedClassTemplate();
9641 
9642       Diag(VD->getLocation(),
9643            IsClassTemplateMember
9644                ? diag::warn_attribute_dllimport_static_field_definition
9645                : diag::err_attribute_dllimport_static_field_definition);
9646       Diag(IA->getLocation(), diag::note_attribute);
9647       if (!IsClassTemplateMember)
9648         VD->setInvalidDecl();
9649     }
9650   }
9651 
9652   // dllimport/dllexport variables cannot be thread local, their TLS index
9653   // isn't exported with the variable.
9654   if (DLLAttr && VD->getTLSKind()) {
9655     Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
9656                                                                   << DLLAttr;
9657     VD->setInvalidDecl();
9658   }
9659 
9660   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
9661     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
9662       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
9663       VD->dropAttr<UsedAttr>();
9664     }
9665   }
9666 
9667   const DeclContext *DC = VD->getDeclContext();
9668   // If there's a #pragma GCC visibility in scope, and this isn't a class
9669   // member, set the visibility of this variable.
9670   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
9671     AddPushedVisibilityAttribute(VD);
9672 
9673   // FIXME: Warn on unused templates.
9674   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
9675       !isa<VarTemplatePartialSpecializationDecl>(VD))
9676     MarkUnusedFileScopedDecl(VD);
9677 
9678   // Now we have parsed the initializer and can update the table of magic
9679   // tag values.
9680   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
9681       !VD->getType()->isIntegralOrEnumerationType())
9682     return;
9683 
9684   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
9685     const Expr *MagicValueExpr = VD->getInit();
9686     if (!MagicValueExpr) {
9687       continue;
9688     }
9689     llvm::APSInt MagicValueInt;
9690     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
9691       Diag(I->getRange().getBegin(),
9692            diag::err_type_tag_for_datatype_not_ice)
9693         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9694       continue;
9695     }
9696     if (MagicValueInt.getActiveBits() > 64) {
9697       Diag(I->getRange().getBegin(),
9698            diag::err_type_tag_for_datatype_too_large)
9699         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9700       continue;
9701     }
9702     uint64_t MagicValue = MagicValueInt.getZExtValue();
9703     RegisterTypeTagForDatatype(I->getArgumentKind(),
9704                                MagicValue,
9705                                I->getMatchingCType(),
9706                                I->getLayoutCompatible(),
9707                                I->getMustBeNull());
9708   }
9709 }
9710 
9711 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
9712                                                    ArrayRef<Decl *> Group) {
9713   SmallVector<Decl*, 8> Decls;
9714 
9715   if (DS.isTypeSpecOwned())
9716     Decls.push_back(DS.getRepAsDecl());
9717 
9718   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
9719   for (unsigned i = 0, e = Group.size(); i != e; ++i)
9720     if (Decl *D = Group[i]) {
9721       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
9722         if (!FirstDeclaratorInGroup)
9723           FirstDeclaratorInGroup = DD;
9724       Decls.push_back(D);
9725     }
9726 
9727   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
9728     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
9729       HandleTagNumbering(*this, Tag, S);
9730       if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9731         Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9732     }
9733   }
9734 
9735   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
9736 }
9737 
9738 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
9739 /// group, performing any necessary semantic checking.
9740 Sema::DeclGroupPtrTy
9741 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
9742                            bool TypeMayContainAuto) {
9743   // C++0x [dcl.spec.auto]p7:
9744   //   If the type deduced for the template parameter U is not the same in each
9745   //   deduction, the program is ill-formed.
9746   // FIXME: When initializer-list support is added, a distinction is needed
9747   // between the deduced type U and the deduced type which 'auto' stands for.
9748   //   auto a = 0, b = { 1, 2, 3 };
9749   // is legal because the deduced type U is 'int' in both cases.
9750   if (TypeMayContainAuto && Group.size() > 1) {
9751     QualType Deduced;
9752     CanQualType DeducedCanon;
9753     VarDecl *DeducedDecl = nullptr;
9754     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
9755       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9756         AutoType *AT = D->getType()->getContainedAutoType();
9757         // Don't reissue diagnostics when instantiating a template.
9758         if (AT && D->isInvalidDecl())
9759           break;
9760         QualType U = AT ? AT->getDeducedType() : QualType();
9761         if (!U.isNull()) {
9762           CanQualType UCanon = Context.getCanonicalType(U);
9763           if (Deduced.isNull()) {
9764             Deduced = U;
9765             DeducedCanon = UCanon;
9766             DeducedDecl = D;
9767           } else if (DeducedCanon != UCanon) {
9768             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9769                  diag::err_auto_different_deductions)
9770               << (AT->isDecltypeAuto() ? 1 : 0)
9771               << Deduced << DeducedDecl->getDeclName()
9772               << U << D->getDeclName()
9773               << DeducedDecl->getInit()->getSourceRange()
9774               << D->getInit()->getSourceRange();
9775             D->setInvalidDecl();
9776             break;
9777           }
9778         }
9779       }
9780     }
9781   }
9782 
9783   ActOnDocumentableDecls(Group);
9784 
9785   return DeclGroupPtrTy::make(
9786       DeclGroupRef::Create(Context, Group.data(), Group.size()));
9787 }
9788 
9789 void Sema::ActOnDocumentableDecl(Decl *D) {
9790   ActOnDocumentableDecls(D);
9791 }
9792 
9793 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
9794   // Don't parse the comment if Doxygen diagnostics are ignored.
9795   if (Group.empty() || !Group[0])
9796    return;
9797 
9798   if (Diags.isIgnored(diag::warn_doc_param_not_found, Group[0]->getLocation()))
9799     return;
9800 
9801   if (Group.size() >= 2) {
9802     // This is a decl group.  Normally it will contain only declarations
9803     // produced from declarator list.  But in case we have any definitions or
9804     // additional declaration references:
9805     //   'typedef struct S {} S;'
9806     //   'typedef struct S *S;'
9807     //   'struct S *pS;'
9808     // FinalizeDeclaratorGroup adds these as separate declarations.
9809     Decl *MaybeTagDecl = Group[0];
9810     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
9811       Group = Group.slice(1);
9812     }
9813   }
9814 
9815   // See if there are any new comments that are not attached to a decl.
9816   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9817   if (!Comments.empty() &&
9818       !Comments.back()->isAttached()) {
9819     // There is at least one comment that not attached to a decl.
9820     // Maybe it should be attached to one of these decls?
9821     //
9822     // Note that this way we pick up not only comments that precede the
9823     // declaration, but also comments that *follow* the declaration -- thanks to
9824     // the lookahead in the lexer: we've consumed the semicolon and looked
9825     // ahead through comments.
9826     for (unsigned i = 0, e = Group.size(); i != e; ++i)
9827       Context.getCommentForDecl(Group[i], &PP);
9828   }
9829 }
9830 
9831 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9832 /// to introduce parameters into function prototype scope.
9833 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
9834   const DeclSpec &DS = D.getDeclSpec();
9835 
9836   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
9837 
9838   // C++03 [dcl.stc]p2 also permits 'auto'.
9839   StorageClass SC = SC_None;
9840   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
9841     SC = SC_Register;
9842   } else if (getLangOpts().CPlusPlus &&
9843              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9844     SC = SC_Auto;
9845   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
9846     Diag(DS.getStorageClassSpecLoc(),
9847          diag::err_invalid_storage_class_in_func_decl);
9848     D.getMutableDeclSpec().ClearStorageClassSpecs();
9849   }
9850 
9851   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9852     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9853       << DeclSpec::getSpecifierName(TSCS);
9854   if (DS.isConstexprSpecified())
9855     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
9856       << 0;
9857 
9858   DiagnoseFunctionSpecifiers(DS);
9859 
9860   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9861   QualType parmDeclType = TInfo->getType();
9862 
9863   if (getLangOpts().CPlusPlus) {
9864     // Check that there are no default arguments inside the type of this
9865     // parameter.
9866     CheckExtraCXXDefaultArguments(D);
9867 
9868     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9869     if (D.getCXXScopeSpec().isSet()) {
9870       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9871         << D.getCXXScopeSpec().getRange();
9872       D.getCXXScopeSpec().clear();
9873     }
9874   }
9875 
9876   // Ensure we have a valid name
9877   IdentifierInfo *II = nullptr;
9878   if (D.hasName()) {
9879     II = D.getIdentifier();
9880     if (!II) {
9881       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9882         << GetNameForDeclarator(D).getName();
9883       D.setInvalidType(true);
9884     }
9885   }
9886 
9887   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
9888   if (II) {
9889     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9890                    ForRedeclaration);
9891     LookupName(R, S);
9892     if (R.isSingleResult()) {
9893       NamedDecl *PrevDecl = R.getFoundDecl();
9894       if (PrevDecl->isTemplateParameter()) {
9895         // Maybe we will complain about the shadowed template parameter.
9896         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9897         // Just pretend that we didn't see the previous declaration.
9898         PrevDecl = nullptr;
9899       } else if (S->isDeclScope(PrevDecl)) {
9900         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
9901         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9902 
9903         // Recover by removing the name
9904         II = nullptr;
9905         D.SetIdentifier(nullptr, D.getIdentifierLoc());
9906         D.setInvalidType(true);
9907       }
9908     }
9909   }
9910 
9911   // Temporarily put parameter variables in the translation unit, not
9912   // the enclosing context.  This prevents them from accidentally
9913   // looking like class members in C++.
9914   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
9915                                     D.getLocStart(),
9916                                     D.getIdentifierLoc(), II,
9917                                     parmDeclType, TInfo,
9918                                     SC);
9919 
9920   if (D.isInvalidType())
9921     New->setInvalidDecl();
9922 
9923   assert(S->isFunctionPrototypeScope());
9924   assert(S->getFunctionPrototypeDepth() >= 1);
9925   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9926                     S->getNextFunctionPrototypeIndex());
9927 
9928   // Add the parameter declaration into this scope.
9929   S->AddDecl(New);
9930   if (II)
9931     IdResolver.AddDecl(New);
9932 
9933   ProcessDeclAttributes(S, New, D);
9934 
9935   if (D.getDeclSpec().isModulePrivateSpecified())
9936     Diag(New->getLocation(), diag::err_module_private_local)
9937       << 1 << New->getDeclName()
9938       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9939       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9940 
9941   if (New->hasAttr<BlocksAttr>()) {
9942     Diag(New->getLocation(), diag::err_block_on_nonlocal);
9943   }
9944   return New;
9945 }
9946 
9947 /// \brief Synthesizes a variable for a parameter arising from a
9948 /// typedef.
9949 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9950                                               SourceLocation Loc,
9951                                               QualType T) {
9952   /* FIXME: setting StartLoc == Loc.
9953      Would it be worth to modify callers so as to provide proper source
9954      location for the unnamed parameters, embedding the parameter's type? */
9955   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
9956                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
9957                                            SC_None, nullptr);
9958   Param->setImplicit();
9959   return Param;
9960 }
9961 
9962 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9963                                     ParmVarDecl * const *ParamEnd) {
9964   // Don't diagnose unused-parameter errors in template instantiations; we
9965   // will already have done so in the template itself.
9966   if (!ActiveTemplateInstantiations.empty())
9967     return;
9968 
9969   for (; Param != ParamEnd; ++Param) {
9970     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
9971         !(*Param)->hasAttr<UnusedAttr>()) {
9972       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9973         << (*Param)->getDeclName();
9974     }
9975   }
9976 }
9977 
9978 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9979                                                   ParmVarDecl * const *ParamEnd,
9980                                                   QualType ReturnTy,
9981                                                   NamedDecl *D) {
9982   if (LangOpts.NumLargeByValueCopy == 0) // No check.
9983     return;
9984 
9985   // Warn if the return value is pass-by-value and larger than the specified
9986   // threshold.
9987   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
9988     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
9989     if (Size > LangOpts.NumLargeByValueCopy)
9990       Diag(D->getLocation(), diag::warn_return_value_size)
9991           << D->getDeclName() << Size;
9992   }
9993 
9994   // Warn if any parameter is pass-by-value and larger than the specified
9995   // threshold.
9996   for (; Param != ParamEnd; ++Param) {
9997     QualType T = (*Param)->getType();
9998     if (T->isDependentType() || !T.isPODType(Context))
9999       continue;
10000     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10001     if (Size > LangOpts.NumLargeByValueCopy)
10002       Diag((*Param)->getLocation(), diag::warn_parameter_size)
10003           << (*Param)->getDeclName() << Size;
10004   }
10005 }
10006 
10007 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10008                                   SourceLocation NameLoc, IdentifierInfo *Name,
10009                                   QualType T, TypeSourceInfo *TSInfo,
10010                                   StorageClass SC) {
10011   // In ARC, infer a lifetime qualifier for appropriate parameter types.
10012   if (getLangOpts().ObjCAutoRefCount &&
10013       T.getObjCLifetime() == Qualifiers::OCL_None &&
10014       T->isObjCLifetimeType()) {
10015 
10016     Qualifiers::ObjCLifetime lifetime;
10017 
10018     // Special cases for arrays:
10019     //   - if it's const, use __unsafe_unretained
10020     //   - otherwise, it's an error
10021     if (T->isArrayType()) {
10022       if (!T.isConstQualified()) {
10023         DelayedDiagnostics.add(
10024             sema::DelayedDiagnostic::makeForbiddenType(
10025             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10026       }
10027       lifetime = Qualifiers::OCL_ExplicitNone;
10028     } else {
10029       lifetime = T->getObjCARCImplicitLifetime();
10030     }
10031     T = Context.getLifetimeQualifiedType(T, lifetime);
10032   }
10033 
10034   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10035                                          Context.getAdjustedParameterType(T),
10036                                          TSInfo, SC, nullptr);
10037 
10038   // Parameters can not be abstract class types.
10039   // For record types, this is done by the AbstractClassUsageDiagnoser once
10040   // the class has been completely parsed.
10041   if (!CurContext->isRecord() &&
10042       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10043                              AbstractParamType))
10044     New->setInvalidDecl();
10045 
10046   // Parameter declarators cannot be interface types. All ObjC objects are
10047   // passed by reference.
10048   if (T->isObjCObjectType()) {
10049     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10050     Diag(NameLoc,
10051          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10052       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10053     T = Context.getObjCObjectPointerType(T);
10054     New->setType(T);
10055   }
10056 
10057   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10058   // duration shall not be qualified by an address-space qualifier."
10059   // Since all parameters have automatic store duration, they can not have
10060   // an address space.
10061   if (T.getAddressSpace() != 0) {
10062     // OpenCL allows function arguments declared to be an array of a type
10063     // to be qualified with an address space.
10064     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10065       Diag(NameLoc, diag::err_arg_with_address_space);
10066       New->setInvalidDecl();
10067     }
10068   }
10069 
10070   return New;
10071 }
10072 
10073 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10074                                            SourceLocation LocAfterDecls) {
10075   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10076 
10077   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10078   // for a K&R function.
10079   if (!FTI.hasPrototype) {
10080     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10081       --i;
10082       if (FTI.Params[i].Param == nullptr) {
10083         SmallString<256> Code;
10084         llvm::raw_svector_ostream(Code)
10085             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10086         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10087             << FTI.Params[i].Ident
10088             << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
10089 
10090         // Implicitly declare the argument as type 'int' for lack of a better
10091         // type.
10092         AttributeFactory attrs;
10093         DeclSpec DS(attrs);
10094         const char* PrevSpec; // unused
10095         unsigned DiagID; // unused
10096         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10097                            DiagID, Context.getPrintingPolicy());
10098         // Use the identifier location for the type source range.
10099         DS.SetRangeStart(FTI.Params[i].IdentLoc);
10100         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10101         Declarator ParamD(DS, Declarator::KNRTypeListContext);
10102         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10103         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10104       }
10105     }
10106   }
10107 }
10108 
10109 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
10110   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10111   assert(D.isFunctionDeclarator() && "Not a function declarator!");
10112   Scope *ParentScope = FnBodyScope->getParent();
10113 
10114   D.setFunctionDefinitionKind(FDK_Definition);
10115   Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
10116   return ActOnStartOfFunctionDef(FnBodyScope, DP);
10117 }
10118 
10119 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10120   Consumer.HandleInlineMethodDefinition(D);
10121 }
10122 
10123 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10124                              const FunctionDecl*& PossibleZeroParamPrototype) {
10125   // Don't warn about invalid declarations.
10126   if (FD->isInvalidDecl())
10127     return false;
10128 
10129   // Or declarations that aren't global.
10130   if (!FD->isGlobal())
10131     return false;
10132 
10133   // Don't warn about C++ member functions.
10134   if (isa<CXXMethodDecl>(FD))
10135     return false;
10136 
10137   // Don't warn about 'main'.
10138   if (FD->isMain())
10139     return false;
10140 
10141   // Don't warn about inline functions.
10142   if (FD->isInlined())
10143     return false;
10144 
10145   // Don't warn about function templates.
10146   if (FD->getDescribedFunctionTemplate())
10147     return false;
10148 
10149   // Don't warn about function template specializations.
10150   if (FD->isFunctionTemplateSpecialization())
10151     return false;
10152 
10153   // Don't warn for OpenCL kernels.
10154   if (FD->hasAttr<OpenCLKernelAttr>())
10155     return false;
10156 
10157   bool MissingPrototype = true;
10158   for (const FunctionDecl *Prev = FD->getPreviousDecl();
10159        Prev; Prev = Prev->getPreviousDecl()) {
10160     // Ignore any declarations that occur in function or method
10161     // scope, because they aren't visible from the header.
10162     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10163       continue;
10164 
10165     MissingPrototype = !Prev->getType()->isFunctionProtoType();
10166     if (FD->getNumParams() == 0)
10167       PossibleZeroParamPrototype = Prev;
10168     break;
10169   }
10170 
10171   return MissingPrototype;
10172 }
10173 
10174 void
10175 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10176                                    const FunctionDecl *EffectiveDefinition) {
10177   // Don't complain if we're in GNU89 mode and the previous definition
10178   // was an extern inline function.
10179   const FunctionDecl *Definition = EffectiveDefinition;
10180   if (!Definition)
10181     if (!FD->isDefined(Definition))
10182       return;
10183 
10184   if (canRedefineFunction(Definition, getLangOpts()))
10185     return;
10186 
10187   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10188       Definition->getStorageClass() == SC_Extern)
10189     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10190         << FD->getDeclName() << getLangOpts().CPlusPlus;
10191   else
10192     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10193 
10194   Diag(Definition->getLocation(), diag::note_previous_definition);
10195   FD->setInvalidDecl();
10196 }
10197 
10198 
10199 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10200                                    Sema &S) {
10201   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10202 
10203   LambdaScopeInfo *LSI = S.PushLambdaScope();
10204   LSI->CallOperator = CallOperator;
10205   LSI->Lambda = LambdaClass;
10206   LSI->ReturnType = CallOperator->getReturnType();
10207   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10208 
10209   if (LCD == LCD_None)
10210     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10211   else if (LCD == LCD_ByCopy)
10212     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10213   else if (LCD == LCD_ByRef)
10214     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10215   DeclarationNameInfo DNI = CallOperator->getNameInfo();
10216 
10217   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
10218   LSI->Mutable = !CallOperator->isConst();
10219 
10220   // Add the captures to the LSI so they can be noted as already
10221   // captured within tryCaptureVar.
10222   auto I = LambdaClass->field_begin();
10223   for (const auto &C : LambdaClass->captures()) {
10224     if (C.capturesVariable()) {
10225       VarDecl *VD = C.getCapturedVar();
10226       if (VD->isInitCapture())
10227         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10228       QualType CaptureType = VD->getType();
10229       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10230       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
10231           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
10232           /*EllipsisLoc*/C.isPackExpansion()
10233                          ? C.getEllipsisLoc() : SourceLocation(),
10234           CaptureType, /*Expr*/ nullptr);
10235 
10236     } else if (C.capturesThis()) {
10237       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
10238                               S.getCurrentThisType(), /*Expr*/ nullptr);
10239     } else {
10240       LSI->addVLATypeCapture(C.getLocation(), I->getType());
10241     }
10242     ++I;
10243   }
10244 }
10245 
10246 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
10247   // Clear the last template instantiation error context.
10248   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10249 
10250   if (!D)
10251     return D;
10252   FunctionDecl *FD = nullptr;
10253 
10254   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10255     FD = FunTmpl->getTemplatedDecl();
10256   else
10257     FD = cast<FunctionDecl>(D);
10258   // If we are instantiating a generic lambda call operator, push
10259   // a LambdaScopeInfo onto the function stack.  But use the information
10260   // that's already been calculated (ActOnLambdaExpr) to prime the current
10261   // LambdaScopeInfo.
10262   // When the template operator is being specialized, the LambdaScopeInfo,
10263   // has to be properly restored so that tryCaptureVariable doesn't try
10264   // and capture any new variables. In addition when calculating potential
10265   // captures during transformation of nested lambdas, it is necessary to
10266   // have the LSI properly restored.
10267   if (isGenericLambdaCallOperatorSpecialization(FD)) {
10268     assert(ActiveTemplateInstantiations.size() &&
10269       "There should be an active template instantiation on the stack "
10270       "when instantiating a generic lambda!");
10271     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
10272   }
10273   else
10274     // Enter a new function scope
10275     PushFunctionScope();
10276 
10277   // See if this is a redefinition.
10278   if (!FD->isLateTemplateParsed())
10279     CheckForFunctionRedefinition(FD);
10280 
10281   // Builtin functions cannot be defined.
10282   if (unsigned BuiltinID = FD->getBuiltinID()) {
10283     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10284         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
10285       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
10286       FD->setInvalidDecl();
10287     }
10288   }
10289 
10290   // The return type of a function definition must be complete
10291   // (C99 6.9.1p3, C++ [dcl.fct]p6).
10292   QualType ResultType = FD->getReturnType();
10293   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
10294       !FD->isInvalidDecl() &&
10295       RequireCompleteType(FD->getLocation(), ResultType,
10296                           diag::err_func_def_incomplete_result))
10297     FD->setInvalidDecl();
10298 
10299   // GNU warning -Wmissing-prototypes:
10300   //   Warn if a global function is defined without a previous
10301   //   prototype declaration. This warning is issued even if the
10302   //   definition itself provides a prototype. The aim is to detect
10303   //   global functions that fail to be declared in header files.
10304   const FunctionDecl *PossibleZeroParamPrototype = nullptr;
10305   if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
10306     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
10307 
10308     if (PossibleZeroParamPrototype) {
10309       // We found a declaration that is not a prototype,
10310       // but that could be a zero-parameter prototype
10311       if (TypeSourceInfo *TI =
10312               PossibleZeroParamPrototype->getTypeSourceInfo()) {
10313         TypeLoc TL = TI->getTypeLoc();
10314         if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
10315           Diag(PossibleZeroParamPrototype->getLocation(),
10316                diag::note_declaration_not_a_prototype)
10317             << PossibleZeroParamPrototype
10318             << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
10319       }
10320     }
10321   }
10322 
10323   if (FnBodyScope)
10324     PushDeclContext(FnBodyScope, FD);
10325 
10326   // Check the validity of our function parameters
10327   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10328                            /*CheckParameterNames=*/true);
10329 
10330   // Introduce our parameters into the function scope
10331   for (auto Param : FD->params()) {
10332     Param->setOwningFunction(FD);
10333 
10334     // If this has an identifier, add it to the scope stack.
10335     if (Param->getIdentifier() && FnBodyScope) {
10336       CheckShadow(FnBodyScope, Param);
10337 
10338       PushOnScopeChains(Param, FnBodyScope);
10339     }
10340   }
10341 
10342   // If we had any tags defined in the function prototype,
10343   // introduce them into the function scope.
10344   if (FnBodyScope) {
10345     for (ArrayRef<NamedDecl *>::iterator
10346              I = FD->getDeclsInPrototypeScope().begin(),
10347              E = FD->getDeclsInPrototypeScope().end();
10348          I != E; ++I) {
10349       NamedDecl *D = *I;
10350 
10351       // Some of these decls (like enums) may have been pinned to the translation unit
10352       // for lack of a real context earlier. If so, remove from the translation unit
10353       // and reattach to the current context.
10354       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
10355         // Is the decl actually in the context?
10356         for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
10357           if (DI == D) {
10358             Context.getTranslationUnitDecl()->removeDecl(D);
10359             break;
10360           }
10361         }
10362         // Either way, reassign the lexical decl context to our FunctionDecl.
10363         D->setLexicalDeclContext(CurContext);
10364       }
10365 
10366       // If the decl has a non-null name, make accessible in the current scope.
10367       if (!D->getName().empty())
10368         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10369 
10370       // Similarly, dive into enums and fish their constants out, making them
10371       // accessible in this scope.
10372       if (auto *ED = dyn_cast<EnumDecl>(D)) {
10373         for (auto *EI : ED->enumerators())
10374           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
10375       }
10376     }
10377   }
10378 
10379   // Ensure that the function's exception specification is instantiated.
10380   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10381     ResolveExceptionSpec(D->getLocation(), FPT);
10382 
10383   // dllimport cannot be applied to non-inline function definitions.
10384   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10385       !FD->isTemplateInstantiation()) {
10386     assert(!FD->hasAttr<DLLExportAttr>());
10387     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10388     FD->setInvalidDecl();
10389     return D;
10390   }
10391   // We want to attach documentation to original Decl (which might be
10392   // a function template).
10393   ActOnDocumentableDecl(D);
10394   if (getCurLexicalContext()->isObjCContainer() &&
10395       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10396       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10397     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10398 
10399   return D;
10400 }
10401 
10402 /// \brief Given the set of return statements within a function body,
10403 /// compute the variables that are subject to the named return value
10404 /// optimization.
10405 ///
10406 /// Each of the variables that is subject to the named return value
10407 /// optimization will be marked as NRVO variables in the AST, and any
10408 /// return statement that has a marked NRVO variable as its NRVO candidate can
10409 /// use the named return value optimization.
10410 ///
10411 /// This function applies a very simplistic algorithm for NRVO: if every return
10412 /// statement in the scope of a variable has the same NRVO candidate, that
10413 /// candidate is an NRVO variable.
10414 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
10415   ReturnStmt **Returns = Scope->Returns.data();
10416 
10417   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
10418     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
10419       if (!NRVOCandidate->isNRVOVariable())
10420         Returns[I]->setNRVOCandidate(nullptr);
10421     }
10422   }
10423 }
10424 
10425 bool Sema::canDelayFunctionBody(const Declarator &D) {
10426   // We can't delay parsing the body of a constexpr function template (yet).
10427   if (D.getDeclSpec().isConstexprSpecified())
10428     return false;
10429 
10430   // We can't delay parsing the body of a function template with a deduced
10431   // return type (yet).
10432   if (D.getDeclSpec().containsPlaceholderType()) {
10433     // If the placeholder introduces a non-deduced trailing return type,
10434     // we can still delay parsing it.
10435     if (D.getNumTypeObjects()) {
10436       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
10437       if (Outer.Kind == DeclaratorChunk::Function &&
10438           Outer.Fun.hasTrailingReturnType()) {
10439         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
10440         return Ty.isNull() || !Ty->isUndeducedType();
10441       }
10442     }
10443     return false;
10444   }
10445 
10446   return true;
10447 }
10448 
10449 bool Sema::canSkipFunctionBody(Decl *D) {
10450   // We cannot skip the body of a function (or function template) which is
10451   // constexpr, since we may need to evaluate its body in order to parse the
10452   // rest of the file.
10453   // We cannot skip the body of a function with an undeduced return type,
10454   // because any callers of that function need to know the type.
10455   if (const FunctionDecl *FD = D->getAsFunction())
10456     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
10457       return false;
10458   return Consumer.shouldSkipFunctionBody(D);
10459 }
10460 
10461 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
10462   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
10463     FD->setHasSkippedBody();
10464   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
10465     MD->setHasSkippedBody();
10466   return ActOnFinishFunctionBody(Decl, nullptr);
10467 }
10468 
10469 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
10470   return ActOnFinishFunctionBody(D, BodyArg, false);
10471 }
10472 
10473 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
10474                                     bool IsInstantiation) {
10475   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
10476 
10477   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10478   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
10479 
10480   if (FD) {
10481     FD->setBody(Body);
10482 
10483     if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
10484         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
10485       // If the function has a deduced result type but contains no 'return'
10486       // statements, the result type as written must be exactly 'auto', and
10487       // the deduced result type is 'void'.
10488       if (!FD->getReturnType()->getAs<AutoType>()) {
10489         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
10490             << FD->getReturnType();
10491         FD->setInvalidDecl();
10492       } else {
10493         // Substitute 'void' for the 'auto' in the type.
10494         TypeLoc ResultType = getReturnTypeLoc(FD);
10495         Context.adjustDeducedFunctionResultType(
10496             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
10497       }
10498     }
10499 
10500     // The only way to be included in UndefinedButUsed is if there is an
10501     // ODR use before the definition. Avoid the expensive map lookup if this
10502     // is the first declaration.
10503     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
10504       if (!FD->isExternallyVisible())
10505         UndefinedButUsed.erase(FD);
10506       else if (FD->isInlined() &&
10507                (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
10508                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
10509         UndefinedButUsed.erase(FD);
10510     }
10511 
10512     // If the function implicitly returns zero (like 'main') or is naked,
10513     // don't complain about missing return statements.
10514     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
10515       WP.disableCheckFallThrough();
10516 
10517     // MSVC permits the use of pure specifier (=0) on function definition,
10518     // defined at class scope, warn about this non-standard construct.
10519     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
10520       Diag(FD->getLocation(), diag::ext_pure_function_definition);
10521 
10522     if (!FD->isInvalidDecl()) {
10523       // Don't diagnose unused parameters of defaulted or deleted functions.
10524       if (Body)
10525         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
10526       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
10527                                              FD->getReturnType(), FD);
10528 
10529       // If this is a structor, we need a vtable.
10530       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
10531         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
10532       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
10533         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
10534 
10535       // Try to apply the named return value optimization. We have to check
10536       // if we can do this here because lambdas keep return statements around
10537       // to deduce an implicit return type.
10538       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
10539           !FD->isDependentContext())
10540         computeNRVO(Body, getCurFunction());
10541     }
10542 
10543     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
10544       const CXXMethodDecl *KeyFunction;
10545       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
10546           MD->isVirtual() &&
10547           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
10548           MD == KeyFunction->getCanonicalDecl()) {
10549         // Update the key-function state if necessary for this ABI.
10550         if (FD->isInlined() &&
10551             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
10552           Context.setNonKeyFunction(MD);
10553 
10554           // If the newly-chosen key function is already defined, then we
10555           // need to mark the vtable as used retroactively.
10556           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
10557           const FunctionDecl *Definition;
10558           if (KeyFunction && KeyFunction->isDefined(Definition))
10559             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
10560         } else {
10561           // We just defined they key function; mark the vtable as used.
10562           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
10563         }
10564       }
10565     }
10566 
10567     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
10568            "Function parsing confused");
10569   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
10570     assert(MD == getCurMethodDecl() && "Method parsing confused");
10571     MD->setBody(Body);
10572     if (!MD->isInvalidDecl()) {
10573       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
10574       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
10575                                              MD->getReturnType(), MD);
10576 
10577       if (Body)
10578         computeNRVO(Body, getCurFunction());
10579     }
10580     if (getCurFunction()->ObjCShouldCallSuper) {
10581       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
10582         << MD->getSelector().getAsString();
10583       getCurFunction()->ObjCShouldCallSuper = false;
10584     }
10585     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
10586       const ObjCMethodDecl *InitMethod = nullptr;
10587       bool isDesignated =
10588           MD->isDesignatedInitializerForTheInterface(&InitMethod);
10589       assert(isDesignated && InitMethod);
10590       (void)isDesignated;
10591 
10592       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
10593         auto IFace = MD->getClassInterface();
10594         if (!IFace)
10595           return false;
10596         auto SuperD = IFace->getSuperClass();
10597         if (!SuperD)
10598           return false;
10599         return SuperD->getIdentifier() ==
10600             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
10601       };
10602       // Don't issue this warning for unavailable inits or direct subclasses
10603       // of NSObject.
10604       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
10605         Diag(MD->getLocation(),
10606              diag::warn_objc_designated_init_missing_super_call);
10607         Diag(InitMethod->getLocation(),
10608              diag::note_objc_designated_init_marked_here);
10609       }
10610       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
10611     }
10612     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
10613       // Don't issue this warning for unavaialable inits.
10614       if (!MD->isUnavailable())
10615         Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
10616       getCurFunction()->ObjCWarnForNoInitDelegation = false;
10617     }
10618   } else {
10619     return nullptr;
10620   }
10621 
10622   assert(!getCurFunction()->ObjCShouldCallSuper &&
10623          "This should only be set for ObjC methods, which should have been "
10624          "handled in the block above.");
10625 
10626   // Verify and clean out per-function state.
10627   if (Body) {
10628     // C++ constructors that have function-try-blocks can't have return
10629     // statements in the handlers of that block. (C++ [except.handle]p14)
10630     // Verify this.
10631     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
10632       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
10633 
10634     // Verify that gotos and switch cases don't jump into scopes illegally.
10635     if (getCurFunction()->NeedsScopeChecking() &&
10636         !PP.isCodeCompletionEnabled())
10637       DiagnoseInvalidJumps(Body);
10638 
10639     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
10640       if (!Destructor->getParent()->isDependentType())
10641         CheckDestructor(Destructor);
10642 
10643       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10644                                              Destructor->getParent());
10645     }
10646 
10647     // If any errors have occurred, clear out any temporaries that may have
10648     // been leftover. This ensures that these temporaries won't be picked up for
10649     // deletion in some later function.
10650     if (getDiagnostics().hasErrorOccurred() ||
10651         getDiagnostics().getSuppressAllDiagnostics()) {
10652       DiscardCleanupsInEvaluationContext();
10653     }
10654     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
10655         !isa<FunctionTemplateDecl>(dcl)) {
10656       // Since the body is valid, issue any analysis-based warnings that are
10657       // enabled.
10658       ActivePolicy = &WP;
10659     }
10660 
10661     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
10662         (!CheckConstexprFunctionDecl(FD) ||
10663          !CheckConstexprFunctionBody(FD, Body)))
10664       FD->setInvalidDecl();
10665 
10666     if (FD && FD->hasAttr<NakedAttr>()) {
10667       for (const Stmt *S : Body->children()) {
10668         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
10669           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
10670           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
10671           FD->setInvalidDecl();
10672           break;
10673         }
10674       }
10675     }
10676 
10677     assert(ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects
10678            && "Leftover temporaries in function");
10679     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
10680     assert(MaybeODRUseExprs.empty() &&
10681            "Leftover expressions for odr-use checking");
10682   }
10683 
10684   if (!IsInstantiation)
10685     PopDeclContext();
10686 
10687   PopFunctionScopeInfo(ActivePolicy, dcl);
10688   // If any errors have occurred, clear out any temporaries that may have
10689   // been leftover. This ensures that these temporaries won't be picked up for
10690   // deletion in some later function.
10691   if (getDiagnostics().hasErrorOccurred()) {
10692     DiscardCleanupsInEvaluationContext();
10693   }
10694 
10695   return dcl;
10696 }
10697 
10698 
10699 /// When we finish delayed parsing of an attribute, we must attach it to the
10700 /// relevant Decl.
10701 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
10702                                        ParsedAttributes &Attrs) {
10703   // Always attach attributes to the underlying decl.
10704   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
10705     D = TD->getTemplatedDecl();
10706   ProcessDeclAttributeList(S, D, Attrs.getList());
10707 
10708   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
10709     if (Method->isStatic())
10710       checkThisInStaticMemberFunctionAttributes(Method);
10711 }
10712 
10713 
10714 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
10715 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
10716 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
10717                                           IdentifierInfo &II, Scope *S) {
10718   // Before we produce a declaration for an implicitly defined
10719   // function, see whether there was a locally-scoped declaration of
10720   // this name as a function or variable. If so, use that
10721   // (non-visible) declaration, and complain about it.
10722   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
10723     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
10724     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
10725     return ExternCPrev;
10726   }
10727 
10728   // Extension in C99.  Legal in C90, but warn about it.
10729   unsigned diag_id;
10730   if (II.getName().startswith("__builtin_"))
10731     diag_id = diag::warn_builtin_unknown;
10732   else if (getLangOpts().C99)
10733     diag_id = diag::ext_implicit_function_decl;
10734   else
10735     diag_id = diag::warn_implicit_function_decl;
10736   Diag(Loc, diag_id) << &II;
10737 
10738   // Because typo correction is expensive, only do it if the implicit
10739   // function declaration is going to be treated as an error.
10740   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
10741     TypoCorrection Corrected;
10742     if (S &&
10743         (Corrected = CorrectTypo(
10744              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
10745              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
10746       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
10747                    /*ErrorRecovery*/false);
10748   }
10749 
10750   // Set a Declarator for the implicit definition: int foo();
10751   const char *Dummy;
10752   AttributeFactory attrFactory;
10753   DeclSpec DS(attrFactory);
10754   unsigned DiagID;
10755   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
10756                                   Context.getPrintingPolicy());
10757   (void)Error; // Silence warning.
10758   assert(!Error && "Error setting up implicit decl!");
10759   SourceLocation NoLoc;
10760   Declarator D(DS, Declarator::BlockContext);
10761   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
10762                                              /*IsAmbiguous=*/false,
10763                                              /*LParenLoc=*/NoLoc,
10764                                              /*Params=*/nullptr,
10765                                              /*NumParams=*/0,
10766                                              /*EllipsisLoc=*/NoLoc,
10767                                              /*RParenLoc=*/NoLoc,
10768                                              /*TypeQuals=*/0,
10769                                              /*RefQualifierIsLvalueRef=*/true,
10770                                              /*RefQualifierLoc=*/NoLoc,
10771                                              /*ConstQualifierLoc=*/NoLoc,
10772                                              /*VolatileQualifierLoc=*/NoLoc,
10773                                              /*RestrictQualifierLoc=*/NoLoc,
10774                                              /*MutableLoc=*/NoLoc,
10775                                              EST_None,
10776                                              /*ESpecLoc=*/NoLoc,
10777                                              /*Exceptions=*/nullptr,
10778                                              /*ExceptionRanges=*/nullptr,
10779                                              /*NumExceptions=*/0,
10780                                              /*NoexceptExpr=*/nullptr,
10781                                              /*ExceptionSpecTokens=*/nullptr,
10782                                              Loc, Loc, D),
10783                 DS.getAttributes(),
10784                 SourceLocation());
10785   D.SetIdentifier(&II, Loc);
10786 
10787   // Insert this function into translation-unit scope.
10788 
10789   DeclContext *PrevDC = CurContext;
10790   CurContext = Context.getTranslationUnitDecl();
10791 
10792   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
10793   FD->setImplicit();
10794 
10795   CurContext = PrevDC;
10796 
10797   AddKnownFunctionAttributes(FD);
10798 
10799   return FD;
10800 }
10801 
10802 /// \brief Adds any function attributes that we know a priori based on
10803 /// the declaration of this function.
10804 ///
10805 /// These attributes can apply both to implicitly-declared builtins
10806 /// (like __builtin___printf_chk) or to library-declared functions
10807 /// like NSLog or printf.
10808 ///
10809 /// We need to check for duplicate attributes both here and where user-written
10810 /// attributes are applied to declarations.
10811 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10812   if (FD->isInvalidDecl())
10813     return;
10814 
10815   // If this is a built-in function, map its builtin attributes to
10816   // actual attributes.
10817   if (unsigned BuiltinID = FD->getBuiltinID()) {
10818     // Handle printf-formatting attributes.
10819     unsigned FormatIdx;
10820     bool HasVAListArg;
10821     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
10822       if (!FD->hasAttr<FormatAttr>()) {
10823         const char *fmt = "printf";
10824         unsigned int NumParams = FD->getNumParams();
10825         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10826             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10827           fmt = "NSString";
10828         FD->addAttr(FormatAttr::CreateImplicit(Context,
10829                                                &Context.Idents.get(fmt),
10830                                                FormatIdx+1,
10831                                                HasVAListArg ? 0 : FormatIdx+2,
10832                                                FD->getLocation()));
10833       }
10834     }
10835     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10836                                              HasVAListArg)) {
10837      if (!FD->hasAttr<FormatAttr>())
10838        FD->addAttr(FormatAttr::CreateImplicit(Context,
10839                                               &Context.Idents.get("scanf"),
10840                                               FormatIdx+1,
10841                                               HasVAListArg ? 0 : FormatIdx+2,
10842                                               FD->getLocation()));
10843     }
10844 
10845     // Mark const if we don't care about errno and that is the only
10846     // thing preventing the function from being const. This allows
10847     // IRgen to use LLVM intrinsics for such functions.
10848     if (!getLangOpts().MathErrno &&
10849         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
10850       if (!FD->hasAttr<ConstAttr>())
10851         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10852     }
10853 
10854     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10855         !FD->hasAttr<ReturnsTwiceAttr>())
10856       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10857                                          FD->getLocation()));
10858     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
10859       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
10860     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
10861       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10862   }
10863 
10864   IdentifierInfo *Name = FD->getIdentifier();
10865   if (!Name)
10866     return;
10867   if ((!getLangOpts().CPlusPlus &&
10868        FD->getDeclContext()->isTranslationUnit()) ||
10869       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
10870        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
10871        LinkageSpecDecl::lang_c)) {
10872     // Okay: this could be a libc/libm/Objective-C function we know
10873     // about.
10874   } else
10875     return;
10876 
10877   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
10878     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
10879     // target-specific builtins, perhaps?
10880     if (!FD->hasAttr<FormatAttr>())
10881       FD->addAttr(FormatAttr::CreateImplicit(Context,
10882                                              &Context.Idents.get("printf"), 2,
10883                                              Name->isStr("vasprintf") ? 0 : 3,
10884                                              FD->getLocation()));
10885   }
10886 
10887   if (Name->isStr("__CFStringMakeConstantString")) {
10888     // We already have a __builtin___CFStringMakeConstantString,
10889     // but builds that use -fno-constant-cfstrings don't go through that.
10890     if (!FD->hasAttr<FormatArgAttr>())
10891       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10892                                                 FD->getLocation()));
10893   }
10894 }
10895 
10896 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
10897                                     TypeSourceInfo *TInfo) {
10898   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
10899   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
10900 
10901   if (!TInfo) {
10902     assert(D.isInvalidType() && "no declarator info for valid type");
10903     TInfo = Context.getTrivialTypeSourceInfo(T);
10904   }
10905 
10906   // Scope manipulation handled by caller.
10907   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
10908                                            D.getLocStart(),
10909                                            D.getIdentifierLoc(),
10910                                            D.getIdentifier(),
10911                                            TInfo);
10912 
10913   // Bail out immediately if we have an invalid declaration.
10914   if (D.isInvalidType()) {
10915     NewTD->setInvalidDecl();
10916     return NewTD;
10917   }
10918 
10919   if (D.getDeclSpec().isModulePrivateSpecified()) {
10920     if (CurContext->isFunctionOrMethod())
10921       Diag(NewTD->getLocation(), diag::err_module_private_local)
10922         << 2 << NewTD->getDeclName()
10923         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10924         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10925     else
10926       NewTD->setModulePrivate();
10927   }
10928 
10929   // C++ [dcl.typedef]p8:
10930   //   If the typedef declaration defines an unnamed class (or
10931   //   enum), the first typedef-name declared by the declaration
10932   //   to be that class type (or enum type) is used to denote the
10933   //   class type (or enum type) for linkage purposes only.
10934   // We need to check whether the type was declared in the declaration.
10935   switch (D.getDeclSpec().getTypeSpecType()) {
10936   case TST_enum:
10937   case TST_struct:
10938   case TST_interface:
10939   case TST_union:
10940   case TST_class: {
10941     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10942 
10943     // Do nothing if the tag is not anonymous or already has an
10944     // associated typedef (from an earlier typedef in this decl group).
10945     if (tagFromDeclSpec->getIdentifier()) break;
10946     if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
10947 
10948     // A well-formed anonymous tag must always be a TUK_Definition.
10949     assert(tagFromDeclSpec->isThisDeclarationADefinition());
10950 
10951     // The type must match the tag exactly;  no qualifiers allowed.
10952     if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10953       break;
10954 
10955     // If we've already computed linkage for the anonymous tag, then
10956     // adding a typedef name for the anonymous decl can change that
10957     // linkage, which might be a serious problem.  Diagnose this as
10958     // unsupported and ignore the typedef name.  TODO: we should
10959     // pursue this as a language defect and establish a formal rule
10960     // for how to handle it.
10961     if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10962       Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10963 
10964       SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
10965       tagLoc = getLocForEndOfToken(tagLoc);
10966 
10967       llvm::SmallString<40> textToInsert;
10968       textToInsert += ' ';
10969       textToInsert += D.getIdentifier()->getName();
10970       Diag(tagLoc, diag::note_typedef_changes_linkage)
10971         << FixItHint::CreateInsertion(tagLoc, textToInsert);
10972       break;
10973     }
10974 
10975     // Otherwise, set this is the anon-decl typedef for the tag.
10976     tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
10977     break;
10978   }
10979 
10980   default:
10981     break;
10982   }
10983 
10984   return NewTD;
10985 }
10986 
10987 
10988 /// \brief Check that this is a valid underlying type for an enum declaration.
10989 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10990   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10991   QualType T = TI->getType();
10992 
10993   if (T->isDependentType())
10994     return false;
10995 
10996   if (const BuiltinType *BT = T->getAs<BuiltinType>())
10997     if (BT->isInteger())
10998       return false;
10999 
11000   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11001   return true;
11002 }
11003 
11004 /// Check whether this is a valid redeclaration of a previous enumeration.
11005 /// \return true if the redeclaration was invalid.
11006 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
11007                                   QualType EnumUnderlyingTy,
11008                                   const EnumDecl *Prev) {
11009   bool IsFixed = !EnumUnderlyingTy.isNull();
11010 
11011   if (IsScoped != Prev->isScoped()) {
11012     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11013       << Prev->isScoped();
11014     Diag(Prev->getLocation(), diag::note_previous_declaration);
11015     return true;
11016   }
11017 
11018   if (IsFixed && Prev->isFixed()) {
11019     if (!EnumUnderlyingTy->isDependentType() &&
11020         !Prev->getIntegerType()->isDependentType() &&
11021         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11022                                         Prev->getIntegerType())) {
11023       // TODO: Highlight the underlying type of the redeclaration.
11024       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11025         << EnumUnderlyingTy << Prev->getIntegerType();
11026       Diag(Prev->getLocation(), diag::note_previous_declaration)
11027           << Prev->getIntegerTypeRange();
11028       return true;
11029     }
11030   } else if (IsFixed != Prev->isFixed()) {
11031     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11032       << Prev->isFixed();
11033     Diag(Prev->getLocation(), diag::note_previous_declaration);
11034     return true;
11035   }
11036 
11037   return false;
11038 }
11039 
11040 /// \brief Get diagnostic %select index for tag kind for
11041 /// redeclaration diagnostic message.
11042 /// WARNING: Indexes apply to particular diagnostics only!
11043 ///
11044 /// \returns diagnostic %select index.
11045 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
11046   switch (Tag) {
11047   case TTK_Struct: return 0;
11048   case TTK_Interface: return 1;
11049   case TTK_Class:  return 2;
11050   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11051   }
11052 }
11053 
11054 /// \brief Determine if tag kind is a class-key compatible with
11055 /// class for redeclaration (class, struct, or __interface).
11056 ///
11057 /// \returns true iff the tag kind is compatible.
11058 static bool isClassCompatTagKind(TagTypeKind Tag)
11059 {
11060   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11061 }
11062 
11063 /// \brief Determine whether a tag with a given kind is acceptable
11064 /// as a redeclaration of the given tag declaration.
11065 ///
11066 /// \returns true if the new tag kind is acceptable, false otherwise.
11067 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11068                                         TagTypeKind NewTag, bool isDefinition,
11069                                         SourceLocation NewTagLoc,
11070                                         const IdentifierInfo &Name) {
11071   // C++ [dcl.type.elab]p3:
11072   //   The class-key or enum keyword present in the
11073   //   elaborated-type-specifier shall agree in kind with the
11074   //   declaration to which the name in the elaborated-type-specifier
11075   //   refers. This rule also applies to the form of
11076   //   elaborated-type-specifier that declares a class-name or
11077   //   friend class since it can be construed as referring to the
11078   //   definition of the class. Thus, in any
11079   //   elaborated-type-specifier, the enum keyword shall be used to
11080   //   refer to an enumeration (7.2), the union class-key shall be
11081   //   used to refer to a union (clause 9), and either the class or
11082   //   struct class-key shall be used to refer to a class (clause 9)
11083   //   declared using the class or struct class-key.
11084   TagTypeKind OldTag = Previous->getTagKind();
11085   if (!isDefinition || !isClassCompatTagKind(NewTag))
11086     if (OldTag == NewTag)
11087       return true;
11088 
11089   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11090     // Warn about the struct/class tag mismatch.
11091     bool isTemplate = false;
11092     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11093       isTemplate = Record->getDescribedClassTemplate();
11094 
11095     if (!ActiveTemplateInstantiations.empty()) {
11096       // In a template instantiation, do not offer fix-its for tag mismatches
11097       // since they usually mess up the template instead of fixing the problem.
11098       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11099         << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11100         << getRedeclDiagFromTagKind(OldTag);
11101       return true;
11102     }
11103 
11104     if (isDefinition) {
11105       // On definitions, check previous tags and issue a fix-it for each
11106       // one that doesn't match the current tag.
11107       if (Previous->getDefinition()) {
11108         // Don't suggest fix-its for redefinitions.
11109         return true;
11110       }
11111 
11112       bool previousMismatch = false;
11113       for (auto I : Previous->redecls()) {
11114         if (I->getTagKind() != NewTag) {
11115           if (!previousMismatch) {
11116             previousMismatch = true;
11117             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11118               << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11119               << getRedeclDiagFromTagKind(I->getTagKind());
11120           }
11121           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11122             << getRedeclDiagFromTagKind(NewTag)
11123             << FixItHint::CreateReplacement(I->getInnerLocStart(),
11124                  TypeWithKeyword::getTagTypeKindName(NewTag));
11125         }
11126       }
11127       return true;
11128     }
11129 
11130     // Check for a previous definition.  If current tag and definition
11131     // are same type, do nothing.  If no definition, but disagree with
11132     // with previous tag type, give a warning, but no fix-it.
11133     const TagDecl *Redecl = Previous->getDefinition() ?
11134                             Previous->getDefinition() : Previous;
11135     if (Redecl->getTagKind() == NewTag) {
11136       return true;
11137     }
11138 
11139     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11140       << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11141       << getRedeclDiagFromTagKind(OldTag);
11142     Diag(Redecl->getLocation(), diag::note_previous_use);
11143 
11144     // If there is a previous definition, suggest a fix-it.
11145     if (Previous->getDefinition()) {
11146         Diag(NewTagLoc, diag::note_struct_class_suggestion)
11147           << getRedeclDiagFromTagKind(Redecl->getTagKind())
11148           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11149                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11150     }
11151 
11152     return true;
11153   }
11154   return false;
11155 }
11156 
11157 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11158 /// from an outer enclosing namespace or file scope inside a friend declaration.
11159 /// This should provide the commented out code in the following snippet:
11160 ///   namespace N {
11161 ///     struct X;
11162 ///     namespace M {
11163 ///       struct Y { friend struct /*N::*/ X; };
11164 ///     }
11165 ///   }
11166 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11167                                          SourceLocation NameLoc) {
11168   // While the decl is in a namespace, do repeated lookup of that name and see
11169   // if we get the same namespace back.  If we do not, continue until
11170   // translation unit scope, at which point we have a fully qualified NNS.
11171   SmallVector<IdentifierInfo *, 4> Namespaces;
11172   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11173   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11174     // This tag should be declared in a namespace, which can only be enclosed by
11175     // other namespaces.  Bail if there's an anonymous namespace in the chain.
11176     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11177     if (!Namespace || Namespace->isAnonymousNamespace())
11178       return FixItHint();
11179     IdentifierInfo *II = Namespace->getIdentifier();
11180     Namespaces.push_back(II);
11181     NamedDecl *Lookup = SemaRef.LookupSingleName(
11182         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11183     if (Lookup == Namespace)
11184       break;
11185   }
11186 
11187   // Once we have all the namespaces, reverse them to go outermost first, and
11188   // build an NNS.
11189   SmallString<64> Insertion;
11190   llvm::raw_svector_ostream OS(Insertion);
11191   if (DC->isTranslationUnit())
11192     OS << "::";
11193   std::reverse(Namespaces.begin(), Namespaces.end());
11194   for (auto *II : Namespaces)
11195     OS << II->getName() << "::";
11196   OS.flush();
11197   return FixItHint::CreateInsertion(NameLoc, Insertion);
11198 }
11199 
11200 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
11201 /// former case, Name will be non-null.  In the later case, Name will be null.
11202 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
11203 /// reference/declaration/definition of a tag.
11204 ///
11205 /// IsTypeSpecifier is true if this is a type-specifier (or
11206 /// trailing-type-specifier) other than one in an alias-declaration.
11207 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11208                      SourceLocation KWLoc, CXXScopeSpec &SS,
11209                      IdentifierInfo *Name, SourceLocation NameLoc,
11210                      AttributeList *Attr, AccessSpecifier AS,
11211                      SourceLocation ModulePrivateLoc,
11212                      MultiTemplateParamsArg TemplateParameterLists,
11213                      bool &OwnedDecl, bool &IsDependent,
11214                      SourceLocation ScopedEnumKWLoc,
11215                      bool ScopedEnumUsesClassTag,
11216                      TypeResult UnderlyingType,
11217                      bool IsTypeSpecifier) {
11218   // If this is not a definition, it must have a name.
11219   IdentifierInfo *OrigName = Name;
11220   assert((Name != nullptr || TUK == TUK_Definition) &&
11221          "Nameless record must be a definition!");
11222   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
11223 
11224   OwnedDecl = false;
11225   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11226   bool ScopedEnum = ScopedEnumKWLoc.isValid();
11227 
11228   // FIXME: Check explicit specializations more carefully.
11229   bool isExplicitSpecialization = false;
11230   bool Invalid = false;
11231 
11232   // We only need to do this matching if we have template parameters
11233   // or a scope specifier, which also conveniently avoids this work
11234   // for non-C++ cases.
11235   if (TemplateParameterLists.size() > 0 ||
11236       (SS.isNotEmpty() && TUK != TUK_Reference)) {
11237     if (TemplateParameterList *TemplateParams =
11238             MatchTemplateParametersToScopeSpecifier(
11239                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
11240                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
11241       if (Kind == TTK_Enum) {
11242         Diag(KWLoc, diag::err_enum_template);
11243         return nullptr;
11244       }
11245 
11246       if (TemplateParams->size() > 0) {
11247         // This is a declaration or definition of a class template (which may
11248         // be a member of another template).
11249 
11250         if (Invalid)
11251           return nullptr;
11252 
11253         OwnedDecl = false;
11254         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
11255                                                SS, Name, NameLoc, Attr,
11256                                                TemplateParams, AS,
11257                                                ModulePrivateLoc,
11258                                                /*FriendLoc*/SourceLocation(),
11259                                                TemplateParameterLists.size()-1,
11260                                                TemplateParameterLists.data());
11261         return Result.get();
11262       } else {
11263         // The "template<>" header is extraneous.
11264         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11265           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11266         isExplicitSpecialization = true;
11267       }
11268     }
11269   }
11270 
11271   // Figure out the underlying type if this a enum declaration. We need to do
11272   // this early, because it's needed to detect if this is an incompatible
11273   // redeclaration.
11274   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11275 
11276   if (Kind == TTK_Enum) {
11277     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11278       // No underlying type explicitly specified, or we failed to parse the
11279       // type, default to int.
11280       EnumUnderlying = Context.IntTy.getTypePtr();
11281     else if (UnderlyingType.get()) {
11282       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11283       // integral type; any cv-qualification is ignored.
11284       TypeSourceInfo *TI = nullptr;
11285       GetTypeFromParser(UnderlyingType.get(), &TI);
11286       EnumUnderlying = TI;
11287 
11288       if (CheckEnumUnderlyingType(TI))
11289         // Recover by falling back to int.
11290         EnumUnderlying = Context.IntTy.getTypePtr();
11291 
11292       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
11293                                           UPPC_FixedUnderlyingType))
11294         EnumUnderlying = Context.IntTy.getTypePtr();
11295 
11296     } else if (getLangOpts().MSVCCompat)
11297       // Microsoft enums are always of int type.
11298       EnumUnderlying = Context.IntTy.getTypePtr();
11299   }
11300 
11301   DeclContext *SearchDC = CurContext;
11302   DeclContext *DC = CurContext;
11303   bool isStdBadAlloc = false;
11304 
11305   RedeclarationKind Redecl = ForRedeclaration;
11306   if (TUK == TUK_Friend || TUK == TUK_Reference)
11307     Redecl = NotForRedeclaration;
11308 
11309   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
11310   if (Name && SS.isNotEmpty()) {
11311     // We have a nested-name tag ('struct foo::bar').
11312 
11313     // Check for invalid 'foo::'.
11314     if (SS.isInvalid()) {
11315       Name = nullptr;
11316       goto CreateNewDecl;
11317     }
11318 
11319     // If this is a friend or a reference to a class in a dependent
11320     // context, don't try to make a decl for it.
11321     if (TUK == TUK_Friend || TUK == TUK_Reference) {
11322       DC = computeDeclContext(SS, false);
11323       if (!DC) {
11324         IsDependent = true;
11325         return nullptr;
11326       }
11327     } else {
11328       DC = computeDeclContext(SS, true);
11329       if (!DC) {
11330         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11331           << SS.getRange();
11332         return nullptr;
11333       }
11334     }
11335 
11336     if (RequireCompleteDeclContext(SS, DC))
11337       return nullptr;
11338 
11339     SearchDC = DC;
11340     // Look-up name inside 'foo::'.
11341     LookupQualifiedName(Previous, DC);
11342 
11343     if (Previous.isAmbiguous())
11344       return nullptr;
11345 
11346     if (Previous.empty()) {
11347       // Name lookup did not find anything. However, if the
11348       // nested-name-specifier refers to the current instantiation,
11349       // and that current instantiation has any dependent base
11350       // classes, we might find something at instantiation time: treat
11351       // this as a dependent elaborated-type-specifier.
11352       // But this only makes any sense for reference-like lookups.
11353       if (Previous.wasNotFoundInCurrentInstantiation() &&
11354           (TUK == TUK_Reference || TUK == TUK_Friend)) {
11355         IsDependent = true;
11356         return nullptr;
11357       }
11358 
11359       // A tag 'foo::bar' must already exist.
11360       Diag(NameLoc, diag::err_not_tag_in_scope)
11361         << Kind << Name << DC << SS.getRange();
11362       Name = nullptr;
11363       Invalid = true;
11364       goto CreateNewDecl;
11365     }
11366   } else if (Name) {
11367     // If this is a named struct, check to see if there was a previous forward
11368     // declaration or definition.
11369     // FIXME: We're looking into outer scopes here, even when we
11370     // shouldn't be. Doing so can result in ambiguities that we
11371     // shouldn't be diagnosing.
11372     LookupName(Previous, S);
11373 
11374     // When declaring or defining a tag, ignore ambiguities introduced
11375     // by types using'ed into this scope.
11376     if (Previous.isAmbiguous() &&
11377         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
11378       LookupResult::Filter F = Previous.makeFilter();
11379       while (F.hasNext()) {
11380         NamedDecl *ND = F.next();
11381         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
11382           F.erase();
11383       }
11384       F.done();
11385     }
11386 
11387     // C++11 [namespace.memdef]p3:
11388     //   If the name in a friend declaration is neither qualified nor
11389     //   a template-id and the declaration is a function or an
11390     //   elaborated-type-specifier, the lookup to determine whether
11391     //   the entity has been previously declared shall not consider
11392     //   any scopes outside the innermost enclosing namespace.
11393     //
11394     // MSVC doesn't implement the above rule for types, so a friend tag
11395     // declaration may be a redeclaration of a type declared in an enclosing
11396     // scope.  They do implement this rule for friend functions.
11397     //
11398     // Does it matter that this should be by scope instead of by
11399     // semantic context?
11400     if (!Previous.empty() && TUK == TUK_Friend) {
11401       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
11402       LookupResult::Filter F = Previous.makeFilter();
11403       bool FriendSawTagOutsideEnclosingNamespace = false;
11404       while (F.hasNext()) {
11405         NamedDecl *ND = F.next();
11406         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11407         if (DC->isFileContext() &&
11408             !EnclosingNS->Encloses(ND->getDeclContext())) {
11409           if (getLangOpts().MSVCCompat)
11410             FriendSawTagOutsideEnclosingNamespace = true;
11411           else
11412             F.erase();
11413         }
11414       }
11415       F.done();
11416 
11417       // Diagnose this MSVC extension in the easy case where lookup would have
11418       // unambiguously found something outside the enclosing namespace.
11419       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
11420         NamedDecl *ND = Previous.getFoundDecl();
11421         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
11422             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
11423       }
11424     }
11425 
11426     // Note:  there used to be some attempt at recovery here.
11427     if (Previous.isAmbiguous())
11428       return nullptr;
11429 
11430     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
11431       // FIXME: This makes sure that we ignore the contexts associated
11432       // with C structs, unions, and enums when looking for a matching
11433       // tag declaration or definition. See the similar lookup tweak
11434       // in Sema::LookupName; is there a better way to deal with this?
11435       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
11436         SearchDC = SearchDC->getParent();
11437     }
11438   }
11439 
11440   if (Previous.isSingleResult() &&
11441       Previous.getFoundDecl()->isTemplateParameter()) {
11442     // Maybe we will complain about the shadowed template parameter.
11443     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
11444     // Just pretend that we didn't see the previous declaration.
11445     Previous.clear();
11446   }
11447 
11448   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
11449       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
11450     // This is a declaration of or a reference to "std::bad_alloc".
11451     isStdBadAlloc = true;
11452 
11453     if (Previous.empty() && StdBadAlloc) {
11454       // std::bad_alloc has been implicitly declared (but made invisible to
11455       // name lookup). Fill in this implicit declaration as the previous
11456       // declaration, so that the declarations get chained appropriately.
11457       Previous.addDecl(getStdBadAlloc());
11458     }
11459   }
11460 
11461   // If we didn't find a previous declaration, and this is a reference
11462   // (or friend reference), move to the correct scope.  In C++, we
11463   // also need to do a redeclaration lookup there, just in case
11464   // there's a shadow friend decl.
11465   if (Name && Previous.empty() &&
11466       (TUK == TUK_Reference || TUK == TUK_Friend)) {
11467     if (Invalid) goto CreateNewDecl;
11468     assert(SS.isEmpty());
11469 
11470     if (TUK == TUK_Reference) {
11471       // C++ [basic.scope.pdecl]p5:
11472       //   -- for an elaborated-type-specifier of the form
11473       //
11474       //          class-key identifier
11475       //
11476       //      if the elaborated-type-specifier is used in the
11477       //      decl-specifier-seq or parameter-declaration-clause of a
11478       //      function defined in namespace scope, the identifier is
11479       //      declared as a class-name in the namespace that contains
11480       //      the declaration; otherwise, except as a friend
11481       //      declaration, the identifier is declared in the smallest
11482       //      non-class, non-function-prototype scope that contains the
11483       //      declaration.
11484       //
11485       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
11486       // C structs and unions.
11487       //
11488       // It is an error in C++ to declare (rather than define) an enum
11489       // type, including via an elaborated type specifier.  We'll
11490       // diagnose that later; for now, declare the enum in the same
11491       // scope as we would have picked for any other tag type.
11492       //
11493       // GNU C also supports this behavior as part of its incomplete
11494       // enum types extension, while GNU C++ does not.
11495       //
11496       // Find the context where we'll be declaring the tag.
11497       // FIXME: We would like to maintain the current DeclContext as the
11498       // lexical context,
11499       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
11500         SearchDC = SearchDC->getParent();
11501 
11502       // Find the scope where we'll be declaring the tag.
11503       while (S->isClassScope() ||
11504              (getLangOpts().CPlusPlus &&
11505               S->isFunctionPrototypeScope()) ||
11506              ((S->getFlags() & Scope::DeclScope) == 0) ||
11507              (S->getEntity() && S->getEntity()->isTransparentContext()))
11508         S = S->getParent();
11509     } else {
11510       assert(TUK == TUK_Friend);
11511       // C++ [namespace.memdef]p3:
11512       //   If a friend declaration in a non-local class first declares a
11513       //   class or function, the friend class or function is a member of
11514       //   the innermost enclosing namespace.
11515       SearchDC = SearchDC->getEnclosingNamespaceContext();
11516     }
11517 
11518     // In C++, we need to do a redeclaration lookup to properly
11519     // diagnose some problems.
11520     if (getLangOpts().CPlusPlus) {
11521       Previous.setRedeclarationKind(ForRedeclaration);
11522       LookupQualifiedName(Previous, SearchDC);
11523     }
11524   }
11525 
11526   if (!Previous.empty()) {
11527     NamedDecl *PrevDecl = Previous.getFoundDecl();
11528     NamedDecl *DirectPrevDecl =
11529         getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
11530 
11531     // It's okay to have a tag decl in the same scope as a typedef
11532     // which hides a tag decl in the same scope.  Finding this
11533     // insanity with a redeclaration lookup can only actually happen
11534     // in C++.
11535     //
11536     // This is also okay for elaborated-type-specifiers, which is
11537     // technically forbidden by the current standard but which is
11538     // okay according to the likely resolution of an open issue;
11539     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
11540     if (getLangOpts().CPlusPlus) {
11541       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11542         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
11543           TagDecl *Tag = TT->getDecl();
11544           if (Tag->getDeclName() == Name &&
11545               Tag->getDeclContext()->getRedeclContext()
11546                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
11547             PrevDecl = Tag;
11548             Previous.clear();
11549             Previous.addDecl(Tag);
11550             Previous.resolveKind();
11551           }
11552         }
11553       }
11554     }
11555 
11556     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
11557       // If this is a use of a previous tag, or if the tag is already declared
11558       // in the same scope (so that the definition/declaration completes or
11559       // rementions the tag), reuse the decl.
11560       if (TUK == TUK_Reference || TUK == TUK_Friend ||
11561           isDeclInScope(DirectPrevDecl, SearchDC, S,
11562                         SS.isNotEmpty() || isExplicitSpecialization)) {
11563         // Make sure that this wasn't declared as an enum and now used as a
11564         // struct or something similar.
11565         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
11566                                           TUK == TUK_Definition, KWLoc,
11567                                           *Name)) {
11568           bool SafeToContinue
11569             = (PrevTagDecl->getTagKind() != TTK_Enum &&
11570                Kind != TTK_Enum);
11571           if (SafeToContinue)
11572             Diag(KWLoc, diag::err_use_with_wrong_tag)
11573               << Name
11574               << FixItHint::CreateReplacement(SourceRange(KWLoc),
11575                                               PrevTagDecl->getKindName());
11576           else
11577             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
11578           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
11579 
11580           if (SafeToContinue)
11581             Kind = PrevTagDecl->getTagKind();
11582           else {
11583             // Recover by making this an anonymous redefinition.
11584             Name = nullptr;
11585             Previous.clear();
11586             Invalid = true;
11587           }
11588         }
11589 
11590         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
11591           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
11592 
11593           // If this is an elaborated-type-specifier for a scoped enumeration,
11594           // the 'class' keyword is not necessary and not permitted.
11595           if (TUK == TUK_Reference || TUK == TUK_Friend) {
11596             if (ScopedEnum)
11597               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
11598                 << PrevEnum->isScoped()
11599                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
11600             return PrevTagDecl;
11601           }
11602 
11603           QualType EnumUnderlyingTy;
11604           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11605             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
11606           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
11607             EnumUnderlyingTy = QualType(T, 0);
11608 
11609           // All conflicts with previous declarations are recovered by
11610           // returning the previous declaration, unless this is a definition,
11611           // in which case we want the caller to bail out.
11612           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
11613                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
11614             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
11615         }
11616 
11617         // C++11 [class.mem]p1:
11618         //   A member shall not be declared twice in the member-specification,
11619         //   except that a nested class or member class template can be declared
11620         //   and then later defined.
11621         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
11622             S->isDeclScope(PrevDecl)) {
11623           Diag(NameLoc, diag::ext_member_redeclared);
11624           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
11625         }
11626 
11627         if (!Invalid) {
11628           // If this is a use, just return the declaration we found, unless
11629           // we have attributes.
11630 
11631           // FIXME: In the future, return a variant or some other clue
11632           // for the consumer of this Decl to know it doesn't own it.
11633           // For our current ASTs this shouldn't be a problem, but will
11634           // need to be changed with DeclGroups.
11635           if (!Attr &&
11636               ((TUK == TUK_Reference &&
11637                 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
11638                || TUK == TUK_Friend))
11639             return PrevTagDecl;
11640 
11641           // Diagnose attempts to redefine a tag.
11642           if (TUK == TUK_Definition) {
11643             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
11644               // If we're defining a specialization and the previous definition
11645               // is from an implicit instantiation, don't emit an error
11646               // here; we'll catch this in the general case below.
11647               bool IsExplicitSpecializationAfterInstantiation = false;
11648               if (isExplicitSpecialization) {
11649                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
11650                   IsExplicitSpecializationAfterInstantiation =
11651                     RD->getTemplateSpecializationKind() !=
11652                     TSK_ExplicitSpecialization;
11653                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
11654                   IsExplicitSpecializationAfterInstantiation =
11655                     ED->getTemplateSpecializationKind() !=
11656                     TSK_ExplicitSpecialization;
11657               }
11658 
11659               if (!IsExplicitSpecializationAfterInstantiation) {
11660                 // A redeclaration in function prototype scope in C isn't
11661                 // visible elsewhere, so merely issue a warning.
11662                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
11663                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
11664                 else
11665                   Diag(NameLoc, diag::err_redefinition) << Name;
11666                 Diag(Def->getLocation(), diag::note_previous_definition);
11667                 // If this is a redefinition, recover by making this
11668                 // struct be anonymous, which will make any later
11669                 // references get the previous definition.
11670                 Name = nullptr;
11671                 Previous.clear();
11672                 Invalid = true;
11673               }
11674             } else {
11675               // If the type is currently being defined, complain
11676               // about a nested redefinition.
11677               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
11678               if (TD->isBeingDefined()) {
11679                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
11680                 Diag(PrevTagDecl->getLocation(),
11681                      diag::note_previous_definition);
11682                 Name = nullptr;
11683                 Previous.clear();
11684                 Invalid = true;
11685               }
11686             }
11687 
11688             // Okay, this is definition of a previously declared or referenced
11689             // tag. We're going to create a new Decl for it.
11690           }
11691 
11692           // Okay, we're going to make a redeclaration.  If this is some kind
11693           // of reference, make sure we build the redeclaration in the same DC
11694           // as the original, and ignore the current access specifier.
11695           if (TUK == TUK_Friend || TUK == TUK_Reference) {
11696             SearchDC = PrevTagDecl->getDeclContext();
11697             AS = AS_none;
11698           }
11699         }
11700         // If we get here we have (another) forward declaration or we
11701         // have a definition.  Just create a new decl.
11702 
11703       } else {
11704         // If we get here, this is a definition of a new tag type in a nested
11705         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
11706         // new decl/type.  We set PrevDecl to NULL so that the entities
11707         // have distinct types.
11708         Previous.clear();
11709       }
11710       // If we get here, we're going to create a new Decl. If PrevDecl
11711       // is non-NULL, it's a definition of the tag declared by
11712       // PrevDecl. If it's NULL, we have a new definition.
11713 
11714 
11715     // Otherwise, PrevDecl is not a tag, but was found with tag
11716     // lookup.  This is only actually possible in C++, where a few
11717     // things like templates still live in the tag namespace.
11718     } else {
11719       // Use a better diagnostic if an elaborated-type-specifier
11720       // found the wrong kind of type on the first
11721       // (non-redeclaration) lookup.
11722       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
11723           !Previous.isForRedeclaration()) {
11724         unsigned Kind = 0;
11725         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11726         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11727         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11728         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
11729         Diag(PrevDecl->getLocation(), diag::note_declared_at);
11730         Invalid = true;
11731 
11732       // Otherwise, only diagnose if the declaration is in scope.
11733       } else if (!isDeclInScope(PrevDecl, SearchDC, S,
11734                                 SS.isNotEmpty() || isExplicitSpecialization)) {
11735         // do nothing
11736 
11737       // Diagnose implicit declarations introduced by elaborated types.
11738       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
11739         unsigned Kind = 0;
11740         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11741         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11742         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11743         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
11744         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11745         Invalid = true;
11746 
11747       // Otherwise it's a declaration.  Call out a particularly common
11748       // case here.
11749       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11750         unsigned Kind = 0;
11751         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
11752         Diag(NameLoc, diag::err_tag_definition_of_typedef)
11753           << Name << Kind << TND->getUnderlyingType();
11754         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11755         Invalid = true;
11756 
11757       // Otherwise, diagnose.
11758       } else {
11759         // The tag name clashes with something else in the target scope,
11760         // issue an error and recover by making this tag be anonymous.
11761         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
11762         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11763         Name = nullptr;
11764         Invalid = true;
11765       }
11766 
11767       // The existing declaration isn't relevant to us; we're in a
11768       // new scope, so clear out the previous declaration.
11769       Previous.clear();
11770     }
11771   }
11772 
11773 CreateNewDecl:
11774 
11775   TagDecl *PrevDecl = nullptr;
11776   if (Previous.isSingleResult())
11777     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
11778 
11779   // If there is an identifier, use the location of the identifier as the
11780   // location of the decl, otherwise use the location of the struct/union
11781   // keyword.
11782   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
11783 
11784   // Otherwise, create a new declaration. If there is a previous
11785   // declaration of the same entity, the two will be linked via
11786   // PrevDecl.
11787   TagDecl *New;
11788 
11789   bool IsForwardReference = false;
11790   if (Kind == TTK_Enum) {
11791     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11792     // enum X { A, B, C } D;    D should chain to X.
11793     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
11794                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
11795                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
11796     // If this is an undefined enum, warn.
11797     if (TUK != TUK_Definition && !Invalid) {
11798       TagDecl *Def;
11799       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
11800           cast<EnumDecl>(New)->isFixed()) {
11801         // C++0x: 7.2p2: opaque-enum-declaration.
11802         // Conflicts are diagnosed above. Do nothing.
11803       }
11804       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
11805         Diag(Loc, diag::ext_forward_ref_enum_def)
11806           << New;
11807         Diag(Def->getLocation(), diag::note_previous_definition);
11808       } else {
11809         unsigned DiagID = diag::ext_forward_ref_enum;
11810         if (getLangOpts().MSVCCompat)
11811           DiagID = diag::ext_ms_forward_ref_enum;
11812         else if (getLangOpts().CPlusPlus)
11813           DiagID = diag::err_forward_ref_enum;
11814         Diag(Loc, DiagID);
11815 
11816         // If this is a forward-declared reference to an enumeration, make a
11817         // note of it; we won't actually be introducing the declaration into
11818         // the declaration context.
11819         if (TUK == TUK_Reference)
11820           IsForwardReference = true;
11821       }
11822     }
11823 
11824     if (EnumUnderlying) {
11825       EnumDecl *ED = cast<EnumDecl>(New);
11826       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11827         ED->setIntegerTypeSourceInfo(TI);
11828       else
11829         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
11830       ED->setPromotionType(ED->getIntegerType());
11831     }
11832 
11833   } else {
11834     // struct/union/class
11835 
11836     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11837     // struct X { int A; } D;    D should chain to X.
11838     if (getLangOpts().CPlusPlus) {
11839       // FIXME: Look for a way to use RecordDecl for simple structs.
11840       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11841                                   cast_or_null<CXXRecordDecl>(PrevDecl));
11842 
11843       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
11844         StdBadAlloc = cast<CXXRecordDecl>(New);
11845     } else
11846       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11847                                cast_or_null<RecordDecl>(PrevDecl));
11848   }
11849 
11850   // C++11 [dcl.type]p3:
11851   //   A type-specifier-seq shall not define a class or enumeration [...].
11852   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11853     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11854       << Context.getTagDeclType(New);
11855     Invalid = true;
11856   }
11857 
11858   // Maybe add qualifier info.
11859   if (SS.isNotEmpty()) {
11860     if (SS.isSet()) {
11861       // If this is either a declaration or a definition, check the
11862       // nested-name-specifier against the current context. We don't do this
11863       // for explicit specializations, because they have similar checking
11864       // (with more specific diagnostics) in the call to
11865       // CheckMemberSpecialization, below.
11866       if (!isExplicitSpecialization &&
11867           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11868           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
11869         Invalid = true;
11870 
11871       New->setQualifierInfo(SS.getWithLocInContext(Context));
11872       if (TemplateParameterLists.size() > 0) {
11873         New->setTemplateParameterListsInfo(Context,
11874                                            TemplateParameterLists.size(),
11875                                            TemplateParameterLists.data());
11876       }
11877     }
11878     else
11879       Invalid = true;
11880   }
11881 
11882   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11883     // Add alignment attributes if necessary; these attributes are checked when
11884     // the ASTContext lays out the structure.
11885     //
11886     // It is important for implementing the correct semantics that this
11887     // happen here (in act on tag decl). The #pragma pack stack is
11888     // maintained as a result of parser callbacks which can occur at
11889     // many points during the parsing of a struct declaration (because
11890     // the #pragma tokens are effectively skipped over during the
11891     // parsing of the struct).
11892     if (TUK == TUK_Definition) {
11893       AddAlignmentAttributesForRecord(RD);
11894       AddMsStructLayoutForRecord(RD);
11895     }
11896   }
11897 
11898   if (ModulePrivateLoc.isValid()) {
11899     if (isExplicitSpecialization)
11900       Diag(New->getLocation(), diag::err_module_private_specialization)
11901         << 2
11902         << FixItHint::CreateRemoval(ModulePrivateLoc);
11903     // __module_private__ does not apply to local classes. However, we only
11904     // diagnose this as an error when the declaration specifiers are
11905     // freestanding. Here, we just ignore the __module_private__.
11906     else if (!SearchDC->isFunctionOrMethod())
11907       New->setModulePrivate();
11908   }
11909 
11910   // If this is a specialization of a member class (of a class template),
11911   // check the specialization.
11912   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
11913     Invalid = true;
11914 
11915   // If we're declaring or defining a tag in function prototype scope in C,
11916   // note that this type can only be used within the function and add it to
11917   // the list of decls to inject into the function definition scope.
11918   if ((Name || Kind == TTK_Enum) &&
11919       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
11920     if (getLangOpts().CPlusPlus) {
11921       // C++ [dcl.fct]p6:
11922       //   Types shall not be defined in return or parameter types.
11923       if (TUK == TUK_Definition && !IsTypeSpecifier) {
11924         Diag(Loc, diag::err_type_defined_in_param_type)
11925             << Name;
11926         Invalid = true;
11927       }
11928     } else {
11929       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11930     }
11931     DeclsInPrototypeScope.push_back(New);
11932   }
11933 
11934   if (Invalid)
11935     New->setInvalidDecl();
11936 
11937   if (Attr)
11938     ProcessDeclAttributeList(S, New, Attr);
11939 
11940   // Set the lexical context. If the tag has a C++ scope specifier, the
11941   // lexical context will be different from the semantic context.
11942   New->setLexicalDeclContext(CurContext);
11943 
11944   // Mark this as a friend decl if applicable.
11945   // In Microsoft mode, a friend declaration also acts as a forward
11946   // declaration so we always pass true to setObjectOfFriendDecl to make
11947   // the tag name visible.
11948   if (TUK == TUK_Friend)
11949     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
11950 
11951   // Set the access specifier.
11952   if (!Invalid && SearchDC->isRecord())
11953     SetMemberAccessSpecifier(New, PrevDecl, AS);
11954 
11955   if (TUK == TUK_Definition)
11956     New->startDefinition();
11957 
11958   // If this has an identifier, add it to the scope stack.
11959   if (TUK == TUK_Friend) {
11960     // We might be replacing an existing declaration in the lookup tables;
11961     // if so, borrow its access specifier.
11962     if (PrevDecl)
11963       New->setAccess(PrevDecl->getAccess());
11964 
11965     DeclContext *DC = New->getDeclContext()->getRedeclContext();
11966     DC->makeDeclVisibleInContext(New);
11967     if (Name) // can be null along some error paths
11968       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11969         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
11970   } else if (Name) {
11971     S = getNonFieldDeclScope(S);
11972     PushOnScopeChains(New, S, !IsForwardReference);
11973     if (IsForwardReference)
11974       SearchDC->makeDeclVisibleInContext(New);
11975 
11976   } else {
11977     CurContext->addDecl(New);
11978   }
11979 
11980   // If this is the C FILE type, notify the AST context.
11981   if (IdentifierInfo *II = New->getIdentifier())
11982     if (!New->isInvalidDecl() &&
11983         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
11984         II->isStr("FILE"))
11985       Context.setFILEDecl(New);
11986 
11987   if (PrevDecl)
11988     mergeDeclAttributes(New, PrevDecl);
11989 
11990   // If there's a #pragma GCC visibility in scope, set the visibility of this
11991   // record.
11992   AddPushedVisibilityAttribute(New);
11993 
11994   OwnedDecl = true;
11995   // In C++, don't return an invalid declaration. We can't recover well from
11996   // the cases where we make the type anonymous.
11997   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
11998 }
11999 
12000 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
12001   AdjustDeclIfTemplate(TagD);
12002   TagDecl *Tag = cast<TagDecl>(TagD);
12003 
12004   // Enter the tag context.
12005   PushDeclContext(S, Tag);
12006 
12007   ActOnDocumentableDecl(TagD);
12008 
12009   // If there's a #pragma GCC visibility in scope, set the visibility of this
12010   // record.
12011   AddPushedVisibilityAttribute(Tag);
12012 }
12013 
12014 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
12015   assert(isa<ObjCContainerDecl>(IDecl) &&
12016          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
12017   DeclContext *OCD = cast<DeclContext>(IDecl);
12018   assert(getContainingDC(OCD) == CurContext &&
12019       "The next DeclContext should be lexically contained in the current one.");
12020   CurContext = OCD;
12021   return IDecl;
12022 }
12023 
12024 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
12025                                            SourceLocation FinalLoc,
12026                                            bool IsFinalSpelledSealed,
12027                                            SourceLocation LBraceLoc) {
12028   AdjustDeclIfTemplate(TagD);
12029   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
12030 
12031   FieldCollector->StartClass();
12032 
12033   if (!Record->getIdentifier())
12034     return;
12035 
12036   if (FinalLoc.isValid())
12037     Record->addAttr(new (Context)
12038                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
12039 
12040   // C++ [class]p2:
12041   //   [...] The class-name is also inserted into the scope of the
12042   //   class itself; this is known as the injected-class-name. For
12043   //   purposes of access checking, the injected-class-name is treated
12044   //   as if it were a public member name.
12045   CXXRecordDecl *InjectedClassName
12046     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
12047                             Record->getLocStart(), Record->getLocation(),
12048                             Record->getIdentifier(),
12049                             /*PrevDecl=*/nullptr,
12050                             /*DelayTypeCreation=*/true);
12051   Context.getTypeDeclType(InjectedClassName, Record);
12052   InjectedClassName->setImplicit();
12053   InjectedClassName->setAccess(AS_public);
12054   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
12055       InjectedClassName->setDescribedClassTemplate(Template);
12056   PushOnScopeChains(InjectedClassName, S);
12057   assert(InjectedClassName->isInjectedClassName() &&
12058          "Broken injected-class-name");
12059 }
12060 
12061 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
12062                                     SourceLocation RBraceLoc) {
12063   AdjustDeclIfTemplate(TagD);
12064   TagDecl *Tag = cast<TagDecl>(TagD);
12065   Tag->setRBraceLoc(RBraceLoc);
12066 
12067   // Make sure we "complete" the definition even it is invalid.
12068   if (Tag->isBeingDefined()) {
12069     assert(Tag->isInvalidDecl() && "We should already have completed it");
12070     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12071       RD->completeDefinition();
12072   }
12073 
12074   if (isa<CXXRecordDecl>(Tag))
12075     FieldCollector->FinishClass();
12076 
12077   // Exit this scope of this tag's definition.
12078   PopDeclContext();
12079 
12080   if (getCurLexicalContext()->isObjCContainer() &&
12081       Tag->getDeclContext()->isFileContext())
12082     Tag->setTopLevelDeclInObjCContainer();
12083 
12084   // Notify the consumer that we've defined a tag.
12085   if (!Tag->isInvalidDecl())
12086     Consumer.HandleTagDeclDefinition(Tag);
12087 }
12088 
12089 void Sema::ActOnObjCContainerFinishDefinition() {
12090   // Exit this scope of this interface definition.
12091   PopDeclContext();
12092 }
12093 
12094 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
12095   assert(DC == CurContext && "Mismatch of container contexts");
12096   OriginalLexicalContext = DC;
12097   ActOnObjCContainerFinishDefinition();
12098 }
12099 
12100 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
12101   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
12102   OriginalLexicalContext = nullptr;
12103 }
12104 
12105 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
12106   AdjustDeclIfTemplate(TagD);
12107   TagDecl *Tag = cast<TagDecl>(TagD);
12108   Tag->setInvalidDecl();
12109 
12110   // Make sure we "complete" the definition even it is invalid.
12111   if (Tag->isBeingDefined()) {
12112     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12113       RD->completeDefinition();
12114   }
12115 
12116   // We're undoing ActOnTagStartDefinition here, not
12117   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
12118   // the FieldCollector.
12119 
12120   PopDeclContext();
12121 }
12122 
12123 // Note that FieldName may be null for anonymous bitfields.
12124 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
12125                                 IdentifierInfo *FieldName,
12126                                 QualType FieldTy, bool IsMsStruct,
12127                                 Expr *BitWidth, bool *ZeroWidth) {
12128   // Default to true; that shouldn't confuse checks for emptiness
12129   if (ZeroWidth)
12130     *ZeroWidth = true;
12131 
12132   // C99 6.7.2.1p4 - verify the field type.
12133   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
12134   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
12135     // Handle incomplete types with specific error.
12136     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
12137       return ExprError();
12138     if (FieldName)
12139       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12140         << FieldName << FieldTy << BitWidth->getSourceRange();
12141     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12142       << FieldTy << BitWidth->getSourceRange();
12143   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12144                                              UPPC_BitFieldWidth))
12145     return ExprError();
12146 
12147   // If the bit-width is type- or value-dependent, don't try to check
12148   // it now.
12149   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
12150     return BitWidth;
12151 
12152   llvm::APSInt Value;
12153   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
12154   if (ICE.isInvalid())
12155     return ICE;
12156   BitWidth = ICE.get();
12157 
12158   if (Value != 0 && ZeroWidth)
12159     *ZeroWidth = false;
12160 
12161   // Zero-width bitfield is ok for anonymous field.
12162   if (Value == 0 && FieldName)
12163     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
12164 
12165   if (Value.isSigned() && Value.isNegative()) {
12166     if (FieldName)
12167       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
12168                << FieldName << Value.toString(10);
12169     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
12170       << Value.toString(10);
12171   }
12172 
12173   if (!FieldTy->isDependentType()) {
12174     uint64_t TypeSize = Context.getTypeSize(FieldTy);
12175     if (Value.getZExtValue() > TypeSize) {
12176       if (!getLangOpts().CPlusPlus || IsMsStruct ||
12177           Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12178         if (FieldName)
12179           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
12180             << FieldName << (unsigned)Value.getZExtValue()
12181             << (unsigned)TypeSize;
12182 
12183         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
12184           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12185       }
12186 
12187       if (FieldName)
12188         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
12189           << FieldName << (unsigned)Value.getZExtValue()
12190           << (unsigned)TypeSize;
12191       else
12192         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
12193           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12194     }
12195   }
12196 
12197   return BitWidth;
12198 }
12199 
12200 /// ActOnField - Each field of a C struct/union is passed into this in order
12201 /// to create a FieldDecl object for it.
12202 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
12203                        Declarator &D, Expr *BitfieldWidth) {
12204   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
12205                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
12206                                /*InitStyle=*/ICIS_NoInit, AS_public);
12207   return Res;
12208 }
12209 
12210 /// HandleField - Analyze a field of a C struct or a C++ data member.
12211 ///
12212 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
12213                              SourceLocation DeclStart,
12214                              Declarator &D, Expr *BitWidth,
12215                              InClassInitStyle InitStyle,
12216                              AccessSpecifier AS) {
12217   IdentifierInfo *II = D.getIdentifier();
12218   SourceLocation Loc = DeclStart;
12219   if (II) Loc = D.getIdentifierLoc();
12220 
12221   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12222   QualType T = TInfo->getType();
12223   if (getLangOpts().CPlusPlus) {
12224     CheckExtraCXXDefaultArguments(D);
12225 
12226     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12227                                         UPPC_DataMemberType)) {
12228       D.setInvalidType();
12229       T = Context.IntTy;
12230       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12231     }
12232   }
12233 
12234   // TR 18037 does not allow fields to be declared with address spaces.
12235   if (T.getQualifiers().hasAddressSpace()) {
12236     Diag(Loc, diag::err_field_with_address_space);
12237     D.setInvalidType();
12238   }
12239 
12240   // OpenCL 1.2 spec, s6.9 r:
12241   // The event type cannot be used to declare a structure or union field.
12242   if (LangOpts.OpenCL && T->isEventT()) {
12243     Diag(Loc, diag::err_event_t_struct_field);
12244     D.setInvalidType();
12245   }
12246 
12247   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12248 
12249   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12250     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12251          diag::err_invalid_thread)
12252       << DeclSpec::getSpecifierName(TSCS);
12253 
12254   // Check to see if this name was declared as a member previously
12255   NamedDecl *PrevDecl = nullptr;
12256   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12257   LookupName(Previous, S);
12258   switch (Previous.getResultKind()) {
12259     case LookupResult::Found:
12260     case LookupResult::FoundUnresolvedValue:
12261       PrevDecl = Previous.getAsSingle<NamedDecl>();
12262       break;
12263 
12264     case LookupResult::FoundOverloaded:
12265       PrevDecl = Previous.getRepresentativeDecl();
12266       break;
12267 
12268     case LookupResult::NotFound:
12269     case LookupResult::NotFoundInCurrentInstantiation:
12270     case LookupResult::Ambiguous:
12271       break;
12272   }
12273   Previous.suppressDiagnostics();
12274 
12275   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12276     // Maybe we will complain about the shadowed template parameter.
12277     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12278     // Just pretend that we didn't see the previous declaration.
12279     PrevDecl = nullptr;
12280   }
12281 
12282   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12283     PrevDecl = nullptr;
12284 
12285   bool Mutable
12286     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
12287   SourceLocation TSSL = D.getLocStart();
12288   FieldDecl *NewFD
12289     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
12290                      TSSL, AS, PrevDecl, &D);
12291 
12292   if (NewFD->isInvalidDecl())
12293     Record->setInvalidDecl();
12294 
12295   if (D.getDeclSpec().isModulePrivateSpecified())
12296     NewFD->setModulePrivate();
12297 
12298   if (NewFD->isInvalidDecl() && PrevDecl) {
12299     // Don't introduce NewFD into scope; there's already something
12300     // with the same name in the same scope.
12301   } else if (II) {
12302     PushOnScopeChains(NewFD, S);
12303   } else
12304     Record->addDecl(NewFD);
12305 
12306   return NewFD;
12307 }
12308 
12309 /// \brief Build a new FieldDecl and check its well-formedness.
12310 ///
12311 /// This routine builds a new FieldDecl given the fields name, type,
12312 /// record, etc. \p PrevDecl should refer to any previous declaration
12313 /// with the same name and in the same scope as the field to be
12314 /// created.
12315 ///
12316 /// \returns a new FieldDecl.
12317 ///
12318 /// \todo The Declarator argument is a hack. It will be removed once
12319 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
12320                                 TypeSourceInfo *TInfo,
12321                                 RecordDecl *Record, SourceLocation Loc,
12322                                 bool Mutable, Expr *BitWidth,
12323                                 InClassInitStyle InitStyle,
12324                                 SourceLocation TSSL,
12325                                 AccessSpecifier AS, NamedDecl *PrevDecl,
12326                                 Declarator *D) {
12327   IdentifierInfo *II = Name.getAsIdentifierInfo();
12328   bool InvalidDecl = false;
12329   if (D) InvalidDecl = D->isInvalidType();
12330 
12331   // If we receive a broken type, recover by assuming 'int' and
12332   // marking this declaration as invalid.
12333   if (T.isNull()) {
12334     InvalidDecl = true;
12335     T = Context.IntTy;
12336   }
12337 
12338   QualType EltTy = Context.getBaseElementType(T);
12339   if (!EltTy->isDependentType()) {
12340     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
12341       // Fields of incomplete type force their record to be invalid.
12342       Record->setInvalidDecl();
12343       InvalidDecl = true;
12344     } else {
12345       NamedDecl *Def;
12346       EltTy->isIncompleteType(&Def);
12347       if (Def && Def->isInvalidDecl()) {
12348         Record->setInvalidDecl();
12349         InvalidDecl = true;
12350       }
12351     }
12352   }
12353 
12354   // OpenCL v1.2 s6.9.c: bitfields are not supported.
12355   if (BitWidth && getLangOpts().OpenCL) {
12356     Diag(Loc, diag::err_opencl_bitfields);
12357     InvalidDecl = true;
12358   }
12359 
12360   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12361   // than a variably modified type.
12362   if (!InvalidDecl && T->isVariablyModifiedType()) {
12363     bool SizeIsNegative;
12364     llvm::APSInt Oversized;
12365 
12366     TypeSourceInfo *FixedTInfo =
12367       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
12368                                                     SizeIsNegative,
12369                                                     Oversized);
12370     if (FixedTInfo) {
12371       Diag(Loc, diag::warn_illegal_constant_array_size);
12372       TInfo = FixedTInfo;
12373       T = FixedTInfo->getType();
12374     } else {
12375       if (SizeIsNegative)
12376         Diag(Loc, diag::err_typecheck_negative_array_size);
12377       else if (Oversized.getBoolValue())
12378         Diag(Loc, diag::err_array_too_large)
12379           << Oversized.toString(10);
12380       else
12381         Diag(Loc, diag::err_typecheck_field_variable_size);
12382       InvalidDecl = true;
12383     }
12384   }
12385 
12386   // Fields can not have abstract class types
12387   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
12388                                              diag::err_abstract_type_in_decl,
12389                                              AbstractFieldType))
12390     InvalidDecl = true;
12391 
12392   bool ZeroWidth = false;
12393   // If this is declared as a bit-field, check the bit-field.
12394   if (!InvalidDecl && BitWidth) {
12395     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
12396                               &ZeroWidth).get();
12397     if (!BitWidth) {
12398       InvalidDecl = true;
12399       BitWidth = nullptr;
12400       ZeroWidth = false;
12401     }
12402   }
12403 
12404   // Check that 'mutable' is consistent with the type of the declaration.
12405   if (!InvalidDecl && Mutable) {
12406     unsigned DiagID = 0;
12407     if (T->isReferenceType())
12408       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
12409                                         : diag::err_mutable_reference;
12410     else if (T.isConstQualified())
12411       DiagID = diag::err_mutable_const;
12412 
12413     if (DiagID) {
12414       SourceLocation ErrLoc = Loc;
12415       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
12416         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
12417       Diag(ErrLoc, DiagID);
12418       if (DiagID != diag::ext_mutable_reference) {
12419         Mutable = false;
12420         InvalidDecl = true;
12421       }
12422     }
12423   }
12424 
12425   // C++11 [class.union]p8 (DR1460):
12426   //   At most one variant member of a union may have a
12427   //   brace-or-equal-initializer.
12428   if (InitStyle != ICIS_NoInit)
12429     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
12430 
12431   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
12432                                        BitWidth, Mutable, InitStyle);
12433   if (InvalidDecl)
12434     NewFD->setInvalidDecl();
12435 
12436   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
12437     Diag(Loc, diag::err_duplicate_member) << II;
12438     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12439     NewFD->setInvalidDecl();
12440   }
12441 
12442   if (!InvalidDecl && getLangOpts().CPlusPlus) {
12443     if (Record->isUnion()) {
12444       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12445         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
12446         if (RDecl->getDefinition()) {
12447           // C++ [class.union]p1: An object of a class with a non-trivial
12448           // constructor, a non-trivial copy constructor, a non-trivial
12449           // destructor, or a non-trivial copy assignment operator
12450           // cannot be a member of a union, nor can an array of such
12451           // objects.
12452           if (CheckNontrivialField(NewFD))
12453             NewFD->setInvalidDecl();
12454         }
12455       }
12456 
12457       // C++ [class.union]p1: If a union contains a member of reference type,
12458       // the program is ill-formed, except when compiling with MSVC extensions
12459       // enabled.
12460       if (EltTy->isReferenceType()) {
12461         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
12462                                     diag::ext_union_member_of_reference_type :
12463                                     diag::err_union_member_of_reference_type)
12464           << NewFD->getDeclName() << EltTy;
12465         if (!getLangOpts().MicrosoftExt)
12466           NewFD->setInvalidDecl();
12467       }
12468     }
12469   }
12470 
12471   // FIXME: We need to pass in the attributes given an AST
12472   // representation, not a parser representation.
12473   if (D) {
12474     // FIXME: The current scope is almost... but not entirely... correct here.
12475     ProcessDeclAttributes(getCurScope(), NewFD, *D);
12476 
12477     if (NewFD->hasAttrs())
12478       CheckAlignasUnderalignment(NewFD);
12479   }
12480 
12481   // In auto-retain/release, infer strong retension for fields of
12482   // retainable type.
12483   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
12484     NewFD->setInvalidDecl();
12485 
12486   if (T.isObjCGCWeak())
12487     Diag(Loc, diag::warn_attribute_weak_on_field);
12488 
12489   NewFD->setAccess(AS);
12490   return NewFD;
12491 }
12492 
12493 bool Sema::CheckNontrivialField(FieldDecl *FD) {
12494   assert(FD);
12495   assert(getLangOpts().CPlusPlus && "valid check only for C++");
12496 
12497   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
12498     return false;
12499 
12500   QualType EltTy = Context.getBaseElementType(FD->getType());
12501   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12502     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
12503     if (RDecl->getDefinition()) {
12504       // We check for copy constructors before constructors
12505       // because otherwise we'll never get complaints about
12506       // copy constructors.
12507 
12508       CXXSpecialMember member = CXXInvalid;
12509       // We're required to check for any non-trivial constructors. Since the
12510       // implicit default constructor is suppressed if there are any
12511       // user-declared constructors, we just need to check that there is a
12512       // trivial default constructor and a trivial copy constructor. (We don't
12513       // worry about move constructors here, since this is a C++98 check.)
12514       if (RDecl->hasNonTrivialCopyConstructor())
12515         member = CXXCopyConstructor;
12516       else if (!RDecl->hasTrivialDefaultConstructor())
12517         member = CXXDefaultConstructor;
12518       else if (RDecl->hasNonTrivialCopyAssignment())
12519         member = CXXCopyAssignment;
12520       else if (RDecl->hasNonTrivialDestructor())
12521         member = CXXDestructor;
12522 
12523       if (member != CXXInvalid) {
12524         if (!getLangOpts().CPlusPlus11 &&
12525             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
12526           // Objective-C++ ARC: it is an error to have a non-trivial field of
12527           // a union. However, system headers in Objective-C programs
12528           // occasionally have Objective-C lifetime objects within unions,
12529           // and rather than cause the program to fail, we make those
12530           // members unavailable.
12531           SourceLocation Loc = FD->getLocation();
12532           if (getSourceManager().isInSystemHeader(Loc)) {
12533             if (!FD->hasAttr<UnavailableAttr>())
12534               FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12535                                   "this system field has retaining ownership",
12536                                   Loc));
12537             return false;
12538           }
12539         }
12540 
12541         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
12542                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
12543                diag::err_illegal_union_or_anon_struct_member)
12544           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
12545         DiagnoseNontrivial(RDecl, member);
12546         return !getLangOpts().CPlusPlus11;
12547       }
12548     }
12549   }
12550 
12551   return false;
12552 }
12553 
12554 /// TranslateIvarVisibility - Translate visibility from a token ID to an
12555 ///  AST enum value.
12556 static ObjCIvarDecl::AccessControl
12557 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
12558   switch (ivarVisibility) {
12559   default: llvm_unreachable("Unknown visitibility kind");
12560   case tok::objc_private: return ObjCIvarDecl::Private;
12561   case tok::objc_public: return ObjCIvarDecl::Public;
12562   case tok::objc_protected: return ObjCIvarDecl::Protected;
12563   case tok::objc_package: return ObjCIvarDecl::Package;
12564   }
12565 }
12566 
12567 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
12568 /// in order to create an IvarDecl object for it.
12569 Decl *Sema::ActOnIvar(Scope *S,
12570                                 SourceLocation DeclStart,
12571                                 Declarator &D, Expr *BitfieldWidth,
12572                                 tok::ObjCKeywordKind Visibility) {
12573 
12574   IdentifierInfo *II = D.getIdentifier();
12575   Expr *BitWidth = (Expr*)BitfieldWidth;
12576   SourceLocation Loc = DeclStart;
12577   if (II) Loc = D.getIdentifierLoc();
12578 
12579   // FIXME: Unnamed fields can be handled in various different ways, for
12580   // example, unnamed unions inject all members into the struct namespace!
12581 
12582   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12583   QualType T = TInfo->getType();
12584 
12585   if (BitWidth) {
12586     // 6.7.2.1p3, 6.7.2.1p4
12587     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
12588     if (!BitWidth)
12589       D.setInvalidType();
12590   } else {
12591     // Not a bitfield.
12592 
12593     // validate II.
12594 
12595   }
12596   if (T->isReferenceType()) {
12597     Diag(Loc, diag::err_ivar_reference_type);
12598     D.setInvalidType();
12599   }
12600   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12601   // than a variably modified type.
12602   else if (T->isVariablyModifiedType()) {
12603     Diag(Loc, diag::err_typecheck_ivar_variable_size);
12604     D.setInvalidType();
12605   }
12606 
12607   // Get the visibility (access control) for this ivar.
12608   ObjCIvarDecl::AccessControl ac =
12609     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
12610                                         : ObjCIvarDecl::None;
12611   // Must set ivar's DeclContext to its enclosing interface.
12612   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
12613   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
12614     return nullptr;
12615   ObjCContainerDecl *EnclosingContext;
12616   if (ObjCImplementationDecl *IMPDecl =
12617       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12618     if (LangOpts.ObjCRuntime.isFragile()) {
12619     // Case of ivar declared in an implementation. Context is that of its class.
12620       EnclosingContext = IMPDecl->getClassInterface();
12621       assert(EnclosingContext && "Implementation has no class interface!");
12622     }
12623     else
12624       EnclosingContext = EnclosingDecl;
12625   } else {
12626     if (ObjCCategoryDecl *CDecl =
12627         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12628       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
12629         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
12630         return nullptr;
12631       }
12632     }
12633     EnclosingContext = EnclosingDecl;
12634   }
12635 
12636   // Construct the decl.
12637   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
12638                                              DeclStart, Loc, II, T,
12639                                              TInfo, ac, (Expr *)BitfieldWidth);
12640 
12641   if (II) {
12642     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
12643                                            ForRedeclaration);
12644     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
12645         && !isa<TagDecl>(PrevDecl)) {
12646       Diag(Loc, diag::err_duplicate_member) << II;
12647       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12648       NewID->setInvalidDecl();
12649     }
12650   }
12651 
12652   // Process attributes attached to the ivar.
12653   ProcessDeclAttributes(S, NewID, D);
12654 
12655   if (D.isInvalidType())
12656     NewID->setInvalidDecl();
12657 
12658   // In ARC, infer 'retaining' for ivars of retainable type.
12659   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
12660     NewID->setInvalidDecl();
12661 
12662   if (D.getDeclSpec().isModulePrivateSpecified())
12663     NewID->setModulePrivate();
12664 
12665   if (II) {
12666     // FIXME: When interfaces are DeclContexts, we'll need to add
12667     // these to the interface.
12668     S->AddDecl(NewID);
12669     IdResolver.AddDecl(NewID);
12670   }
12671 
12672   if (LangOpts.ObjCRuntime.isNonFragile() &&
12673       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
12674     Diag(Loc, diag::warn_ivars_in_interface);
12675 
12676   return NewID;
12677 }
12678 
12679 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
12680 /// class and class extensions. For every class \@interface and class
12681 /// extension \@interface, if the last ivar is a bitfield of any type,
12682 /// then add an implicit `char :0` ivar to the end of that interface.
12683 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
12684                              SmallVectorImpl<Decl *> &AllIvarDecls) {
12685   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
12686     return;
12687 
12688   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
12689   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
12690 
12691   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
12692     return;
12693   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
12694   if (!ID) {
12695     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
12696       if (!CD->IsClassExtension())
12697         return;
12698     }
12699     // No need to add this to end of @implementation.
12700     else
12701       return;
12702   }
12703   // All conditions are met. Add a new bitfield to the tail end of ivars.
12704   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
12705   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
12706 
12707   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
12708                               DeclLoc, DeclLoc, nullptr,
12709                               Context.CharTy,
12710                               Context.getTrivialTypeSourceInfo(Context.CharTy,
12711                                                                DeclLoc),
12712                               ObjCIvarDecl::Private, BW,
12713                               true);
12714   AllIvarDecls.push_back(Ivar);
12715 }
12716 
12717 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
12718                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
12719                        SourceLocation RBrac, AttributeList *Attr) {
12720   assert(EnclosingDecl && "missing record or interface decl");
12721 
12722   // If this is an Objective-C @implementation or category and we have
12723   // new fields here we should reset the layout of the interface since
12724   // it will now change.
12725   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
12726     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
12727     switch (DC->getKind()) {
12728     default: break;
12729     case Decl::ObjCCategory:
12730       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
12731       break;
12732     case Decl::ObjCImplementation:
12733       Context.
12734         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
12735       break;
12736     }
12737   }
12738 
12739   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
12740 
12741   // Start counting up the number of named members; make sure to include
12742   // members of anonymous structs and unions in the total.
12743   unsigned NumNamedMembers = 0;
12744   if (Record) {
12745     for (const auto *I : Record->decls()) {
12746       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
12747         if (IFD->getDeclName())
12748           ++NumNamedMembers;
12749     }
12750   }
12751 
12752   // Verify that all the fields are okay.
12753   SmallVector<FieldDecl*, 32> RecFields;
12754 
12755   bool ARCErrReported = false;
12756   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
12757        i != end; ++i) {
12758     FieldDecl *FD = cast<FieldDecl>(*i);
12759 
12760     // Get the type for the field.
12761     const Type *FDTy = FD->getType().getTypePtr();
12762 
12763     if (!FD->isAnonymousStructOrUnion()) {
12764       // Remember all fields written by the user.
12765       RecFields.push_back(FD);
12766     }
12767 
12768     // If the field is already invalid for some reason, don't emit more
12769     // diagnostics about it.
12770     if (FD->isInvalidDecl()) {
12771       EnclosingDecl->setInvalidDecl();
12772       continue;
12773     }
12774 
12775     // C99 6.7.2.1p2:
12776     //   A structure or union shall not contain a member with
12777     //   incomplete or function type (hence, a structure shall not
12778     //   contain an instance of itself, but may contain a pointer to
12779     //   an instance of itself), except that the last member of a
12780     //   structure with more than one named member may have incomplete
12781     //   array type; such a structure (and any union containing,
12782     //   possibly recursively, a member that is such a structure)
12783     //   shall not be a member of a structure or an element of an
12784     //   array.
12785     if (FDTy->isFunctionType()) {
12786       // Field declared as a function.
12787       Diag(FD->getLocation(), diag::err_field_declared_as_function)
12788         << FD->getDeclName();
12789       FD->setInvalidDecl();
12790       EnclosingDecl->setInvalidDecl();
12791       continue;
12792     } else if (FDTy->isIncompleteArrayType() && Record &&
12793                ((i + 1 == Fields.end() && !Record->isUnion()) ||
12794                 ((getLangOpts().MicrosoftExt ||
12795                   getLangOpts().CPlusPlus) &&
12796                  (i + 1 == Fields.end() || Record->isUnion())))) {
12797       // Flexible array member.
12798       // Microsoft and g++ is more permissive regarding flexible array.
12799       // It will accept flexible array in union and also
12800       // as the sole element of a struct/class.
12801       unsigned DiagID = 0;
12802       if (Record->isUnion())
12803         DiagID = getLangOpts().MicrosoftExt
12804                      ? diag::ext_flexible_array_union_ms
12805                      : getLangOpts().CPlusPlus
12806                            ? diag::ext_flexible_array_union_gnu
12807                            : diag::err_flexible_array_union;
12808       else if (Fields.size() == 1)
12809         DiagID = getLangOpts().MicrosoftExt
12810                      ? diag::ext_flexible_array_empty_aggregate_ms
12811                      : getLangOpts().CPlusPlus
12812                            ? diag::ext_flexible_array_empty_aggregate_gnu
12813                            : NumNamedMembers < 1
12814                                  ? diag::err_flexible_array_empty_aggregate
12815                                  : 0;
12816 
12817       if (DiagID)
12818         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
12819                                         << Record->getTagKind();
12820       // While the layout of types that contain virtual bases is not specified
12821       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
12822       // virtual bases after the derived members.  This would make a flexible
12823       // array member declared at the end of an object not adjacent to the end
12824       // of the type.
12825       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
12826         if (RD->getNumVBases() != 0)
12827           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
12828             << FD->getDeclName() << Record->getTagKind();
12829       if (!getLangOpts().C99)
12830         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
12831           << FD->getDeclName() << Record->getTagKind();
12832 
12833       // If the element type has a non-trivial destructor, we would not
12834       // implicitly destroy the elements, so disallow it for now.
12835       //
12836       // FIXME: GCC allows this. We should probably either implicitly delete
12837       // the destructor of the containing class, or just allow this.
12838       QualType BaseElem = Context.getBaseElementType(FD->getType());
12839       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
12840         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
12841           << FD->getDeclName() << FD->getType();
12842         FD->setInvalidDecl();
12843         EnclosingDecl->setInvalidDecl();
12844         continue;
12845       }
12846       // Okay, we have a legal flexible array member at the end of the struct.
12847       Record->setHasFlexibleArrayMember(true);
12848     } else if (!FDTy->isDependentType() &&
12849                RequireCompleteType(FD->getLocation(), FD->getType(),
12850                                    diag::err_field_incomplete)) {
12851       // Incomplete type
12852       FD->setInvalidDecl();
12853       EnclosingDecl->setInvalidDecl();
12854       continue;
12855     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
12856       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
12857         // A type which contains a flexible array member is considered to be a
12858         // flexible array member.
12859         Record->setHasFlexibleArrayMember(true);
12860         if (!Record->isUnion()) {
12861           // If this is a struct/class and this is not the last element, reject
12862           // it.  Note that GCC supports variable sized arrays in the middle of
12863           // structures.
12864           if (i + 1 != Fields.end())
12865             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
12866               << FD->getDeclName() << FD->getType();
12867           else {
12868             // We support flexible arrays at the end of structs in
12869             // other structs as an extension.
12870             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12871               << FD->getDeclName();
12872           }
12873         }
12874       }
12875       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12876           RequireNonAbstractType(FD->getLocation(), FD->getType(),
12877                                  diag::err_abstract_type_in_decl,
12878                                  AbstractIvarType)) {
12879         // Ivars can not have abstract class types
12880         FD->setInvalidDecl();
12881       }
12882       if (Record && FDTTy->getDecl()->hasObjectMember())
12883         Record->setHasObjectMember(true);
12884       if (Record && FDTTy->getDecl()->hasVolatileMember())
12885         Record->setHasVolatileMember(true);
12886     } else if (FDTy->isObjCObjectType()) {
12887       /// A field cannot be an Objective-c object
12888       Diag(FD->getLocation(), diag::err_statically_allocated_object)
12889         << FixItHint::CreateInsertion(FD->getLocation(), "*");
12890       QualType T = Context.getObjCObjectPointerType(FD->getType());
12891       FD->setType(T);
12892     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12893                (!getLangOpts().CPlusPlus || Record->isUnion())) {
12894       // It's an error in ARC if a field has lifetime.
12895       // We don't want to report this in a system header, though,
12896       // so we just make the field unavailable.
12897       // FIXME: that's really not sufficient; we need to make the type
12898       // itself invalid to, say, initialize or copy.
12899       QualType T = FD->getType();
12900       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12901       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12902         SourceLocation loc = FD->getLocation();
12903         if (getSourceManager().isInSystemHeader(loc)) {
12904           if (!FD->hasAttr<UnavailableAttr>()) {
12905             FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12906                               "this system field has retaining ownership",
12907                               loc));
12908           }
12909         } else {
12910           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
12911             << T->isBlockPointerType() << Record->getTagKind();
12912         }
12913         ARCErrReported = true;
12914       }
12915     } else if (getLangOpts().ObjC1 &&
12916                getLangOpts().getGC() != LangOptions::NonGC &&
12917                Record && !Record->hasObjectMember()) {
12918       if (FD->getType()->isObjCObjectPointerType() ||
12919           FD->getType().isObjCGCStrong())
12920         Record->setHasObjectMember(true);
12921       else if (Context.getAsArrayType(FD->getType())) {
12922         QualType BaseType = Context.getBaseElementType(FD->getType());
12923         if (BaseType->isRecordType() &&
12924             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
12925           Record->setHasObjectMember(true);
12926         else if (BaseType->isObjCObjectPointerType() ||
12927                  BaseType.isObjCGCStrong())
12928                Record->setHasObjectMember(true);
12929       }
12930     }
12931     if (Record && FD->getType().isVolatileQualified())
12932       Record->setHasVolatileMember(true);
12933     // Keep track of the number of named members.
12934     if (FD->getIdentifier())
12935       ++NumNamedMembers;
12936   }
12937 
12938   // Okay, we successfully defined 'Record'.
12939   if (Record) {
12940     bool Completed = false;
12941     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12942       if (!CXXRecord->isInvalidDecl()) {
12943         // Set access bits correctly on the directly-declared conversions.
12944         for (CXXRecordDecl::conversion_iterator
12945                I = CXXRecord->conversion_begin(),
12946                E = CXXRecord->conversion_end(); I != E; ++I)
12947           I.setAccess((*I)->getAccess());
12948 
12949         if (!CXXRecord->isDependentType()) {
12950           if (CXXRecord->hasUserDeclaredDestructor()) {
12951             // Adjust user-defined destructor exception spec.
12952             if (getLangOpts().CPlusPlus11)
12953               AdjustDestructorExceptionSpec(CXXRecord,
12954                                             CXXRecord->getDestructor());
12955           }
12956 
12957           // Add any implicitly-declared members to this class.
12958           AddImplicitlyDeclaredMembersToClass(CXXRecord);
12959 
12960           // If we have virtual base classes, we may end up finding multiple
12961           // final overriders for a given virtual function. Check for this
12962           // problem now.
12963           if (CXXRecord->getNumVBases()) {
12964             CXXFinalOverriderMap FinalOverriders;
12965             CXXRecord->getFinalOverriders(FinalOverriders);
12966 
12967             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12968                                              MEnd = FinalOverriders.end();
12969                  M != MEnd; ++M) {
12970               for (OverridingMethods::iterator SO = M->second.begin(),
12971                                             SOEnd = M->second.end();
12972                    SO != SOEnd; ++SO) {
12973                 assert(SO->second.size() > 0 &&
12974                        "Virtual function without overridding functions?");
12975                 if (SO->second.size() == 1)
12976                   continue;
12977 
12978                 // C++ [class.virtual]p2:
12979                 //   In a derived class, if a virtual member function of a base
12980                 //   class subobject has more than one final overrider the
12981                 //   program is ill-formed.
12982                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
12983                   << (const NamedDecl *)M->first << Record;
12984                 Diag(M->first->getLocation(),
12985                      diag::note_overridden_virtual_function);
12986                 for (OverridingMethods::overriding_iterator
12987                           OM = SO->second.begin(),
12988                        OMEnd = SO->second.end();
12989                      OM != OMEnd; ++OM)
12990                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
12991                     << (const NamedDecl *)M->first << OM->Method->getParent();
12992 
12993                 Record->setInvalidDecl();
12994               }
12995             }
12996             CXXRecord->completeDefinition(&FinalOverriders);
12997             Completed = true;
12998           }
12999         }
13000       }
13001     }
13002 
13003     if (!Completed)
13004       Record->completeDefinition();
13005 
13006     if (Record->hasAttrs()) {
13007       CheckAlignasUnderalignment(Record);
13008 
13009       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
13010         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
13011                                            IA->getRange(), IA->getBestCase(),
13012                                            IA->getSemanticSpelling());
13013     }
13014 
13015     // Check if the structure/union declaration is a type that can have zero
13016     // size in C. For C this is a language extension, for C++ it may cause
13017     // compatibility problems.
13018     bool CheckForZeroSize;
13019     if (!getLangOpts().CPlusPlus) {
13020       CheckForZeroSize = true;
13021     } else {
13022       // For C++ filter out types that cannot be referenced in C code.
13023       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
13024       CheckForZeroSize =
13025           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
13026           !CXXRecord->isDependentType() &&
13027           CXXRecord->isCLike();
13028     }
13029     if (CheckForZeroSize) {
13030       bool ZeroSize = true;
13031       bool IsEmpty = true;
13032       unsigned NonBitFields = 0;
13033       for (RecordDecl::field_iterator I = Record->field_begin(),
13034                                       E = Record->field_end();
13035            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
13036         IsEmpty = false;
13037         if (I->isUnnamedBitfield()) {
13038           if (I->getBitWidthValue(Context) > 0)
13039             ZeroSize = false;
13040         } else {
13041           ++NonBitFields;
13042           QualType FieldType = I->getType();
13043           if (FieldType->isIncompleteType() ||
13044               !Context.getTypeSizeInChars(FieldType).isZero())
13045             ZeroSize = false;
13046         }
13047       }
13048 
13049       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
13050       // allowed in C++, but warn if its declaration is inside
13051       // extern "C" block.
13052       if (ZeroSize) {
13053         Diag(RecLoc, getLangOpts().CPlusPlus ?
13054                          diag::warn_zero_size_struct_union_in_extern_c :
13055                          diag::warn_zero_size_struct_union_compat)
13056           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
13057       }
13058 
13059       // Structs without named members are extension in C (C99 6.7.2.1p7),
13060       // but are accepted by GCC.
13061       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
13062         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
13063                                diag::ext_no_named_members_in_struct_union)
13064           << Record->isUnion();
13065       }
13066     }
13067   } else {
13068     ObjCIvarDecl **ClsFields =
13069       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
13070     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
13071       ID->setEndOfDefinitionLoc(RBrac);
13072       // Add ivar's to class's DeclContext.
13073       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13074         ClsFields[i]->setLexicalDeclContext(ID);
13075         ID->addDecl(ClsFields[i]);
13076       }
13077       // Must enforce the rule that ivars in the base classes may not be
13078       // duplicates.
13079       if (ID->getSuperClass())
13080         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
13081     } else if (ObjCImplementationDecl *IMPDecl =
13082                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13083       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
13084       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
13085         // Ivar declared in @implementation never belongs to the implementation.
13086         // Only it is in implementation's lexical context.
13087         ClsFields[I]->setLexicalDeclContext(IMPDecl);
13088       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
13089       IMPDecl->setIvarLBraceLoc(LBrac);
13090       IMPDecl->setIvarRBraceLoc(RBrac);
13091     } else if (ObjCCategoryDecl *CDecl =
13092                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13093       // case of ivars in class extension; all other cases have been
13094       // reported as errors elsewhere.
13095       // FIXME. Class extension does not have a LocEnd field.
13096       // CDecl->setLocEnd(RBrac);
13097       // Add ivar's to class extension's DeclContext.
13098       // Diagnose redeclaration of private ivars.
13099       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
13100       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13101         if (IDecl) {
13102           if (const ObjCIvarDecl *ClsIvar =
13103               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
13104             Diag(ClsFields[i]->getLocation(),
13105                  diag::err_duplicate_ivar_declaration);
13106             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
13107             continue;
13108           }
13109           for (const auto *Ext : IDecl->known_extensions()) {
13110             if (const ObjCIvarDecl *ClsExtIvar
13111                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
13112               Diag(ClsFields[i]->getLocation(),
13113                    diag::err_duplicate_ivar_declaration);
13114               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
13115               continue;
13116             }
13117           }
13118         }
13119         ClsFields[i]->setLexicalDeclContext(CDecl);
13120         CDecl->addDecl(ClsFields[i]);
13121       }
13122       CDecl->setIvarLBraceLoc(LBrac);
13123       CDecl->setIvarRBraceLoc(RBrac);
13124     }
13125   }
13126 
13127   if (Attr)
13128     ProcessDeclAttributeList(S, Record, Attr);
13129 }
13130 
13131 /// \brief Determine whether the given integral value is representable within
13132 /// the given type T.
13133 static bool isRepresentableIntegerValue(ASTContext &Context,
13134                                         llvm::APSInt &Value,
13135                                         QualType T) {
13136   assert(T->isIntegralType(Context) && "Integral type required!");
13137   unsigned BitWidth = Context.getIntWidth(T);
13138 
13139   if (Value.isUnsigned() || Value.isNonNegative()) {
13140     if (T->isSignedIntegerOrEnumerationType())
13141       --BitWidth;
13142     return Value.getActiveBits() <= BitWidth;
13143   }
13144   return Value.getMinSignedBits() <= BitWidth;
13145 }
13146 
13147 // \brief Given an integral type, return the next larger integral type
13148 // (or a NULL type of no such type exists).
13149 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
13150   // FIXME: Int128/UInt128 support, which also needs to be introduced into
13151   // enum checking below.
13152   assert(T->isIntegralType(Context) && "Integral type required!");
13153   const unsigned NumTypes = 4;
13154   QualType SignedIntegralTypes[NumTypes] = {
13155     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
13156   };
13157   QualType UnsignedIntegralTypes[NumTypes] = {
13158     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
13159     Context.UnsignedLongLongTy
13160   };
13161 
13162   unsigned BitWidth = Context.getTypeSize(T);
13163   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
13164                                                         : UnsignedIntegralTypes;
13165   for (unsigned I = 0; I != NumTypes; ++I)
13166     if (Context.getTypeSize(Types[I]) > BitWidth)
13167       return Types[I];
13168 
13169   return QualType();
13170 }
13171 
13172 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
13173                                           EnumConstantDecl *LastEnumConst,
13174                                           SourceLocation IdLoc,
13175                                           IdentifierInfo *Id,
13176                                           Expr *Val) {
13177   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13178   llvm::APSInt EnumVal(IntWidth);
13179   QualType EltTy;
13180 
13181   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
13182     Val = nullptr;
13183 
13184   if (Val)
13185     Val = DefaultLvalueConversion(Val).get();
13186 
13187   if (Val) {
13188     if (Enum->isDependentType() || Val->isTypeDependent())
13189       EltTy = Context.DependentTy;
13190     else {
13191       SourceLocation ExpLoc;
13192       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
13193           !getLangOpts().MSVCCompat) {
13194         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
13195         // constant-expression in the enumerator-definition shall be a converted
13196         // constant expression of the underlying type.
13197         EltTy = Enum->getIntegerType();
13198         ExprResult Converted =
13199           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
13200                                            CCEK_Enumerator);
13201         if (Converted.isInvalid())
13202           Val = nullptr;
13203         else
13204           Val = Converted.get();
13205       } else if (!Val->isValueDependent() &&
13206                  !(Val = VerifyIntegerConstantExpression(Val,
13207                                                          &EnumVal).get())) {
13208         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
13209       } else {
13210         if (Enum->isFixed()) {
13211           EltTy = Enum->getIntegerType();
13212 
13213           // In Obj-C and Microsoft mode, require the enumeration value to be
13214           // representable in the underlying type of the enumeration. In C++11,
13215           // we perform a non-narrowing conversion as part of converted constant
13216           // expression checking.
13217           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13218             if (getLangOpts().MSVCCompat) {
13219               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
13220               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13221             } else
13222               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
13223           } else
13224             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13225         } else if (getLangOpts().CPlusPlus) {
13226           // C++11 [dcl.enum]p5:
13227           //   If the underlying type is not fixed, the type of each enumerator
13228           //   is the type of its initializing value:
13229           //     - If an initializer is specified for an enumerator, the
13230           //       initializing value has the same type as the expression.
13231           EltTy = Val->getType();
13232         } else {
13233           // C99 6.7.2.2p2:
13234           //   The expression that defines the value of an enumeration constant
13235           //   shall be an integer constant expression that has a value
13236           //   representable as an int.
13237 
13238           // Complain if the value is not representable in an int.
13239           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
13240             Diag(IdLoc, diag::ext_enum_value_not_int)
13241               << EnumVal.toString(10) << Val->getSourceRange()
13242               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13243           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13244             // Force the type of the expression to 'int'.
13245             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
13246           }
13247           EltTy = Val->getType();
13248         }
13249       }
13250     }
13251   }
13252 
13253   if (!Val) {
13254     if (Enum->isDependentType())
13255       EltTy = Context.DependentTy;
13256     else if (!LastEnumConst) {
13257       // C++0x [dcl.enum]p5:
13258       //   If the underlying type is not fixed, the type of each enumerator
13259       //   is the type of its initializing value:
13260       //     - If no initializer is specified for the first enumerator, the
13261       //       initializing value has an unspecified integral type.
13262       //
13263       // GCC uses 'int' for its unspecified integral type, as does
13264       // C99 6.7.2.2p3.
13265       if (Enum->isFixed()) {
13266         EltTy = Enum->getIntegerType();
13267       }
13268       else {
13269         EltTy = Context.IntTy;
13270       }
13271     } else {
13272       // Assign the last value + 1.
13273       EnumVal = LastEnumConst->getInitVal();
13274       ++EnumVal;
13275       EltTy = LastEnumConst->getType();
13276 
13277       // Check for overflow on increment.
13278       if (EnumVal < LastEnumConst->getInitVal()) {
13279         // C++0x [dcl.enum]p5:
13280         //   If the underlying type is not fixed, the type of each enumerator
13281         //   is the type of its initializing value:
13282         //
13283         //     - Otherwise the type of the initializing value is the same as
13284         //       the type of the initializing value of the preceding enumerator
13285         //       unless the incremented value is not representable in that type,
13286         //       in which case the type is an unspecified integral type
13287         //       sufficient to contain the incremented value. If no such type
13288         //       exists, the program is ill-formed.
13289         QualType T = getNextLargerIntegralType(Context, EltTy);
13290         if (T.isNull() || Enum->isFixed()) {
13291           // There is no integral type larger enough to represent this
13292           // value. Complain, then allow the value to wrap around.
13293           EnumVal = LastEnumConst->getInitVal();
13294           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
13295           ++EnumVal;
13296           if (Enum->isFixed())
13297             // When the underlying type is fixed, this is ill-formed.
13298             Diag(IdLoc, diag::err_enumerator_wrapped)
13299               << EnumVal.toString(10)
13300               << EltTy;
13301           else
13302             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
13303               << EnumVal.toString(10);
13304         } else {
13305           EltTy = T;
13306         }
13307 
13308         // Retrieve the last enumerator's value, extent that type to the
13309         // type that is supposed to be large enough to represent the incremented
13310         // value, then increment.
13311         EnumVal = LastEnumConst->getInitVal();
13312         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13313         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
13314         ++EnumVal;
13315 
13316         // If we're not in C++, diagnose the overflow of enumerator values,
13317         // which in C99 means that the enumerator value is not representable in
13318         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
13319         // permits enumerator values that are representable in some larger
13320         // integral type.
13321         if (!getLangOpts().CPlusPlus && !T.isNull())
13322           Diag(IdLoc, diag::warn_enum_value_overflow);
13323       } else if (!getLangOpts().CPlusPlus &&
13324                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13325         // Enforce C99 6.7.2.2p2 even when we compute the next value.
13326         Diag(IdLoc, diag::ext_enum_value_not_int)
13327           << EnumVal.toString(10) << 1;
13328       }
13329     }
13330   }
13331 
13332   if (!EltTy->isDependentType()) {
13333     // Make the enumerator value match the signedness and size of the
13334     // enumerator's type.
13335     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
13336     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13337   }
13338 
13339   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
13340                                   Val, EnumVal);
13341 }
13342 
13343 
13344 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
13345                               SourceLocation IdLoc, IdentifierInfo *Id,
13346                               AttributeList *Attr,
13347                               SourceLocation EqualLoc, Expr *Val) {
13348   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
13349   EnumConstantDecl *LastEnumConst =
13350     cast_or_null<EnumConstantDecl>(lastEnumConst);
13351 
13352   // The scope passed in may not be a decl scope.  Zip up the scope tree until
13353   // we find one that is.
13354   S = getNonFieldDeclScope(S);
13355 
13356   // Verify that there isn't already something declared with this name in this
13357   // scope.
13358   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
13359                                          ForRedeclaration);
13360   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13361     // Maybe we will complain about the shadowed template parameter.
13362     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
13363     // Just pretend that we didn't see the previous declaration.
13364     PrevDecl = nullptr;
13365   }
13366 
13367   if (PrevDecl) {
13368     // When in C++, we may get a TagDecl with the same name; in this case the
13369     // enum constant will 'hide' the tag.
13370     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
13371            "Received TagDecl when not in C++!");
13372     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
13373       if (isa<EnumConstantDecl>(PrevDecl))
13374         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
13375       else
13376         Diag(IdLoc, diag::err_redefinition) << Id;
13377       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13378       return nullptr;
13379     }
13380   }
13381 
13382   // C++ [class.mem]p15:
13383   // If T is the name of a class, then each of the following shall have a name
13384   // different from T:
13385   // - every enumerator of every member of class T that is an unscoped
13386   // enumerated type
13387   if (CXXRecordDecl *Record
13388                       = dyn_cast<CXXRecordDecl>(
13389                              TheEnumDecl->getDeclContext()->getRedeclContext()))
13390     if (!TheEnumDecl->isScoped() &&
13391         Record->getIdentifier() && Record->getIdentifier() == Id)
13392       Diag(IdLoc, diag::err_member_name_of_class) << Id;
13393 
13394   EnumConstantDecl *New =
13395     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
13396 
13397   if (New) {
13398     // Process attributes.
13399     if (Attr) ProcessDeclAttributeList(S, New, Attr);
13400 
13401     // Register this decl in the current scope stack.
13402     New->setAccess(TheEnumDecl->getAccess());
13403     PushOnScopeChains(New, S);
13404   }
13405 
13406   ActOnDocumentableDecl(New);
13407 
13408   return New;
13409 }
13410 
13411 // Returns true when the enum initial expression does not trigger the
13412 // duplicate enum warning.  A few common cases are exempted as follows:
13413 // Element2 = Element1
13414 // Element2 = Element1 + 1
13415 // Element2 = Element1 - 1
13416 // Where Element2 and Element1 are from the same enum.
13417 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
13418   Expr *InitExpr = ECD->getInitExpr();
13419   if (!InitExpr)
13420     return true;
13421   InitExpr = InitExpr->IgnoreImpCasts();
13422 
13423   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
13424     if (!BO->isAdditiveOp())
13425       return true;
13426     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
13427     if (!IL)
13428       return true;
13429     if (IL->getValue() != 1)
13430       return true;
13431 
13432     InitExpr = BO->getLHS();
13433   }
13434 
13435   // This checks if the elements are from the same enum.
13436   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
13437   if (!DRE)
13438     return true;
13439 
13440   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
13441   if (!EnumConstant)
13442     return true;
13443 
13444   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
13445       Enum)
13446     return true;
13447 
13448   return false;
13449 }
13450 
13451 struct DupKey {
13452   int64_t val;
13453   bool isTombstoneOrEmptyKey;
13454   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
13455     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
13456 };
13457 
13458 static DupKey GetDupKey(const llvm::APSInt& Val) {
13459   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
13460                 false);
13461 }
13462 
13463 struct DenseMapInfoDupKey {
13464   static DupKey getEmptyKey() { return DupKey(0, true); }
13465   static DupKey getTombstoneKey() { return DupKey(1, true); }
13466   static unsigned getHashValue(const DupKey Key) {
13467     return (unsigned)(Key.val * 37);
13468   }
13469   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
13470     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
13471            LHS.val == RHS.val;
13472   }
13473 };
13474 
13475 // Emits a warning when an element is implicitly set a value that
13476 // a previous element has already been set to.
13477 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
13478                                         EnumDecl *Enum,
13479                                         QualType EnumType) {
13480   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
13481     return;
13482   // Avoid anonymous enums
13483   if (!Enum->getIdentifier())
13484     return;
13485 
13486   // Only check for small enums.
13487   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
13488     return;
13489 
13490   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
13491   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
13492 
13493   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
13494   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
13495           ValueToVectorMap;
13496 
13497   DuplicatesVector DupVector;
13498   ValueToVectorMap EnumMap;
13499 
13500   // Populate the EnumMap with all values represented by enum constants without
13501   // an initialier.
13502   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13503     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
13504 
13505     // Null EnumConstantDecl means a previous diagnostic has been emitted for
13506     // this constant.  Skip this enum since it may be ill-formed.
13507     if (!ECD) {
13508       return;
13509     }
13510 
13511     if (ECD->getInitExpr())
13512       continue;
13513 
13514     DupKey Key = GetDupKey(ECD->getInitVal());
13515     DeclOrVector &Entry = EnumMap[Key];
13516 
13517     // First time encountering this value.
13518     if (Entry.isNull())
13519       Entry = ECD;
13520   }
13521 
13522   // Create vectors for any values that has duplicates.
13523   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13524     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
13525     if (!ValidDuplicateEnum(ECD, Enum))
13526       continue;
13527 
13528     DupKey Key = GetDupKey(ECD->getInitVal());
13529 
13530     DeclOrVector& Entry = EnumMap[Key];
13531     if (Entry.isNull())
13532       continue;
13533 
13534     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
13535       // Ensure constants are different.
13536       if (D == ECD)
13537         continue;
13538 
13539       // Create new vector and push values onto it.
13540       ECDVector *Vec = new ECDVector();
13541       Vec->push_back(D);
13542       Vec->push_back(ECD);
13543 
13544       // Update entry to point to the duplicates vector.
13545       Entry = Vec;
13546 
13547       // Store the vector somewhere we can consult later for quick emission of
13548       // diagnostics.
13549       DupVector.push_back(Vec);
13550       continue;
13551     }
13552 
13553     ECDVector *Vec = Entry.get<ECDVector*>();
13554     // Make sure constants are not added more than once.
13555     if (*Vec->begin() == ECD)
13556       continue;
13557 
13558     Vec->push_back(ECD);
13559   }
13560 
13561   // Emit diagnostics.
13562   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
13563                                   DupVectorEnd = DupVector.end();
13564        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
13565     ECDVector *Vec = *DupVectorIter;
13566     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
13567 
13568     // Emit warning for one enum constant.
13569     ECDVector::iterator I = Vec->begin();
13570     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
13571       << (*I)->getName() << (*I)->getInitVal().toString(10)
13572       << (*I)->getSourceRange();
13573     ++I;
13574 
13575     // Emit one note for each of the remaining enum constants with
13576     // the same value.
13577     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
13578       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
13579         << (*I)->getName() << (*I)->getInitVal().toString(10)
13580         << (*I)->getSourceRange();
13581     delete Vec;
13582   }
13583 }
13584 
13585 bool
13586 Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
13587                         bool AllowMask) const {
13588   FlagEnumAttr *FEAttr = ED->getAttr<FlagEnumAttr>();
13589   assert(FEAttr && "looking for value in non-flag enum");
13590 
13591   llvm::APInt FlagMask = ~FEAttr->getFlagBits();
13592   unsigned Width = FlagMask.getBitWidth();
13593 
13594   // We will try a zero-extended value for the regular check first.
13595   llvm::APInt ExtVal = Val.zextOrSelf(Width);
13596 
13597   // A value is in a flag enum if either its bits are a subset of the enum's
13598   // flag bits (the first condition) or we are allowing masks and the same is
13599   // true of its complement (the second condition). When masks are allowed, we
13600   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
13601   //
13602   // While it's true that any value could be used as a mask, the assumption is
13603   // that a mask will have all of the insignificant bits set. Anything else is
13604   // likely a logic error.
13605   if (!(FlagMask & ExtVal))
13606     return true;
13607 
13608   if (AllowMask) {
13609     // Try a one-extended value instead. This can happen if the enum is wider
13610     // than the constant used, in C with extensions to allow for wider enums.
13611     // The mask will still have the correct behaviour, so we give the user the
13612     // benefit of the doubt.
13613     //
13614     // FIXME: This heuristic can cause weird results if the enum was extended
13615     // to a larger type and is signed, because then bit-masks of smaller types
13616     // that get extended will fall out of range (e.g. ~0x1u). We currently don't
13617     // detect that case and will get a false positive for it. In most cases,
13618     // though, it can be fixed by making it a signed type (e.g. ~0x1), so it may
13619     // be fine just to accept this as a warning.
13620     ExtVal |= llvm::APInt::getHighBitsSet(Width, Width - Val.getBitWidth());
13621     if (!(FlagMask & ~ExtVal))
13622       return true;
13623   }
13624 
13625   return false;
13626 }
13627 
13628 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
13629                          SourceLocation RBraceLoc, Decl *EnumDeclX,
13630                          ArrayRef<Decl *> Elements,
13631                          Scope *S, AttributeList *Attr) {
13632   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
13633   QualType EnumType = Context.getTypeDeclType(Enum);
13634 
13635   if (Attr)
13636     ProcessDeclAttributeList(S, Enum, Attr);
13637 
13638   if (Enum->isDependentType()) {
13639     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13640       EnumConstantDecl *ECD =
13641         cast_or_null<EnumConstantDecl>(Elements[i]);
13642       if (!ECD) continue;
13643 
13644       ECD->setType(EnumType);
13645     }
13646 
13647     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
13648     return;
13649   }
13650 
13651   // TODO: If the result value doesn't fit in an int, it must be a long or long
13652   // long value.  ISO C does not support this, but GCC does as an extension,
13653   // emit a warning.
13654   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13655   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
13656   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
13657 
13658   // Verify that all the values are okay, compute the size of the values, and
13659   // reverse the list.
13660   unsigned NumNegativeBits = 0;
13661   unsigned NumPositiveBits = 0;
13662 
13663   // Keep track of whether all elements have type int.
13664   bool AllElementsInt = true;
13665 
13666   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13667     EnumConstantDecl *ECD =
13668       cast_or_null<EnumConstantDecl>(Elements[i]);
13669     if (!ECD) continue;  // Already issued a diagnostic.
13670 
13671     const llvm::APSInt &InitVal = ECD->getInitVal();
13672 
13673     // Keep track of the size of positive and negative values.
13674     if (InitVal.isUnsigned() || InitVal.isNonNegative())
13675       NumPositiveBits = std::max(NumPositiveBits,
13676                                  (unsigned)InitVal.getActiveBits());
13677     else
13678       NumNegativeBits = std::max(NumNegativeBits,
13679                                  (unsigned)InitVal.getMinSignedBits());
13680 
13681     // Keep track of whether every enum element has type int (very commmon).
13682     if (AllElementsInt)
13683       AllElementsInt = ECD->getType() == Context.IntTy;
13684   }
13685 
13686   // Figure out the type that should be used for this enum.
13687   QualType BestType;
13688   unsigned BestWidth;
13689 
13690   // C++0x N3000 [conv.prom]p3:
13691   //   An rvalue of an unscoped enumeration type whose underlying
13692   //   type is not fixed can be converted to an rvalue of the first
13693   //   of the following types that can represent all the values of
13694   //   the enumeration: int, unsigned int, long int, unsigned long
13695   //   int, long long int, or unsigned long long int.
13696   // C99 6.4.4.3p2:
13697   //   An identifier declared as an enumeration constant has type int.
13698   // The C99 rule is modified by a gcc extension
13699   QualType BestPromotionType;
13700 
13701   bool Packed = Enum->hasAttr<PackedAttr>();
13702   // -fshort-enums is the equivalent to specifying the packed attribute on all
13703   // enum definitions.
13704   if (LangOpts.ShortEnums)
13705     Packed = true;
13706 
13707   if (Enum->isFixed()) {
13708     BestType = Enum->getIntegerType();
13709     if (BestType->isPromotableIntegerType())
13710       BestPromotionType = Context.getPromotedIntegerType(BestType);
13711     else
13712       BestPromotionType = BestType;
13713 
13714     BestWidth = Context.getIntWidth(BestType);
13715   }
13716   else if (NumNegativeBits) {
13717     // If there is a negative value, figure out the smallest integer type (of
13718     // int/long/longlong) that fits.
13719     // If it's packed, check also if it fits a char or a short.
13720     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
13721       BestType = Context.SignedCharTy;
13722       BestWidth = CharWidth;
13723     } else if (Packed && NumNegativeBits <= ShortWidth &&
13724                NumPositiveBits < ShortWidth) {
13725       BestType = Context.ShortTy;
13726       BestWidth = ShortWidth;
13727     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
13728       BestType = Context.IntTy;
13729       BestWidth = IntWidth;
13730     } else {
13731       BestWidth = Context.getTargetInfo().getLongWidth();
13732 
13733       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
13734         BestType = Context.LongTy;
13735       } else {
13736         BestWidth = Context.getTargetInfo().getLongLongWidth();
13737 
13738         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
13739           Diag(Enum->getLocation(), diag::ext_enum_too_large);
13740         BestType = Context.LongLongTy;
13741       }
13742     }
13743     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
13744   } else {
13745     // If there is no negative value, figure out the smallest type that fits
13746     // all of the enumerator values.
13747     // If it's packed, check also if it fits a char or a short.
13748     if (Packed && NumPositiveBits <= CharWidth) {
13749       BestType = Context.UnsignedCharTy;
13750       BestPromotionType = Context.IntTy;
13751       BestWidth = CharWidth;
13752     } else if (Packed && NumPositiveBits <= ShortWidth) {
13753       BestType = Context.UnsignedShortTy;
13754       BestPromotionType = Context.IntTy;
13755       BestWidth = ShortWidth;
13756     } else if (NumPositiveBits <= IntWidth) {
13757       BestType = Context.UnsignedIntTy;
13758       BestWidth = IntWidth;
13759       BestPromotionType
13760         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13761                            ? Context.UnsignedIntTy : Context.IntTy;
13762     } else if (NumPositiveBits <=
13763                (BestWidth = Context.getTargetInfo().getLongWidth())) {
13764       BestType = Context.UnsignedLongTy;
13765       BestPromotionType
13766         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13767                            ? Context.UnsignedLongTy : Context.LongTy;
13768     } else {
13769       BestWidth = Context.getTargetInfo().getLongLongWidth();
13770       assert(NumPositiveBits <= BestWidth &&
13771              "How could an initializer get larger than ULL?");
13772       BestType = Context.UnsignedLongLongTy;
13773       BestPromotionType
13774         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13775                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
13776     }
13777   }
13778 
13779   FlagEnumAttr *FEAttr = Enum->getAttr<FlagEnumAttr>();
13780   if (FEAttr)
13781     FEAttr->getFlagBits() = llvm::APInt(BestWidth, 0);
13782 
13783   // Loop over all of the enumerator constants, changing their types to match
13784   // the type of the enum if needed. If we have a flag type, we also prepare the
13785   // FlagBits cache.
13786   for (auto *D : Elements) {
13787     auto *ECD = cast_or_null<EnumConstantDecl>(D);
13788     if (!ECD) continue;  // Already issued a diagnostic.
13789 
13790     // Standard C says the enumerators have int type, but we allow, as an
13791     // extension, the enumerators to be larger than int size.  If each
13792     // enumerator value fits in an int, type it as an int, otherwise type it the
13793     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
13794     // that X has type 'int', not 'unsigned'.
13795 
13796     // Determine whether the value fits into an int.
13797     llvm::APSInt InitVal = ECD->getInitVal();
13798 
13799     // If it fits into an integer type, force it.  Otherwise force it to match
13800     // the enum decl type.
13801     QualType NewTy;
13802     unsigned NewWidth;
13803     bool NewSign;
13804     if (!getLangOpts().CPlusPlus &&
13805         !Enum->isFixed() &&
13806         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
13807       NewTy = Context.IntTy;
13808       NewWidth = IntWidth;
13809       NewSign = true;
13810     } else if (ECD->getType() == BestType) {
13811       // Already the right type!
13812       if (getLangOpts().CPlusPlus)
13813         // C++ [dcl.enum]p4: Following the closing brace of an
13814         // enum-specifier, each enumerator has the type of its
13815         // enumeration.
13816         ECD->setType(EnumType);
13817       goto flagbits;
13818     } else {
13819       NewTy = BestType;
13820       NewWidth = BestWidth;
13821       NewSign = BestType->isSignedIntegerOrEnumerationType();
13822     }
13823 
13824     // Adjust the APSInt value.
13825     InitVal = InitVal.extOrTrunc(NewWidth);
13826     InitVal.setIsSigned(NewSign);
13827     ECD->setInitVal(InitVal);
13828 
13829     // Adjust the Expr initializer and type.
13830     if (ECD->getInitExpr() &&
13831         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
13832       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
13833                                                 CK_IntegralCast,
13834                                                 ECD->getInitExpr(),
13835                                                 /*base paths*/ nullptr,
13836                                                 VK_RValue));
13837     if (getLangOpts().CPlusPlus)
13838       // C++ [dcl.enum]p4: Following the closing brace of an
13839       // enum-specifier, each enumerator has the type of its
13840       // enumeration.
13841       ECD->setType(EnumType);
13842     else
13843       ECD->setType(NewTy);
13844 
13845 flagbits:
13846     // Check to see if we have a constant with exactly one bit set. Note that x
13847     // & (x - 1) will be nonzero if and only if x has more than one bit set.
13848     if (FEAttr) {
13849       llvm::APInt ExtVal = InitVal.zextOrSelf(BestWidth);
13850       if (ExtVal != 0 && !(ExtVal & (ExtVal - 1))) {
13851         FEAttr->getFlagBits() |= ExtVal;
13852       }
13853     }
13854   }
13855 
13856   if (FEAttr) {
13857     for (Decl *D : Elements) {
13858       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
13859       if (!ECD) continue;  // Already issued a diagnostic.
13860 
13861       llvm::APSInt InitVal = ECD->getInitVal();
13862       if (InitVal != 0 && !IsValueInFlagEnum(Enum, InitVal, true))
13863         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
13864           << ECD << Enum;
13865     }
13866   }
13867 
13868 
13869 
13870   Enum->completeDefinition(BestType, BestPromotionType,
13871                            NumPositiveBits, NumNegativeBits);
13872 
13873   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
13874 
13875   // Now that the enum type is defined, ensure it's not been underaligned.
13876   if (Enum->hasAttrs())
13877     CheckAlignasUnderalignment(Enum);
13878 }
13879 
13880 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
13881                                   SourceLocation StartLoc,
13882                                   SourceLocation EndLoc) {
13883   StringLiteral *AsmString = cast<StringLiteral>(expr);
13884 
13885   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
13886                                                    AsmString, StartLoc,
13887                                                    EndLoc);
13888   CurContext->addDecl(New);
13889   return New;
13890 }
13891 
13892 static void checkModuleImportContext(Sema &S, Module *M,
13893                                      SourceLocation ImportLoc,
13894                                      DeclContext *DC) {
13895   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
13896     switch (LSD->getLanguage()) {
13897     case LinkageSpecDecl::lang_c:
13898       if (!M->IsExternC) {
13899         S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
13900           << M->getFullModuleName();
13901         S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
13902         return;
13903       }
13904       break;
13905     case LinkageSpecDecl::lang_cxx:
13906       break;
13907     }
13908     DC = LSD->getParent();
13909   }
13910 
13911   while (isa<LinkageSpecDecl>(DC))
13912     DC = DC->getParent();
13913   if (!isa<TranslationUnitDecl>(DC)) {
13914     S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
13915       << M->getFullModuleName() << DC;
13916     S.Diag(cast<Decl>(DC)->getLocStart(),
13917            diag::note_module_import_not_at_top_level)
13918       << DC;
13919   }
13920 }
13921 
13922 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
13923                                    SourceLocation ImportLoc,
13924                                    ModuleIdPath Path) {
13925   Module *Mod =
13926       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
13927                                    /*IsIncludeDirective=*/false);
13928   if (!Mod)
13929     return true;
13930 
13931   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13932 
13933   // FIXME: we should support importing a submodule within a different submodule
13934   // of the same top-level module. Until we do, make it an error rather than
13935   // silently ignoring the import.
13936   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
13937     Diag(ImportLoc, diag::err_module_self_import)
13938         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
13939   else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
13940     Diag(ImportLoc, diag::err_module_import_in_implementation)
13941         << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
13942 
13943   SmallVector<SourceLocation, 2> IdentifierLocs;
13944   Module *ModCheck = Mod;
13945   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13946     // If we've run out of module parents, just drop the remaining identifiers.
13947     // We need the length to be consistent.
13948     if (!ModCheck)
13949       break;
13950     ModCheck = ModCheck->Parent;
13951 
13952     IdentifierLocs.push_back(Path[I].second);
13953   }
13954 
13955   ImportDecl *Import = ImportDecl::Create(Context,
13956                                           Context.getTranslationUnitDecl(),
13957                                           AtLoc.isValid()? AtLoc : ImportLoc,
13958                                           Mod, IdentifierLocs);
13959   Context.getTranslationUnitDecl()->addDecl(Import);
13960   return Import;
13961 }
13962 
13963 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
13964   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13965 
13966   // FIXME: Should we synthesize an ImportDecl here?
13967   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13968                                       /*Complain=*/true);
13969 }
13970 
13971 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
13972                                                       Module *Mod) {
13973   // Bail if we're not allowed to implicitly import a module here.
13974   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
13975     return;
13976 
13977   // Create the implicit import declaration.
13978   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13979   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13980                                                    Loc, Mod, Loc);
13981   TU->addDecl(ImportD);
13982   Consumer.HandleImplicitImportDecl(ImportD);
13983 
13984   // Make the module visible.
13985   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13986                                       /*Complain=*/false);
13987 }
13988 
13989 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13990                                       IdentifierInfo* AliasName,
13991                                       SourceLocation PragmaLoc,
13992                                       SourceLocation NameLoc,
13993                                       SourceLocation AliasNameLoc) {
13994   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13995                                     LookupOrdinaryName);
13996   AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13997                                                     AliasName->getName(), 0);
13998 
13999   if (PrevDecl)
14000     PrevDecl->addAttr(Attr);
14001   else
14002     (void)ExtnameUndeclaredIdentifiers.insert(
14003       std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
14004 }
14005 
14006 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
14007                              SourceLocation PragmaLoc,
14008                              SourceLocation NameLoc) {
14009   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
14010 
14011   if (PrevDecl) {
14012     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
14013   } else {
14014     (void)WeakUndeclaredIdentifiers.insert(
14015       std::pair<IdentifierInfo*,WeakInfo>
14016         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
14017   }
14018 }
14019 
14020 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
14021                                 IdentifierInfo* AliasName,
14022                                 SourceLocation PragmaLoc,
14023                                 SourceLocation NameLoc,
14024                                 SourceLocation AliasNameLoc) {
14025   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
14026                                     LookupOrdinaryName);
14027   WeakInfo W = WeakInfo(Name, NameLoc);
14028 
14029   if (PrevDecl) {
14030     if (!PrevDecl->hasAttr<AliasAttr>())
14031       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
14032         DeclApplyPragmaWeak(TUScope, ND, W);
14033   } else {
14034     (void)WeakUndeclaredIdentifiers.insert(
14035       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
14036   }
14037 }
14038 
14039 Decl *Sema::getObjCDeclContext() const {
14040   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
14041 }
14042 
14043 AvailabilityResult Sema::getCurContextAvailability() const {
14044   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
14045   if (!D)
14046     return AR_Available;
14047 
14048   // If we are within an Objective-C method, we should consult
14049   // both the availability of the method as well as the
14050   // enclosing class.  If the class is (say) deprecated,
14051   // the entire method is considered deprecated from the
14052   // purpose of checking if the current context is deprecated.
14053   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
14054     AvailabilityResult R = MD->getAvailability();
14055     if (R != AR_Available)
14056       return R;
14057     D = MD->getClassInterface();
14058   }
14059   // If we are within an Objective-c @implementation, it
14060   // gets the same availability context as the @interface.
14061   else if (const ObjCImplementationDecl *ID =
14062             dyn_cast<ObjCImplementationDecl>(D)) {
14063     D = ID->getClassInterface();
14064   }
14065   // Recover from user error.
14066   return D ? D->getAvailability() : AR_Available;
14067 }
14068