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   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
4868 }
4869 
4870 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
4871   // FIXME: We can have multiple results via __attribute__((overloadable)).
4872   auto Result = Context.getExternCContextDecl()->lookup(Name);
4873   return Result.empty() ? nullptr : *Result.begin();
4874 }
4875 
4876 /// \brief Diagnose function specifiers on a declaration of an identifier that
4877 /// does not identify a function.
4878 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
4879   // FIXME: We should probably indicate the identifier in question to avoid
4880   // confusion for constructs like "inline int a(), b;"
4881   if (DS.isInlineSpecified())
4882     Diag(DS.getInlineSpecLoc(),
4883          diag::err_inline_non_function);
4884 
4885   if (DS.isVirtualSpecified())
4886     Diag(DS.getVirtualSpecLoc(),
4887          diag::err_virtual_non_function);
4888 
4889   if (DS.isExplicitSpecified())
4890     Diag(DS.getExplicitSpecLoc(),
4891          diag::err_explicit_non_function);
4892 
4893   if (DS.isNoreturnSpecified())
4894     Diag(DS.getNoreturnSpecLoc(),
4895          diag::err_noreturn_non_function);
4896 }
4897 
4898 NamedDecl*
4899 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4900                              TypeSourceInfo *TInfo, LookupResult &Previous) {
4901   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4902   if (D.getCXXScopeSpec().isSet()) {
4903     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4904       << D.getCXXScopeSpec().getRange();
4905     D.setInvalidType();
4906     // Pretend we didn't see the scope specifier.
4907     DC = CurContext;
4908     Previous.clear();
4909   }
4910 
4911   DiagnoseFunctionSpecifiers(D.getDeclSpec());
4912 
4913   if (D.getDeclSpec().isConstexprSpecified())
4914     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4915       << 1;
4916 
4917   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4918     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4919       << D.getName().getSourceRange();
4920     return nullptr;
4921   }
4922 
4923   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4924   if (!NewTD) return nullptr;
4925 
4926   // Handle attributes prior to checking for duplicates in MergeVarDecl
4927   ProcessDeclAttributes(S, NewTD, D);
4928 
4929   CheckTypedefForVariablyModifiedType(S, NewTD);
4930 
4931   bool Redeclaration = D.isRedeclaration();
4932   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4933   D.setRedeclaration(Redeclaration);
4934   return ND;
4935 }
4936 
4937 void
4938 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4939   // C99 6.7.7p2: If a typedef name specifies a variably modified type
4940   // then it shall have block scope.
4941   // Note that variably modified types must be fixed before merging the decl so
4942   // that redeclarations will match.
4943   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4944   QualType T = TInfo->getType();
4945   if (T->isVariablyModifiedType()) {
4946     getCurFunction()->setHasBranchProtectedScope();
4947 
4948     if (S->getFnParent() == nullptr) {
4949       bool SizeIsNegative;
4950       llvm::APSInt Oversized;
4951       TypeSourceInfo *FixedTInfo =
4952         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4953                                                       SizeIsNegative,
4954                                                       Oversized);
4955       if (FixedTInfo) {
4956         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4957         NewTD->setTypeSourceInfo(FixedTInfo);
4958       } else {
4959         if (SizeIsNegative)
4960           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4961         else if (T->isVariableArrayType())
4962           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4963         else if (Oversized.getBoolValue())
4964           Diag(NewTD->getLocation(), diag::err_array_too_large)
4965             << Oversized.toString(10);
4966         else
4967           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4968         NewTD->setInvalidDecl();
4969       }
4970     }
4971   }
4972 }
4973 
4974 
4975 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4976 /// declares a typedef-name, either using the 'typedef' type specifier or via
4977 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4978 NamedDecl*
4979 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4980                            LookupResult &Previous, bool &Redeclaration) {
4981   // Merge the decl with the existing one if appropriate. If the decl is
4982   // in an outer scope, it isn't the same thing.
4983   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4984                        /*AllowInlineNamespace*/false);
4985   filterNonConflictingPreviousTypedefDecls(Context, NewTD, Previous);
4986   if (!Previous.empty()) {
4987     Redeclaration = true;
4988     MergeTypedefNameDecl(NewTD, Previous);
4989   }
4990 
4991   // If this is the C FILE type, notify the AST context.
4992   if (IdentifierInfo *II = NewTD->getIdentifier())
4993     if (!NewTD->isInvalidDecl() &&
4994         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4995       if (II->isStr("FILE"))
4996         Context.setFILEDecl(NewTD);
4997       else if (II->isStr("jmp_buf"))
4998         Context.setjmp_bufDecl(NewTD);
4999       else if (II->isStr("sigjmp_buf"))
5000         Context.setsigjmp_bufDecl(NewTD);
5001       else if (II->isStr("ucontext_t"))
5002         Context.setucontext_tDecl(NewTD);
5003     }
5004 
5005   return NewTD;
5006 }
5007 
5008 /// \brief Determines whether the given declaration is an out-of-scope
5009 /// previous declaration.
5010 ///
5011 /// This routine should be invoked when name lookup has found a
5012 /// previous declaration (PrevDecl) that is not in the scope where a
5013 /// new declaration by the same name is being introduced. If the new
5014 /// declaration occurs in a local scope, previous declarations with
5015 /// linkage may still be considered previous declarations (C99
5016 /// 6.2.2p4-5, C++ [basic.link]p6).
5017 ///
5018 /// \param PrevDecl the previous declaration found by name
5019 /// lookup
5020 ///
5021 /// \param DC the context in which the new declaration is being
5022 /// declared.
5023 ///
5024 /// \returns true if PrevDecl is an out-of-scope previous declaration
5025 /// for a new delcaration with the same name.
5026 static bool
5027 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5028                                 ASTContext &Context) {
5029   if (!PrevDecl)
5030     return false;
5031 
5032   if (!PrevDecl->hasLinkage())
5033     return false;
5034 
5035   if (Context.getLangOpts().CPlusPlus) {
5036     // C++ [basic.link]p6:
5037     //   If there is a visible declaration of an entity with linkage
5038     //   having the same name and type, ignoring entities declared
5039     //   outside the innermost enclosing namespace scope, the block
5040     //   scope declaration declares that same entity and receives the
5041     //   linkage of the previous declaration.
5042     DeclContext *OuterContext = DC->getRedeclContext();
5043     if (!OuterContext->isFunctionOrMethod())
5044       // This rule only applies to block-scope declarations.
5045       return false;
5046 
5047     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5048     if (PrevOuterContext->isRecord())
5049       // We found a member function: ignore it.
5050       return false;
5051 
5052     // Find the innermost enclosing namespace for the new and
5053     // previous declarations.
5054     OuterContext = OuterContext->getEnclosingNamespaceContext();
5055     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5056 
5057     // The previous declaration is in a different namespace, so it
5058     // isn't the same function.
5059     if (!OuterContext->Equals(PrevOuterContext))
5060       return false;
5061   }
5062 
5063   return true;
5064 }
5065 
5066 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5067   CXXScopeSpec &SS = D.getCXXScopeSpec();
5068   if (!SS.isSet()) return;
5069   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5070 }
5071 
5072 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5073   QualType type = decl->getType();
5074   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5075   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5076     // Various kinds of declaration aren't allowed to be __autoreleasing.
5077     unsigned kind = -1U;
5078     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5079       if (var->hasAttr<BlocksAttr>())
5080         kind = 0; // __block
5081       else if (!var->hasLocalStorage())
5082         kind = 1; // global
5083     } else if (isa<ObjCIvarDecl>(decl)) {
5084       kind = 3; // ivar
5085     } else if (isa<FieldDecl>(decl)) {
5086       kind = 2; // field
5087     }
5088 
5089     if (kind != -1U) {
5090       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5091         << kind;
5092     }
5093   } else if (lifetime == Qualifiers::OCL_None) {
5094     // Try to infer lifetime.
5095     if (!type->isObjCLifetimeType())
5096       return false;
5097 
5098     lifetime = type->getObjCARCImplicitLifetime();
5099     type = Context.getLifetimeQualifiedType(type, lifetime);
5100     decl->setType(type);
5101   }
5102 
5103   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5104     // Thread-local variables cannot have lifetime.
5105     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5106         var->getTLSKind()) {
5107       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5108         << var->getType();
5109       return true;
5110     }
5111   }
5112 
5113   return false;
5114 }
5115 
5116 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5117   // Ensure that an auto decl is deduced otherwise the checks below might cache
5118   // the wrong linkage.
5119   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5120 
5121   // 'weak' only applies to declarations with external linkage.
5122   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5123     if (!ND.isExternallyVisible()) {
5124       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5125       ND.dropAttr<WeakAttr>();
5126     }
5127   }
5128   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5129     if (ND.isExternallyVisible()) {
5130       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5131       ND.dropAttr<WeakRefAttr>();
5132       ND.dropAttr<AliasAttr>();
5133     }
5134   }
5135 
5136   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5137     if (VD->hasInit()) {
5138       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5139         assert(VD->isThisDeclarationADefinition() &&
5140                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5141         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
5142         VD->dropAttr<AliasAttr>();
5143       }
5144     }
5145   }
5146 
5147   // 'selectany' only applies to externally visible varable declarations.
5148   // It does not apply to functions.
5149   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5150     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5151       S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
5152       ND.dropAttr<SelectAnyAttr>();
5153     }
5154   }
5155 
5156   // dll attributes require external linkage.
5157   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5158     if (!ND.isExternallyVisible()) {
5159       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5160         << &ND << Attr;
5161       ND.setInvalidDecl();
5162     }
5163   }
5164 }
5165 
5166 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5167                                            NamedDecl *NewDecl,
5168                                            bool IsSpecialization) {
5169   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5170     OldDecl = OldTD->getTemplatedDecl();
5171   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5172     NewDecl = NewTD->getTemplatedDecl();
5173 
5174   if (!OldDecl || !NewDecl)
5175     return;
5176 
5177   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5178   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5179   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5180   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5181 
5182   // dllimport and dllexport are inheritable attributes so we have to exclude
5183   // inherited attribute instances.
5184   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5185                     (NewExportAttr && !NewExportAttr->isInherited());
5186 
5187   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5188   // the only exception being explicit specializations.
5189   // Implicitly generated declarations are also excluded for now because there
5190   // is no other way to switch these to use dllimport or dllexport.
5191   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5192 
5193   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5194     // If the declaration hasn't been used yet, allow with a warning for
5195     // free functions and global variables.
5196     bool JustWarn = false;
5197     if (!OldDecl->isUsed() && !OldDecl->isCXXClassMember()) {
5198       auto *VD = dyn_cast<VarDecl>(OldDecl);
5199       if (VD && !VD->getDescribedVarTemplate())
5200         JustWarn = true;
5201       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5202       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5203         JustWarn = true;
5204     }
5205 
5206     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5207                                : diag::err_attribute_dll_redeclaration;
5208     S.Diag(NewDecl->getLocation(), DiagID)
5209         << NewDecl
5210         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5211     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5212     if (!JustWarn) {
5213       NewDecl->setInvalidDecl();
5214       return;
5215     }
5216   }
5217 
5218   // A redeclaration is not allowed to drop a dllimport attribute, the only
5219   // exceptions being inline function definitions, local extern declarations,
5220   // and qualified friend declarations.
5221   // NB: MSVC converts such a declaration to dllexport.
5222   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5223   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5224     // Ignore static data because out-of-line definitions are diagnosed
5225     // separately.
5226     IsStaticDataMember = VD->isStaticDataMember();
5227   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5228     IsInline = FD->isInlined();
5229     IsQualifiedFriend = FD->getQualifier() &&
5230                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5231   }
5232 
5233   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5234       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5235     S.Diag(NewDecl->getLocation(),
5236            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5237       << NewDecl << OldImportAttr;
5238     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5239     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5240     OldDecl->dropAttr<DLLImportAttr>();
5241     NewDecl->dropAttr<DLLImportAttr>();
5242   } else if (IsInline && OldImportAttr &&
5243              !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5244     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5245     OldDecl->dropAttr<DLLImportAttr>();
5246     NewDecl->dropAttr<DLLImportAttr>();
5247     S.Diag(NewDecl->getLocation(),
5248            diag::warn_dllimport_dropped_from_inline_function)
5249         << NewDecl << OldImportAttr;
5250   }
5251 }
5252 
5253 /// Given that we are within the definition of the given function,
5254 /// will that definition behave like C99's 'inline', where the
5255 /// definition is discarded except for optimization purposes?
5256 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5257   // Try to avoid calling GetGVALinkageForFunction.
5258 
5259   // All cases of this require the 'inline' keyword.
5260   if (!FD->isInlined()) return false;
5261 
5262   // This is only possible in C++ with the gnu_inline attribute.
5263   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5264     return false;
5265 
5266   // Okay, go ahead and call the relatively-more-expensive function.
5267 
5268 #ifndef NDEBUG
5269   // AST quite reasonably asserts that it's working on a function
5270   // definition.  We don't really have a way to tell it that we're
5271   // currently defining the function, so just lie to it in +Asserts
5272   // builds.  This is an awful hack.
5273   FD->setLazyBody(1);
5274 #endif
5275 
5276   bool isC99Inline =
5277       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5278 
5279 #ifndef NDEBUG
5280   FD->setLazyBody(0);
5281 #endif
5282 
5283   return isC99Inline;
5284 }
5285 
5286 /// Determine whether a variable is extern "C" prior to attaching
5287 /// an initializer. We can't just call isExternC() here, because that
5288 /// will also compute and cache whether the declaration is externally
5289 /// visible, which might change when we attach the initializer.
5290 ///
5291 /// This can only be used if the declaration is known to not be a
5292 /// redeclaration of an internal linkage declaration.
5293 ///
5294 /// For instance:
5295 ///
5296 ///   auto x = []{};
5297 ///
5298 /// Attaching the initializer here makes this declaration not externally
5299 /// visible, because its type has internal linkage.
5300 ///
5301 /// FIXME: This is a hack.
5302 template<typename T>
5303 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5304   if (S.getLangOpts().CPlusPlus) {
5305     // In C++, the overloadable attribute negates the effects of extern "C".
5306     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5307       return false;
5308   }
5309   return D->isExternC();
5310 }
5311 
5312 static bool shouldConsiderLinkage(const VarDecl *VD) {
5313   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5314   if (DC->isFunctionOrMethod())
5315     return VD->hasExternalStorage();
5316   if (DC->isFileContext())
5317     return true;
5318   if (DC->isRecord())
5319     return false;
5320   llvm_unreachable("Unexpected context");
5321 }
5322 
5323 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5324   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5325   if (DC->isFileContext() || DC->isFunctionOrMethod())
5326     return true;
5327   if (DC->isRecord())
5328     return false;
5329   llvm_unreachable("Unexpected context");
5330 }
5331 
5332 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5333                           AttributeList::Kind Kind) {
5334   for (const AttributeList *L = AttrList; L; L = L->getNext())
5335     if (L->getKind() == Kind)
5336       return true;
5337   return false;
5338 }
5339 
5340 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5341                           AttributeList::Kind Kind) {
5342   // Check decl attributes on the DeclSpec.
5343   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5344     return true;
5345 
5346   // Walk the declarator structure, checking decl attributes that were in a type
5347   // position to the decl itself.
5348   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5349     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5350       return true;
5351   }
5352 
5353   // Finally, check attributes on the decl itself.
5354   return hasParsedAttr(S, PD.getAttributes(), Kind);
5355 }
5356 
5357 /// Adjust the \c DeclContext for a function or variable that might be a
5358 /// function-local external declaration.
5359 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5360   if (!DC->isFunctionOrMethod())
5361     return false;
5362 
5363   // If this is a local extern function or variable declared within a function
5364   // template, don't add it into the enclosing namespace scope until it is
5365   // instantiated; it might have a dependent type right now.
5366   if (DC->isDependentContext())
5367     return true;
5368 
5369   // C++11 [basic.link]p7:
5370   //   When a block scope declaration of an entity with linkage is not found to
5371   //   refer to some other declaration, then that entity is a member of the
5372   //   innermost enclosing namespace.
5373   //
5374   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5375   // semantically-enclosing namespace, not a lexically-enclosing one.
5376   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5377     DC = DC->getParent();
5378   return true;
5379 }
5380 
5381 NamedDecl *
5382 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5383                               TypeSourceInfo *TInfo, LookupResult &Previous,
5384                               MultiTemplateParamsArg TemplateParamLists,
5385                               bool &AddToScope) {
5386   QualType R = TInfo->getType();
5387   DeclarationName Name = GetNameForDeclarator(D).getName();
5388 
5389   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5390   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5391 
5392   // dllimport globals without explicit storage class are treated as extern. We
5393   // have to change the storage class this early to get the right DeclContext.
5394   if (SC == SC_None && !DC->isRecord() &&
5395       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5396       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5397     SC = SC_Extern;
5398 
5399   DeclContext *OriginalDC = DC;
5400   bool IsLocalExternDecl = SC == SC_Extern &&
5401                            adjustContextForLocalExternDecl(DC);
5402 
5403   if (getLangOpts().OpenCL) {
5404     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5405     QualType NR = R;
5406     while (NR->isPointerType()) {
5407       if (NR->isFunctionPointerType()) {
5408         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5409         D.setInvalidType();
5410         break;
5411       }
5412       NR = NR->getPointeeType();
5413     }
5414 
5415     if (!getOpenCLOptions().cl_khr_fp16) {
5416       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5417       // half array type (unless the cl_khr_fp16 extension is enabled).
5418       if (Context.getBaseElementType(R)->isHalfType()) {
5419         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5420         D.setInvalidType();
5421       }
5422     }
5423   }
5424 
5425   if (SCSpec == DeclSpec::SCS_mutable) {
5426     // mutable can only appear on non-static class members, so it's always
5427     // an error here
5428     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5429     D.setInvalidType();
5430     SC = SC_None;
5431   }
5432 
5433   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5434       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5435                               D.getDeclSpec().getStorageClassSpecLoc())) {
5436     // In C++11, the 'register' storage class specifier is deprecated.
5437     // Suppress the warning in system macros, it's used in macros in some
5438     // popular C system headers, such as in glibc's htonl() macro.
5439     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5440          diag::warn_deprecated_register)
5441       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5442   }
5443 
5444   IdentifierInfo *II = Name.getAsIdentifierInfo();
5445   if (!II) {
5446     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5447       << Name;
5448     return nullptr;
5449   }
5450 
5451   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5452 
5453   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5454     // C99 6.9p2: The storage-class specifiers auto and register shall not
5455     // appear in the declaration specifiers in an external declaration.
5456     // Global Register+Asm is a GNU extension we support.
5457     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5458       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5459       D.setInvalidType();
5460     }
5461   }
5462 
5463   if (getLangOpts().OpenCL) {
5464     // Set up the special work-group-local storage class for variables in the
5465     // OpenCL __local address space.
5466     if (R.getAddressSpace() == LangAS::opencl_local) {
5467       SC = SC_OpenCLWorkGroupLocal;
5468     }
5469 
5470     // OpenCL v1.2 s6.9.b p4:
5471     // The sampler type cannot be used with the __local and __global address
5472     // space qualifiers.
5473     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5474       R.getAddressSpace() == LangAS::opencl_global)) {
5475       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5476     }
5477 
5478     // OpenCL 1.2 spec, p6.9 r:
5479     // The event type cannot be used to declare a program scope variable.
5480     // The event type cannot be used with the __local, __constant and __global
5481     // address space qualifiers.
5482     if (R->isEventT()) {
5483       if (S->getParent() == nullptr) {
5484         Diag(D.getLocStart(), diag::err_event_t_global_var);
5485         D.setInvalidType();
5486       }
5487 
5488       if (R.getAddressSpace()) {
5489         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5490         D.setInvalidType();
5491       }
5492     }
5493   }
5494 
5495   bool IsExplicitSpecialization = false;
5496   bool IsVariableTemplateSpecialization = false;
5497   bool IsPartialSpecialization = false;
5498   bool IsVariableTemplate = false;
5499   VarDecl *NewVD = nullptr;
5500   VarTemplateDecl *NewTemplate = nullptr;
5501   TemplateParameterList *TemplateParams = nullptr;
5502   if (!getLangOpts().CPlusPlus) {
5503     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5504                             D.getIdentifierLoc(), II,
5505                             R, TInfo, SC);
5506 
5507     if (D.isInvalidType())
5508       NewVD->setInvalidDecl();
5509   } else {
5510     bool Invalid = false;
5511 
5512     if (DC->isRecord() && !CurContext->isRecord()) {
5513       // This is an out-of-line definition of a static data member.
5514       switch (SC) {
5515       case SC_None:
5516         break;
5517       case SC_Static:
5518         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5519              diag::err_static_out_of_line)
5520           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5521         break;
5522       case SC_Auto:
5523       case SC_Register:
5524       case SC_Extern:
5525         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5526         // to names of variables declared in a block or to function parameters.
5527         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5528         // of class members
5529 
5530         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5531              diag::err_storage_class_for_static_member)
5532           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5533         break;
5534       case SC_PrivateExtern:
5535         llvm_unreachable("C storage class in c++!");
5536       case SC_OpenCLWorkGroupLocal:
5537         llvm_unreachable("OpenCL storage class in c++!");
5538       }
5539     }
5540 
5541     if (SC == SC_Static && CurContext->isRecord()) {
5542       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5543         if (RD->isLocalClass())
5544           Diag(D.getIdentifierLoc(),
5545                diag::err_static_data_member_not_allowed_in_local_class)
5546             << Name << RD->getDeclName();
5547 
5548         // C++98 [class.union]p1: If a union contains a static data member,
5549         // the program is ill-formed. C++11 drops this restriction.
5550         if (RD->isUnion())
5551           Diag(D.getIdentifierLoc(),
5552                getLangOpts().CPlusPlus11
5553                  ? diag::warn_cxx98_compat_static_data_member_in_union
5554                  : diag::ext_static_data_member_in_union) << Name;
5555         // We conservatively disallow static data members in anonymous structs.
5556         else if (!RD->getDeclName())
5557           Diag(D.getIdentifierLoc(),
5558                diag::err_static_data_member_not_allowed_in_anon_struct)
5559             << Name << RD->isUnion();
5560       }
5561     }
5562 
5563     // Match up the template parameter lists with the scope specifier, then
5564     // determine whether we have a template or a template specialization.
5565     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5566         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5567         D.getCXXScopeSpec(),
5568         D.getName().getKind() == UnqualifiedId::IK_TemplateId
5569             ? D.getName().TemplateId
5570             : nullptr,
5571         TemplateParamLists,
5572         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5573 
5574     if (TemplateParams) {
5575       if (!TemplateParams->size() &&
5576           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5577         // There is an extraneous 'template<>' for this variable. Complain
5578         // about it, but allow the declaration of the variable.
5579         Diag(TemplateParams->getTemplateLoc(),
5580              diag::err_template_variable_noparams)
5581           << II
5582           << SourceRange(TemplateParams->getTemplateLoc(),
5583                          TemplateParams->getRAngleLoc());
5584         TemplateParams = nullptr;
5585       } else {
5586         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5587           // This is an explicit specialization or a partial specialization.
5588           // FIXME: Check that we can declare a specialization here.
5589           IsVariableTemplateSpecialization = true;
5590           IsPartialSpecialization = TemplateParams->size() > 0;
5591         } else { // if (TemplateParams->size() > 0)
5592           // This is a template declaration.
5593           IsVariableTemplate = true;
5594 
5595           // Check that we can declare a template here.
5596           if (CheckTemplateDeclScope(S, TemplateParams))
5597             return nullptr;
5598 
5599           // Only C++1y supports variable templates (N3651).
5600           Diag(D.getIdentifierLoc(),
5601                getLangOpts().CPlusPlus14
5602                    ? diag::warn_cxx11_compat_variable_template
5603                    : diag::ext_variable_template);
5604         }
5605       }
5606     } else {
5607       assert(
5608           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5609           "should have a 'template<>' for this decl");
5610     }
5611 
5612     if (IsVariableTemplateSpecialization) {
5613       SourceLocation TemplateKWLoc =
5614           TemplateParamLists.size() > 0
5615               ? TemplateParamLists[0]->getTemplateLoc()
5616               : SourceLocation();
5617       DeclResult Res = ActOnVarTemplateSpecialization(
5618           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5619           IsPartialSpecialization);
5620       if (Res.isInvalid())
5621         return nullptr;
5622       NewVD = cast<VarDecl>(Res.get());
5623       AddToScope = false;
5624     } else
5625       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5626                               D.getIdentifierLoc(), II, R, TInfo, SC);
5627 
5628     // If this is supposed to be a variable template, create it as such.
5629     if (IsVariableTemplate) {
5630       NewTemplate =
5631           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5632                                   TemplateParams, NewVD);
5633       NewVD->setDescribedVarTemplate(NewTemplate);
5634     }
5635 
5636     // If this decl has an auto type in need of deduction, make a note of the
5637     // Decl so we can diagnose uses of it in its own initializer.
5638     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5639       ParsingInitForAutoVars.insert(NewVD);
5640 
5641     if (D.isInvalidType() || Invalid) {
5642       NewVD->setInvalidDecl();
5643       if (NewTemplate)
5644         NewTemplate->setInvalidDecl();
5645     }
5646 
5647     SetNestedNameSpecifier(NewVD, D);
5648 
5649     // If we have any template parameter lists that don't directly belong to
5650     // the variable (matching the scope specifier), store them.
5651     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5652     if (TemplateParamLists.size() > VDTemplateParamLists)
5653       NewVD->setTemplateParameterListsInfo(
5654           Context, TemplateParamLists.size() - VDTemplateParamLists,
5655           TemplateParamLists.data());
5656 
5657     if (D.getDeclSpec().isConstexprSpecified())
5658       NewVD->setConstexpr(true);
5659   }
5660 
5661   // Set the lexical context. If the declarator has a C++ scope specifier, the
5662   // lexical context will be different from the semantic context.
5663   NewVD->setLexicalDeclContext(CurContext);
5664   if (NewTemplate)
5665     NewTemplate->setLexicalDeclContext(CurContext);
5666 
5667   if (IsLocalExternDecl)
5668     NewVD->setLocalExternDecl();
5669 
5670   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5671     // C++11 [dcl.stc]p4:
5672     //   When thread_local is applied to a variable of block scope the
5673     //   storage-class-specifier static is implied if it does not appear
5674     //   explicitly.
5675     // Core issue: 'static' is not implied if the variable is declared
5676     //   'extern'.
5677     if (NewVD->hasLocalStorage() &&
5678         (SCSpec != DeclSpec::SCS_unspecified ||
5679          TSCS != DeclSpec::TSCS_thread_local ||
5680          !DC->isFunctionOrMethod()))
5681       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5682            diag::err_thread_non_global)
5683         << DeclSpec::getSpecifierName(TSCS);
5684     else if (!Context.getTargetInfo().isTLSSupported())
5685       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5686            diag::err_thread_unsupported);
5687     else
5688       NewVD->setTSCSpec(TSCS);
5689   }
5690 
5691   // C99 6.7.4p3
5692   //   An inline definition of a function with external linkage shall
5693   //   not contain a definition of a modifiable object with static or
5694   //   thread storage duration...
5695   // We only apply this when the function is required to be defined
5696   // elsewhere, i.e. when the function is not 'extern inline'.  Note
5697   // that a local variable with thread storage duration still has to
5698   // be marked 'static'.  Also note that it's possible to get these
5699   // semantics in C++ using __attribute__((gnu_inline)).
5700   if (SC == SC_Static && S->getFnParent() != nullptr &&
5701       !NewVD->getType().isConstQualified()) {
5702     FunctionDecl *CurFD = getCurFunctionDecl();
5703     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5704       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5705            diag::warn_static_local_in_extern_inline);
5706       MaybeSuggestAddingStaticToDecl(CurFD);
5707     }
5708   }
5709 
5710   if (D.getDeclSpec().isModulePrivateSpecified()) {
5711     if (IsVariableTemplateSpecialization)
5712       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5713           << (IsPartialSpecialization ? 1 : 0)
5714           << FixItHint::CreateRemoval(
5715                  D.getDeclSpec().getModulePrivateSpecLoc());
5716     else if (IsExplicitSpecialization)
5717       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5718         << 2
5719         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5720     else if (NewVD->hasLocalStorage())
5721       Diag(NewVD->getLocation(), diag::err_module_private_local)
5722         << 0 << NewVD->getDeclName()
5723         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5724         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5725     else {
5726       NewVD->setModulePrivate();
5727       if (NewTemplate)
5728         NewTemplate->setModulePrivate();
5729     }
5730   }
5731 
5732   // Handle attributes prior to checking for duplicates in MergeVarDecl
5733   ProcessDeclAttributes(S, NewVD, D);
5734 
5735   if (getLangOpts().CUDA) {
5736     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5737     // storage [duration]."
5738     if (SC == SC_None && S->getFnParent() != nullptr &&
5739         (NewVD->hasAttr<CUDASharedAttr>() ||
5740          NewVD->hasAttr<CUDAConstantAttr>())) {
5741       NewVD->setStorageClass(SC_Static);
5742     }
5743   }
5744 
5745   // Ensure that dllimport globals without explicit storage class are treated as
5746   // extern. The storage class is set above using parsed attributes. Now we can
5747   // check the VarDecl itself.
5748   assert(!NewVD->hasAttr<DLLImportAttr>() ||
5749          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
5750          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
5751 
5752   // In auto-retain/release, infer strong retension for variables of
5753   // retainable type.
5754   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5755     NewVD->setInvalidDecl();
5756 
5757   // Handle GNU asm-label extension (encoded as an attribute).
5758   if (Expr *E = (Expr*)D.getAsmLabel()) {
5759     // The parser guarantees this is a string.
5760     StringLiteral *SE = cast<StringLiteral>(E);
5761     StringRef Label = SE->getString();
5762     if (S->getFnParent() != nullptr) {
5763       switch (SC) {
5764       case SC_None:
5765       case SC_Auto:
5766         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5767         break;
5768       case SC_Register:
5769         // Local Named register
5770         if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5771           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5772         break;
5773       case SC_Static:
5774       case SC_Extern:
5775       case SC_PrivateExtern:
5776       case SC_OpenCLWorkGroupLocal:
5777         break;
5778       }
5779     } else if (SC == SC_Register) {
5780       // Global Named register
5781       if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5782         Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5783       if (!R->isIntegralType(Context) && !R->isPointerType()) {
5784         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
5785         NewVD->setInvalidDecl(true);
5786       }
5787     }
5788 
5789     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
5790                                                 Context, Label, 0));
5791   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5792     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5793       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5794     if (I != ExtnameUndeclaredIdentifiers.end()) {
5795       NewVD->addAttr(I->second);
5796       ExtnameUndeclaredIdentifiers.erase(I);
5797     }
5798   }
5799 
5800   // Diagnose shadowed variables before filtering for scope.
5801   if (D.getCXXScopeSpec().isEmpty())
5802     CheckShadow(S, NewVD, Previous);
5803 
5804   // Don't consider existing declarations that are in a different
5805   // scope and are out-of-semantic-context declarations (if the new
5806   // declaration has linkage).
5807   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5808                        D.getCXXScopeSpec().isNotEmpty() ||
5809                        IsExplicitSpecialization ||
5810                        IsVariableTemplateSpecialization);
5811 
5812   // Check whether the previous declaration is in the same block scope. This
5813   // affects whether we merge types with it, per C++11 [dcl.array]p3.
5814   if (getLangOpts().CPlusPlus &&
5815       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5816     NewVD->setPreviousDeclInSameBlockScope(
5817         Previous.isSingleResult() && !Previous.isShadowed() &&
5818         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
5819 
5820   if (!getLangOpts().CPlusPlus) {
5821     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5822   } else {
5823     // If this is an explicit specialization of a static data member, check it.
5824     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5825         CheckMemberSpecialization(NewVD, Previous))
5826       NewVD->setInvalidDecl();
5827 
5828     // Merge the decl with the existing one if appropriate.
5829     if (!Previous.empty()) {
5830       if (Previous.isSingleResult() &&
5831           isa<FieldDecl>(Previous.getFoundDecl()) &&
5832           D.getCXXScopeSpec().isSet()) {
5833         // The user tried to define a non-static data member
5834         // out-of-line (C++ [dcl.meaning]p1).
5835         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5836           << D.getCXXScopeSpec().getRange();
5837         Previous.clear();
5838         NewVD->setInvalidDecl();
5839       }
5840     } else if (D.getCXXScopeSpec().isSet()) {
5841       // No previous declaration in the qualifying scope.
5842       Diag(D.getIdentifierLoc(), diag::err_no_member)
5843         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
5844         << D.getCXXScopeSpec().getRange();
5845       NewVD->setInvalidDecl();
5846     }
5847 
5848     if (!IsVariableTemplateSpecialization)
5849       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5850 
5851     if (NewTemplate) {
5852       VarTemplateDecl *PrevVarTemplate =
5853           NewVD->getPreviousDecl()
5854               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5855               : nullptr;
5856 
5857       // Check the template parameter list of this declaration, possibly
5858       // merging in the template parameter list from the previous variable
5859       // template declaration.
5860       if (CheckTemplateParameterList(
5861               TemplateParams,
5862               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5863                               : nullptr,
5864               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5865                DC->isDependentContext())
5866                   ? TPC_ClassTemplateMember
5867                   : TPC_VarTemplate))
5868         NewVD->setInvalidDecl();
5869 
5870       // If we are providing an explicit specialization of a static variable
5871       // template, make a note of that.
5872       if (PrevVarTemplate &&
5873           PrevVarTemplate->getInstantiatedFromMemberTemplate())
5874         PrevVarTemplate->setMemberSpecialization();
5875     }
5876   }
5877 
5878   ProcessPragmaWeak(S, NewVD);
5879 
5880   // If this is the first declaration of an extern C variable, update
5881   // the map of such variables.
5882   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
5883       isIncompleteDeclExternC(*this, NewVD))
5884     RegisterLocallyScopedExternCDecl(NewVD, S);
5885 
5886   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5887     Decl *ManglingContextDecl;
5888     if (MangleNumberingContext *MCtx =
5889             getCurrentMangleNumberContext(NewVD->getDeclContext(),
5890                                           ManglingContextDecl)) {
5891       Context.setManglingNumber(
5892           NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
5893       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5894     }
5895   }
5896 
5897   if (D.isRedeclaration() && !Previous.empty()) {
5898     checkDLLAttributeRedeclaration(
5899         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
5900         IsExplicitSpecialization);
5901   }
5902 
5903   if (NewTemplate) {
5904     if (NewVD->isInvalidDecl())
5905       NewTemplate->setInvalidDecl();
5906     ActOnDocumentableDecl(NewTemplate);
5907     return NewTemplate;
5908   }
5909 
5910   return NewVD;
5911 }
5912 
5913 /// \brief Diagnose variable or built-in function shadowing.  Implements
5914 /// -Wshadow.
5915 ///
5916 /// This method is called whenever a VarDecl is added to a "useful"
5917 /// scope.
5918 ///
5919 /// \param S the scope in which the shadowing name is being declared
5920 /// \param R the lookup of the name
5921 ///
5922 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
5923   // Return if warning is ignored.
5924   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
5925     return;
5926 
5927   // Don't diagnose declarations at file scope.
5928   if (D->hasGlobalStorage())
5929     return;
5930 
5931   DeclContext *NewDC = D->getDeclContext();
5932 
5933   // Only diagnose if we're shadowing an unambiguous field or variable.
5934   if (R.getResultKind() != LookupResult::Found)
5935     return;
5936 
5937   NamedDecl* ShadowedDecl = R.getFoundDecl();
5938   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5939     return;
5940 
5941   // Fields are not shadowed by variables in C++ static methods.
5942   if (isa<FieldDecl>(ShadowedDecl))
5943     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5944       if (MD->isStatic())
5945         return;
5946 
5947   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5948     if (shadowedVar->isExternC()) {
5949       // For shadowing external vars, make sure that we point to the global
5950       // declaration, not a locally scoped extern declaration.
5951       for (auto I : shadowedVar->redecls())
5952         if (I->isFileVarDecl()) {
5953           ShadowedDecl = I;
5954           break;
5955         }
5956     }
5957 
5958   DeclContext *OldDC = ShadowedDecl->getDeclContext();
5959 
5960   // Only warn about certain kinds of shadowing for class members.
5961   if (NewDC && NewDC->isRecord()) {
5962     // In particular, don't warn about shadowing non-class members.
5963     if (!OldDC->isRecord())
5964       return;
5965 
5966     // TODO: should we warn about static data members shadowing
5967     // static data members from base classes?
5968 
5969     // TODO: don't diagnose for inaccessible shadowed members.
5970     // This is hard to do perfectly because we might friend the
5971     // shadowing context, but that's just a false negative.
5972   }
5973 
5974   // Determine what kind of declaration we're shadowing.
5975   unsigned Kind;
5976   if (isa<RecordDecl>(OldDC)) {
5977     if (isa<FieldDecl>(ShadowedDecl))
5978       Kind = 3; // field
5979     else
5980       Kind = 2; // static data member
5981   } else if (OldDC->isFileContext())
5982     Kind = 1; // global
5983   else
5984     Kind = 0; // local
5985 
5986   DeclarationName Name = R.getLookupName();
5987 
5988   // Emit warning and note.
5989   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5990     return;
5991   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
5992   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5993 }
5994 
5995 /// \brief Check -Wshadow without the advantage of a previous lookup.
5996 void Sema::CheckShadow(Scope *S, VarDecl *D) {
5997   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
5998     return;
5999 
6000   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6001                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6002   LookupName(R, S);
6003   CheckShadow(S, D, R);
6004 }
6005 
6006 /// Check for conflict between this global or extern "C" declaration and
6007 /// previous global or extern "C" declarations. This is only used in C++.
6008 template<typename T>
6009 static bool checkGlobalOrExternCConflict(
6010     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6011   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6012   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6013 
6014   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6015     // The common case: this global doesn't conflict with any extern "C"
6016     // declaration.
6017     return false;
6018   }
6019 
6020   if (Prev) {
6021     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6022       // Both the old and new declarations have C language linkage. This is a
6023       // redeclaration.
6024       Previous.clear();
6025       Previous.addDecl(Prev);
6026       return true;
6027     }
6028 
6029     // This is a global, non-extern "C" declaration, and there is a previous
6030     // non-global extern "C" declaration. Diagnose if this is a variable
6031     // declaration.
6032     if (!isa<VarDecl>(ND))
6033       return false;
6034   } else {
6035     // The declaration is extern "C". Check for any declaration in the
6036     // translation unit which might conflict.
6037     if (IsGlobal) {
6038       // We have already performed the lookup into the translation unit.
6039       IsGlobal = false;
6040       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6041            I != E; ++I) {
6042         if (isa<VarDecl>(*I)) {
6043           Prev = *I;
6044           break;
6045         }
6046       }
6047     } else {
6048       DeclContext::lookup_result R =
6049           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6050       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6051            I != E; ++I) {
6052         if (isa<VarDecl>(*I)) {
6053           Prev = *I;
6054           break;
6055         }
6056         // FIXME: If we have any other entity with this name in global scope,
6057         // the declaration is ill-formed, but that is a defect: it breaks the
6058         // 'stat' hack, for instance. Only variables can have mangled name
6059         // clashes with extern "C" declarations, so only they deserve a
6060         // diagnostic.
6061       }
6062     }
6063 
6064     if (!Prev)
6065       return false;
6066   }
6067 
6068   // Use the first declaration's location to ensure we point at something which
6069   // is lexically inside an extern "C" linkage-spec.
6070   assert(Prev && "should have found a previous declaration to diagnose");
6071   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6072     Prev = FD->getFirstDecl();
6073   else
6074     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6075 
6076   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6077     << IsGlobal << ND;
6078   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6079     << IsGlobal;
6080   return false;
6081 }
6082 
6083 /// Apply special rules for handling extern "C" declarations. Returns \c true
6084 /// if we have found that this is a redeclaration of some prior entity.
6085 ///
6086 /// Per C++ [dcl.link]p6:
6087 ///   Two declarations [for a function or variable] with C language linkage
6088 ///   with the same name that appear in different scopes refer to the same
6089 ///   [entity]. An entity with C language linkage shall not be declared with
6090 ///   the same name as an entity in global scope.
6091 template<typename T>
6092 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6093                                                   LookupResult &Previous) {
6094   if (!S.getLangOpts().CPlusPlus) {
6095     // In C, when declaring a global variable, look for a corresponding 'extern'
6096     // variable declared in function scope. We don't need this in C++, because
6097     // we find local extern decls in the surrounding file-scope DeclContext.
6098     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6099       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6100         Previous.clear();
6101         Previous.addDecl(Prev);
6102         return true;
6103       }
6104     }
6105     return false;
6106   }
6107 
6108   // A declaration in the translation unit can conflict with an extern "C"
6109   // declaration.
6110   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6111     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6112 
6113   // An extern "C" declaration can conflict with a declaration in the
6114   // translation unit or can be a redeclaration of an extern "C" declaration
6115   // in another scope.
6116   if (isIncompleteDeclExternC(S,ND))
6117     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6118 
6119   // Neither global nor extern "C": nothing to do.
6120   return false;
6121 }
6122 
6123 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6124   // If the decl is already known invalid, don't check it.
6125   if (NewVD->isInvalidDecl())
6126     return;
6127 
6128   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6129   QualType T = TInfo->getType();
6130 
6131   // Defer checking an 'auto' type until its initializer is attached.
6132   if (T->isUndeducedType())
6133     return;
6134 
6135   if (NewVD->hasAttrs())
6136     CheckAlignasUnderalignment(NewVD);
6137 
6138   if (T->isObjCObjectType()) {
6139     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6140       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6141     T = Context.getObjCObjectPointerType(T);
6142     NewVD->setType(T);
6143   }
6144 
6145   // Emit an error if an address space was applied to decl with local storage.
6146   // This includes arrays of objects with address space qualifiers, but not
6147   // automatic variables that point to other address spaces.
6148   // ISO/IEC TR 18037 S5.1.2
6149   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6150     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6151     NewVD->setInvalidDecl();
6152     return;
6153   }
6154 
6155   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6156   // __constant address space.
6157   if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
6158       && T.getAddressSpace() != LangAS::opencl_constant
6159       && !T->isSamplerT()){
6160     Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
6161     NewVD->setInvalidDecl();
6162     return;
6163   }
6164 
6165   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6166   // scope.
6167   if ((getLangOpts().OpenCLVersion >= 120)
6168       && NewVD->isStaticLocal()) {
6169     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6170     NewVD->setInvalidDecl();
6171     return;
6172   }
6173 
6174   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6175       && !NewVD->hasAttr<BlocksAttr>()) {
6176     if (getLangOpts().getGC() != LangOptions::NonGC)
6177       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6178     else {
6179       assert(!getLangOpts().ObjCAutoRefCount);
6180       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6181     }
6182   }
6183 
6184   bool isVM = T->isVariablyModifiedType();
6185   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6186       NewVD->hasAttr<BlocksAttr>())
6187     getCurFunction()->setHasBranchProtectedScope();
6188 
6189   if ((isVM && NewVD->hasLinkage()) ||
6190       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6191     bool SizeIsNegative;
6192     llvm::APSInt Oversized;
6193     TypeSourceInfo *FixedTInfo =
6194       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6195                                                     SizeIsNegative, Oversized);
6196     if (!FixedTInfo && T->isVariableArrayType()) {
6197       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6198       // FIXME: This won't give the correct result for
6199       // int a[10][n];
6200       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6201 
6202       if (NewVD->isFileVarDecl())
6203         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6204         << SizeRange;
6205       else if (NewVD->isStaticLocal())
6206         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6207         << SizeRange;
6208       else
6209         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6210         << SizeRange;
6211       NewVD->setInvalidDecl();
6212       return;
6213     }
6214 
6215     if (!FixedTInfo) {
6216       if (NewVD->isFileVarDecl())
6217         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6218       else
6219         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6220       NewVD->setInvalidDecl();
6221       return;
6222     }
6223 
6224     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6225     NewVD->setType(FixedTInfo->getType());
6226     NewVD->setTypeSourceInfo(FixedTInfo);
6227   }
6228 
6229   if (T->isVoidType()) {
6230     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6231     //                    of objects and functions.
6232     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6233       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6234         << T;
6235       NewVD->setInvalidDecl();
6236       return;
6237     }
6238   }
6239 
6240   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6241     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6242     NewVD->setInvalidDecl();
6243     return;
6244   }
6245 
6246   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6247     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6248     NewVD->setInvalidDecl();
6249     return;
6250   }
6251 
6252   if (NewVD->isConstexpr() && !T->isDependentType() &&
6253       RequireLiteralType(NewVD->getLocation(), T,
6254                          diag::err_constexpr_var_non_literal)) {
6255     NewVD->setInvalidDecl();
6256     return;
6257   }
6258 }
6259 
6260 /// \brief Perform semantic checking on a newly-created variable
6261 /// declaration.
6262 ///
6263 /// This routine performs all of the type-checking required for a
6264 /// variable declaration once it has been built. It is used both to
6265 /// check variables after they have been parsed and their declarators
6266 /// have been translated into a declaration, and to check variables
6267 /// that have been instantiated from a template.
6268 ///
6269 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6270 ///
6271 /// Returns true if the variable declaration is a redeclaration.
6272 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6273   CheckVariableDeclarationType(NewVD);
6274 
6275   // If the decl is already known invalid, don't check it.
6276   if (NewVD->isInvalidDecl())
6277     return false;
6278 
6279   // If we did not find anything by this name, look for a non-visible
6280   // extern "C" declaration with the same name.
6281   if (Previous.empty() &&
6282       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6283     Previous.setShadowed();
6284 
6285   // Filter out any non-conflicting previous declarations.
6286   filterNonConflictingPreviousDecls(Context, NewVD, Previous);
6287 
6288   if (!Previous.empty()) {
6289     MergeVarDecl(NewVD, Previous);
6290     return true;
6291   }
6292   return false;
6293 }
6294 
6295 /// \brief Data used with FindOverriddenMethod
6296 struct FindOverriddenMethodData {
6297   Sema *S;
6298   CXXMethodDecl *Method;
6299 };
6300 
6301 /// \brief Member lookup function that determines whether a given C++
6302 /// method overrides a method in a base class, to be used with
6303 /// CXXRecordDecl::lookupInBases().
6304 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
6305                                  CXXBasePath &Path,
6306                                  void *UserData) {
6307   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6308 
6309   FindOverriddenMethodData *Data
6310     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
6311 
6312   DeclarationName Name = Data->Method->getDeclName();
6313 
6314   // FIXME: Do we care about other names here too?
6315   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6316     // We really want to find the base class destructor here.
6317     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
6318     CanQualType CT = Data->S->Context.getCanonicalType(T);
6319 
6320     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
6321   }
6322 
6323   for (Path.Decls = BaseRecord->lookup(Name);
6324        !Path.Decls.empty();
6325        Path.Decls = Path.Decls.slice(1)) {
6326     NamedDecl *D = Path.Decls.front();
6327     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6328       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
6329         return true;
6330     }
6331   }
6332 
6333   return false;
6334 }
6335 
6336 namespace {
6337   enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6338 }
6339 /// \brief Report an error regarding overriding, along with any relevant
6340 /// overriden methods.
6341 ///
6342 /// \param DiagID the primary error to report.
6343 /// \param MD the overriding method.
6344 /// \param OEK which overrides to include as notes.
6345 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6346                             OverrideErrorKind OEK = OEK_All) {
6347   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6348   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6349                                       E = MD->end_overridden_methods();
6350        I != E; ++I) {
6351     // This check (& the OEK parameter) could be replaced by a predicate, but
6352     // without lambdas that would be overkill. This is still nicer than writing
6353     // out the diag loop 3 times.
6354     if ((OEK == OEK_All) ||
6355         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6356         (OEK == OEK_Deleted && (*I)->isDeleted()))
6357       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6358   }
6359 }
6360 
6361 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6362 /// and if so, check that it's a valid override and remember it.
6363 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6364   // Look for methods in base classes that this method might override.
6365   CXXBasePaths Paths;
6366   FindOverriddenMethodData Data;
6367   Data.Method = MD;
6368   Data.S = this;
6369   bool hasDeletedOverridenMethods = false;
6370   bool hasNonDeletedOverridenMethods = false;
6371   bool AddedAny = false;
6372   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
6373     for (auto *I : Paths.found_decls()) {
6374       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6375         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6376         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6377             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6378             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6379             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6380           hasDeletedOverridenMethods |= OldMD->isDeleted();
6381           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6382           AddedAny = true;
6383         }
6384       }
6385     }
6386   }
6387 
6388   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6389     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6390   }
6391   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6392     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6393   }
6394 
6395   return AddedAny;
6396 }
6397 
6398 namespace {
6399   // Struct for holding all of the extra arguments needed by
6400   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6401   struct ActOnFDArgs {
6402     Scope *S;
6403     Declarator &D;
6404     MultiTemplateParamsArg TemplateParamLists;
6405     bool AddToScope;
6406   };
6407 }
6408 
6409 namespace {
6410 
6411 // Callback to only accept typo corrections that have a non-zero edit distance.
6412 // Also only accept corrections that have the same parent decl.
6413 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6414  public:
6415   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6416                             CXXRecordDecl *Parent)
6417       : Context(Context), OriginalFD(TypoFD),
6418         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6419 
6420   bool ValidateCandidate(const TypoCorrection &candidate) override {
6421     if (candidate.getEditDistance() == 0)
6422       return false;
6423 
6424     SmallVector<unsigned, 1> MismatchedParams;
6425     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6426                                           CDeclEnd = candidate.end();
6427          CDecl != CDeclEnd; ++CDecl) {
6428       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6429 
6430       if (FD && !FD->hasBody() &&
6431           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6432         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6433           CXXRecordDecl *Parent = MD->getParent();
6434           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6435             return true;
6436         } else if (!ExpectedParent) {
6437           return true;
6438         }
6439       }
6440     }
6441 
6442     return false;
6443   }
6444 
6445  private:
6446   ASTContext &Context;
6447   FunctionDecl *OriginalFD;
6448   CXXRecordDecl *ExpectedParent;
6449 };
6450 
6451 }
6452 
6453 /// \brief Generate diagnostics for an invalid function redeclaration.
6454 ///
6455 /// This routine handles generating the diagnostic messages for an invalid
6456 /// function redeclaration, including finding possible similar declarations
6457 /// or performing typo correction if there are no previous declarations with
6458 /// the same name.
6459 ///
6460 /// Returns a NamedDecl iff typo correction was performed and substituting in
6461 /// the new declaration name does not cause new errors.
6462 static NamedDecl *DiagnoseInvalidRedeclaration(
6463     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6464     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6465   DeclarationName Name = NewFD->getDeclName();
6466   DeclContext *NewDC = NewFD->getDeclContext();
6467   SmallVector<unsigned, 1> MismatchedParams;
6468   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6469   TypoCorrection Correction;
6470   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6471   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6472                                    : diag::err_member_decl_does_not_match;
6473   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6474                     IsLocalFriend ? Sema::LookupLocalFriendName
6475                                   : Sema::LookupOrdinaryName,
6476                     Sema::ForRedeclaration);
6477 
6478   NewFD->setInvalidDecl();
6479   if (IsLocalFriend)
6480     SemaRef.LookupName(Prev, S);
6481   else
6482     SemaRef.LookupQualifiedName(Prev, NewDC);
6483   assert(!Prev.isAmbiguous() &&
6484          "Cannot have an ambiguity in previous-declaration lookup");
6485   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6486   if (!Prev.empty()) {
6487     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6488          Func != FuncEnd; ++Func) {
6489       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6490       if (FD &&
6491           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6492         // Add 1 to the index so that 0 can mean the mismatch didn't
6493         // involve a parameter
6494         unsigned ParamNum =
6495             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6496         NearMatches.push_back(std::make_pair(FD, ParamNum));
6497       }
6498     }
6499   // If the qualified name lookup yielded nothing, try typo correction
6500   } else if ((Correction = SemaRef.CorrectTypo(
6501                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6502                   &ExtraArgs.D.getCXXScopeSpec(),
6503                   llvm::make_unique<DifferentNameValidatorCCC>(
6504                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
6505                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6506     // Set up everything for the call to ActOnFunctionDeclarator
6507     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6508                               ExtraArgs.D.getIdentifierLoc());
6509     Previous.clear();
6510     Previous.setLookupName(Correction.getCorrection());
6511     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6512                                     CDeclEnd = Correction.end();
6513          CDecl != CDeclEnd; ++CDecl) {
6514       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6515       if (FD && !FD->hasBody() &&
6516           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6517         Previous.addDecl(FD);
6518       }
6519     }
6520     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6521 
6522     NamedDecl *Result;
6523     // Retry building the function declaration with the new previous
6524     // declarations, and with errors suppressed.
6525     {
6526       // Trap errors.
6527       Sema::SFINAETrap Trap(SemaRef);
6528 
6529       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6530       // pieces need to verify the typo-corrected C++ declaration and hopefully
6531       // eliminate the need for the parameter pack ExtraArgs.
6532       Result = SemaRef.ActOnFunctionDeclarator(
6533           ExtraArgs.S, ExtraArgs.D,
6534           Correction.getCorrectionDecl()->getDeclContext(),
6535           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6536           ExtraArgs.AddToScope);
6537 
6538       if (Trap.hasErrorOccurred())
6539         Result = nullptr;
6540     }
6541 
6542     if (Result) {
6543       // Determine which correction we picked.
6544       Decl *Canonical = Result->getCanonicalDecl();
6545       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6546            I != E; ++I)
6547         if ((*I)->getCanonicalDecl() == Canonical)
6548           Correction.setCorrectionDecl(*I);
6549 
6550       SemaRef.diagnoseTypo(
6551           Correction,
6552           SemaRef.PDiag(IsLocalFriend
6553                           ? diag::err_no_matching_local_friend_suggest
6554                           : diag::err_member_decl_does_not_match_suggest)
6555             << Name << NewDC << IsDefinition);
6556       return Result;
6557     }
6558 
6559     // Pretend the typo correction never occurred
6560     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6561                               ExtraArgs.D.getIdentifierLoc());
6562     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6563     Previous.clear();
6564     Previous.setLookupName(Name);
6565   }
6566 
6567   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6568       << Name << NewDC << IsDefinition << NewFD->getLocation();
6569 
6570   bool NewFDisConst = false;
6571   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6572     NewFDisConst = NewMD->isConst();
6573 
6574   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6575        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6576        NearMatch != NearMatchEnd; ++NearMatch) {
6577     FunctionDecl *FD = NearMatch->first;
6578     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6579     bool FDisConst = MD && MD->isConst();
6580     bool IsMember = MD || !IsLocalFriend;
6581 
6582     // FIXME: These notes are poorly worded for the local friend case.
6583     if (unsigned Idx = NearMatch->second) {
6584       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6585       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6586       if (Loc.isInvalid()) Loc = FD->getLocation();
6587       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6588                                  : diag::note_local_decl_close_param_match)
6589         << Idx << FDParam->getType()
6590         << NewFD->getParamDecl(Idx - 1)->getType();
6591     } else if (FDisConst != NewFDisConst) {
6592       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6593           << NewFDisConst << FD->getSourceRange().getEnd();
6594     } else
6595       SemaRef.Diag(FD->getLocation(),
6596                    IsMember ? diag::note_member_def_close_match
6597                             : diag::note_local_decl_close_match);
6598   }
6599   return nullptr;
6600 }
6601 
6602 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
6603   switch (D.getDeclSpec().getStorageClassSpec()) {
6604   default: llvm_unreachable("Unknown storage class!");
6605   case DeclSpec::SCS_auto:
6606   case DeclSpec::SCS_register:
6607   case DeclSpec::SCS_mutable:
6608     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6609                  diag::err_typecheck_sclass_func);
6610     D.setInvalidType();
6611     break;
6612   case DeclSpec::SCS_unspecified: break;
6613   case DeclSpec::SCS_extern:
6614     if (D.getDeclSpec().isExternInLinkageSpec())
6615       return SC_None;
6616     return SC_Extern;
6617   case DeclSpec::SCS_static: {
6618     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6619       // C99 6.7.1p5:
6620       //   The declaration of an identifier for a function that has
6621       //   block scope shall have no explicit storage-class specifier
6622       //   other than extern
6623       // See also (C++ [dcl.stc]p4).
6624       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6625                    diag::err_static_block_func);
6626       break;
6627     } else
6628       return SC_Static;
6629   }
6630   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6631   }
6632 
6633   // No explicit storage class has already been returned
6634   return SC_None;
6635 }
6636 
6637 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6638                                            DeclContext *DC, QualType &R,
6639                                            TypeSourceInfo *TInfo,
6640                                            StorageClass SC,
6641                                            bool &IsVirtualOkay) {
6642   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6643   DeclarationName Name = NameInfo.getName();
6644 
6645   FunctionDecl *NewFD = nullptr;
6646   bool isInline = D.getDeclSpec().isInlineSpecified();
6647 
6648   if (!SemaRef.getLangOpts().CPlusPlus) {
6649     // Determine whether the function was written with a
6650     // prototype. This true when:
6651     //   - there is a prototype in the declarator, or
6652     //   - the type R of the function is some kind of typedef or other reference
6653     //     to a type name (which eventually refers to a function type).
6654     bool HasPrototype =
6655       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6656       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6657 
6658     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6659                                  D.getLocStart(), NameInfo, R,
6660                                  TInfo, SC, isInline,
6661                                  HasPrototype, false);
6662     if (D.isInvalidType())
6663       NewFD->setInvalidDecl();
6664 
6665     return NewFD;
6666   }
6667 
6668   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6669   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6670 
6671   // Check that the return type is not an abstract class type.
6672   // For record types, this is done by the AbstractClassUsageDiagnoser once
6673   // the class has been completely parsed.
6674   if (!DC->isRecord() &&
6675       SemaRef.RequireNonAbstractType(
6676           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6677           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
6678     D.setInvalidType();
6679 
6680   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6681     // This is a C++ constructor declaration.
6682     assert(DC->isRecord() &&
6683            "Constructors can only be declared in a member context");
6684 
6685     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6686     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6687                                       D.getLocStart(), NameInfo,
6688                                       R, TInfo, isExplicit, isInline,
6689                                       /*isImplicitlyDeclared=*/false,
6690                                       isConstexpr);
6691 
6692   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6693     // This is a C++ destructor declaration.
6694     if (DC->isRecord()) {
6695       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6696       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6697       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6698                                         SemaRef.Context, Record,
6699                                         D.getLocStart(),
6700                                         NameInfo, R, TInfo, isInline,
6701                                         /*isImplicitlyDeclared=*/false);
6702 
6703       // If the class is complete, then we now create the implicit exception
6704       // specification. If the class is incomplete or dependent, we can't do
6705       // it yet.
6706       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6707           Record->getDefinition() && !Record->isBeingDefined() &&
6708           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6709         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6710       }
6711 
6712       IsVirtualOkay = true;
6713       return NewDD;
6714 
6715     } else {
6716       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6717       D.setInvalidType();
6718 
6719       // Create a FunctionDecl to satisfy the function definition parsing
6720       // code path.
6721       return FunctionDecl::Create(SemaRef.Context, DC,
6722                                   D.getLocStart(),
6723                                   D.getIdentifierLoc(), Name, R, TInfo,
6724                                   SC, isInline,
6725                                   /*hasPrototype=*/true, isConstexpr);
6726     }
6727 
6728   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6729     if (!DC->isRecord()) {
6730       SemaRef.Diag(D.getIdentifierLoc(),
6731            diag::err_conv_function_not_member);
6732       return nullptr;
6733     }
6734 
6735     SemaRef.CheckConversionDeclarator(D, R, SC);
6736     IsVirtualOkay = true;
6737     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6738                                      D.getLocStart(), NameInfo,
6739                                      R, TInfo, isInline, isExplicit,
6740                                      isConstexpr, SourceLocation());
6741 
6742   } else if (DC->isRecord()) {
6743     // If the name of the function is the same as the name of the record,
6744     // then this must be an invalid constructor that has a return type.
6745     // (The parser checks for a return type and makes the declarator a
6746     // constructor if it has no return type).
6747     if (Name.getAsIdentifierInfo() &&
6748         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6749       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6750         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6751         << SourceRange(D.getIdentifierLoc());
6752       return nullptr;
6753     }
6754 
6755     // This is a C++ method declaration.
6756     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6757                                                cast<CXXRecordDecl>(DC),
6758                                                D.getLocStart(), NameInfo, R,
6759                                                TInfo, SC, isInline,
6760                                                isConstexpr, SourceLocation());
6761     IsVirtualOkay = !Ret->isStatic();
6762     return Ret;
6763   } else {
6764     bool isFriend =
6765         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
6766     if (!isFriend && SemaRef.CurContext->isRecord())
6767       return nullptr;
6768 
6769     // Determine whether the function was written with a
6770     // prototype. This true when:
6771     //   - we're in C++ (where every function has a prototype),
6772     return FunctionDecl::Create(SemaRef.Context, DC,
6773                                 D.getLocStart(),
6774                                 NameInfo, R, TInfo, SC, isInline,
6775                                 true/*HasPrototype*/, isConstexpr);
6776   }
6777 }
6778 
6779 enum OpenCLParamType {
6780   ValidKernelParam,
6781   PtrPtrKernelParam,
6782   PtrKernelParam,
6783   PrivatePtrKernelParam,
6784   InvalidKernelParam,
6785   RecordKernelParam
6786 };
6787 
6788 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6789   if (PT->isPointerType()) {
6790     QualType PointeeType = PT->getPointeeType();
6791     if (PointeeType->isPointerType())
6792       return PtrPtrKernelParam;
6793     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
6794                                               : PtrKernelParam;
6795   }
6796 
6797   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6798   // be used as builtin types.
6799 
6800   if (PT->isImageType())
6801     return PtrKernelParam;
6802 
6803   if (PT->isBooleanType())
6804     return InvalidKernelParam;
6805 
6806   if (PT->isEventT())
6807     return InvalidKernelParam;
6808 
6809   if (PT->isHalfType())
6810     return InvalidKernelParam;
6811 
6812   if (PT->isRecordType())
6813     return RecordKernelParam;
6814 
6815   return ValidKernelParam;
6816 }
6817 
6818 static void checkIsValidOpenCLKernelParameter(
6819   Sema &S,
6820   Declarator &D,
6821   ParmVarDecl *Param,
6822   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
6823   QualType PT = Param->getType();
6824 
6825   // Cache the valid types we encounter to avoid rechecking structs that are
6826   // used again
6827   if (ValidTypes.count(PT.getTypePtr()))
6828     return;
6829 
6830   switch (getOpenCLKernelParameterType(PT)) {
6831   case PtrPtrKernelParam:
6832     // OpenCL v1.2 s6.9.a:
6833     // A kernel function argument cannot be declared as a
6834     // pointer to a pointer type.
6835     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6836     D.setInvalidType();
6837     return;
6838 
6839   case PrivatePtrKernelParam:
6840     // OpenCL v1.2 s6.9.a:
6841     // A kernel function argument cannot be declared as a
6842     // pointer to the private address space.
6843     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
6844     D.setInvalidType();
6845     return;
6846 
6847     // OpenCL v1.2 s6.9.k:
6848     // Arguments to kernel functions in a program cannot be declared with the
6849     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6850     // uintptr_t or a struct and/or union that contain fields declared to be
6851     // one of these built-in scalar types.
6852 
6853   case InvalidKernelParam:
6854     // OpenCL v1.2 s6.8 n:
6855     // A kernel function argument cannot be declared
6856     // of event_t type.
6857     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6858     D.setInvalidType();
6859     return;
6860 
6861   case PtrKernelParam:
6862   case ValidKernelParam:
6863     ValidTypes.insert(PT.getTypePtr());
6864     return;
6865 
6866   case RecordKernelParam:
6867     break;
6868   }
6869 
6870   // Track nested structs we will inspect
6871   SmallVector<const Decl *, 4> VisitStack;
6872 
6873   // Track where we are in the nested structs. Items will migrate from
6874   // VisitStack to HistoryStack as we do the DFS for bad field.
6875   SmallVector<const FieldDecl *, 4> HistoryStack;
6876   HistoryStack.push_back(nullptr);
6877 
6878   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6879   VisitStack.push_back(PD);
6880 
6881   assert(VisitStack.back() && "First decl null?");
6882 
6883   do {
6884     const Decl *Next = VisitStack.pop_back_val();
6885     if (!Next) {
6886       assert(!HistoryStack.empty());
6887       // Found a marker, we have gone up a level
6888       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6889         ValidTypes.insert(Hist->getType().getTypePtr());
6890 
6891       continue;
6892     }
6893 
6894     // Adds everything except the original parameter declaration (which is not a
6895     // field itself) to the history stack.
6896     const RecordDecl *RD;
6897     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6898       HistoryStack.push_back(Field);
6899       RD = Field->getType()->castAs<RecordType>()->getDecl();
6900     } else {
6901       RD = cast<RecordDecl>(Next);
6902     }
6903 
6904     // Add a null marker so we know when we've gone back up a level
6905     VisitStack.push_back(nullptr);
6906 
6907     for (const auto *FD : RD->fields()) {
6908       QualType QT = FD->getType();
6909 
6910       if (ValidTypes.count(QT.getTypePtr()))
6911         continue;
6912 
6913       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6914       if (ParamType == ValidKernelParam)
6915         continue;
6916 
6917       if (ParamType == RecordKernelParam) {
6918         VisitStack.push_back(FD);
6919         continue;
6920       }
6921 
6922       // OpenCL v1.2 s6.9.p:
6923       // Arguments to kernel functions that are declared to be a struct or union
6924       // do not allow OpenCL objects to be passed as elements of the struct or
6925       // union.
6926       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
6927           ParamType == PrivatePtrKernelParam) {
6928         S.Diag(Param->getLocation(),
6929                diag::err_record_with_pointers_kernel_param)
6930           << PT->isUnionType()
6931           << PT;
6932       } else {
6933         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6934       }
6935 
6936       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6937         << PD->getDeclName();
6938 
6939       // We have an error, now let's go back up through history and show where
6940       // the offending field came from
6941       for (ArrayRef<const FieldDecl *>::const_iterator
6942                I = HistoryStack.begin() + 1,
6943                E = HistoryStack.end();
6944            I != E; ++I) {
6945         const FieldDecl *OuterField = *I;
6946         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6947           << OuterField->getType();
6948       }
6949 
6950       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6951         << QT->isPointerType()
6952         << QT;
6953       D.setInvalidType();
6954       return;
6955     }
6956   } while (!VisitStack.empty());
6957 }
6958 
6959 NamedDecl*
6960 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
6961                               TypeSourceInfo *TInfo, LookupResult &Previous,
6962                               MultiTemplateParamsArg TemplateParamLists,
6963                               bool &AddToScope) {
6964   QualType R = TInfo->getType();
6965 
6966   assert(R.getTypePtr()->isFunctionType());
6967 
6968   // TODO: consider using NameInfo for diagnostic.
6969   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6970   DeclarationName Name = NameInfo.getName();
6971   StorageClass SC = getFunctionStorageClass(*this, D);
6972 
6973   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6974     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6975          diag::err_invalid_thread)
6976       << DeclSpec::getSpecifierName(TSCS);
6977 
6978   if (D.isFirstDeclarationOfMember())
6979     adjustMemberFunctionCC(R, D.isStaticMember());
6980 
6981   bool isFriend = false;
6982   FunctionTemplateDecl *FunctionTemplate = nullptr;
6983   bool isExplicitSpecialization = false;
6984   bool isFunctionTemplateSpecialization = false;
6985 
6986   bool isDependentClassScopeExplicitSpecialization = false;
6987   bool HasExplicitTemplateArgs = false;
6988   TemplateArgumentListInfo TemplateArgs;
6989 
6990   bool isVirtualOkay = false;
6991 
6992   DeclContext *OriginalDC = DC;
6993   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6994 
6995   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6996                                               isVirtualOkay);
6997   if (!NewFD) return nullptr;
6998 
6999   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7000     NewFD->setTopLevelDeclInObjCContainer();
7001 
7002   // Set the lexical context. If this is a function-scope declaration, or has a
7003   // C++ scope specifier, or is the object of a friend declaration, the lexical
7004   // context will be different from the semantic context.
7005   NewFD->setLexicalDeclContext(CurContext);
7006 
7007   if (IsLocalExternDecl)
7008     NewFD->setLocalExternDecl();
7009 
7010   if (getLangOpts().CPlusPlus) {
7011     bool isInline = D.getDeclSpec().isInlineSpecified();
7012     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7013     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7014     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7015     isFriend = D.getDeclSpec().isFriendSpecified();
7016     if (isFriend && !isInline && D.isFunctionDefinition()) {
7017       // C++ [class.friend]p5
7018       //   A function can be defined in a friend declaration of a
7019       //   class . . . . Such a function is implicitly inline.
7020       NewFD->setImplicitlyInline();
7021     }
7022 
7023     // If this is a method defined in an __interface, and is not a constructor
7024     // or an overloaded operator, then set the pure flag (isVirtual will already
7025     // return true).
7026     if (const CXXRecordDecl *Parent =
7027           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7028       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7029         NewFD->setPure(true);
7030     }
7031 
7032     SetNestedNameSpecifier(NewFD, D);
7033     isExplicitSpecialization = false;
7034     isFunctionTemplateSpecialization = false;
7035     if (D.isInvalidType())
7036       NewFD->setInvalidDecl();
7037 
7038     // Match up the template parameter lists with the scope specifier, then
7039     // determine whether we have a template or a template specialization.
7040     bool Invalid = false;
7041     if (TemplateParameterList *TemplateParams =
7042             MatchTemplateParametersToScopeSpecifier(
7043                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7044                 D.getCXXScopeSpec(),
7045                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7046                     ? D.getName().TemplateId
7047                     : nullptr,
7048                 TemplateParamLists, isFriend, isExplicitSpecialization,
7049                 Invalid)) {
7050       if (TemplateParams->size() > 0) {
7051         // This is a function template
7052 
7053         // Check that we can declare a template here.
7054         if (CheckTemplateDeclScope(S, TemplateParams))
7055           NewFD->setInvalidDecl();
7056 
7057         // A destructor cannot be a template.
7058         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7059           Diag(NewFD->getLocation(), diag::err_destructor_template);
7060           NewFD->setInvalidDecl();
7061         }
7062 
7063         // If we're adding a template to a dependent context, we may need to
7064         // rebuilding some of the types used within the template parameter list,
7065         // now that we know what the current instantiation is.
7066         if (DC->isDependentContext()) {
7067           ContextRAII SavedContext(*this, DC);
7068           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7069             Invalid = true;
7070         }
7071 
7072 
7073         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7074                                                         NewFD->getLocation(),
7075                                                         Name, TemplateParams,
7076                                                         NewFD);
7077         FunctionTemplate->setLexicalDeclContext(CurContext);
7078         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7079 
7080         // For source fidelity, store the other template param lists.
7081         if (TemplateParamLists.size() > 1) {
7082           NewFD->setTemplateParameterListsInfo(Context,
7083                                                TemplateParamLists.size() - 1,
7084                                                TemplateParamLists.data());
7085         }
7086       } else {
7087         // This is a function template specialization.
7088         isFunctionTemplateSpecialization = true;
7089         // For source fidelity, store all the template param lists.
7090         if (TemplateParamLists.size() > 0)
7091           NewFD->setTemplateParameterListsInfo(Context,
7092                                                TemplateParamLists.size(),
7093                                                TemplateParamLists.data());
7094 
7095         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7096         if (isFriend) {
7097           // We want to remove the "template<>", found here.
7098           SourceRange RemoveRange = TemplateParams->getSourceRange();
7099 
7100           // If we remove the template<> and the name is not a
7101           // template-id, we're actually silently creating a problem:
7102           // the friend declaration will refer to an untemplated decl,
7103           // and clearly the user wants a template specialization.  So
7104           // we need to insert '<>' after the name.
7105           SourceLocation InsertLoc;
7106           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7107             InsertLoc = D.getName().getSourceRange().getEnd();
7108             InsertLoc = getLocForEndOfToken(InsertLoc);
7109           }
7110 
7111           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7112             << Name << RemoveRange
7113             << FixItHint::CreateRemoval(RemoveRange)
7114             << FixItHint::CreateInsertion(InsertLoc, "<>");
7115         }
7116       }
7117     }
7118     else {
7119       // All template param lists were matched against the scope specifier:
7120       // this is NOT (an explicit specialization of) a template.
7121       if (TemplateParamLists.size() > 0)
7122         // For source fidelity, store all the template param lists.
7123         NewFD->setTemplateParameterListsInfo(Context,
7124                                              TemplateParamLists.size(),
7125                                              TemplateParamLists.data());
7126     }
7127 
7128     if (Invalid) {
7129       NewFD->setInvalidDecl();
7130       if (FunctionTemplate)
7131         FunctionTemplate->setInvalidDecl();
7132     }
7133 
7134     // C++ [dcl.fct.spec]p5:
7135     //   The virtual specifier shall only be used in declarations of
7136     //   nonstatic class member functions that appear within a
7137     //   member-specification of a class declaration; see 10.3.
7138     //
7139     if (isVirtual && !NewFD->isInvalidDecl()) {
7140       if (!isVirtualOkay) {
7141         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7142              diag::err_virtual_non_function);
7143       } else if (!CurContext->isRecord()) {
7144         // 'virtual' was specified outside of the class.
7145         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7146              diag::err_virtual_out_of_class)
7147           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7148       } else if (NewFD->getDescribedFunctionTemplate()) {
7149         // C++ [temp.mem]p3:
7150         //  A member function template shall not be virtual.
7151         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7152              diag::err_virtual_member_function_template)
7153           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7154       } else {
7155         // Okay: Add virtual to the method.
7156         NewFD->setVirtualAsWritten(true);
7157       }
7158 
7159       if (getLangOpts().CPlusPlus14 &&
7160           NewFD->getReturnType()->isUndeducedType())
7161         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7162     }
7163 
7164     if (getLangOpts().CPlusPlus14 &&
7165         (NewFD->isDependentContext() ||
7166          (isFriend && CurContext->isDependentContext())) &&
7167         NewFD->getReturnType()->isUndeducedType()) {
7168       // If the function template is referenced directly (for instance, as a
7169       // member of the current instantiation), pretend it has a dependent type.
7170       // This is not really justified by the standard, but is the only sane
7171       // thing to do.
7172       // FIXME: For a friend function, we have not marked the function as being
7173       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7174       const FunctionProtoType *FPT =
7175           NewFD->getType()->castAs<FunctionProtoType>();
7176       QualType Result =
7177           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7178       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7179                                              FPT->getExtProtoInfo()));
7180     }
7181 
7182     // C++ [dcl.fct.spec]p3:
7183     //  The inline specifier shall not appear on a block scope function
7184     //  declaration.
7185     if (isInline && !NewFD->isInvalidDecl()) {
7186       if (CurContext->isFunctionOrMethod()) {
7187         // 'inline' is not allowed on block scope function declaration.
7188         Diag(D.getDeclSpec().getInlineSpecLoc(),
7189              diag::err_inline_declaration_block_scope) << Name
7190           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7191       }
7192     }
7193 
7194     // C++ [dcl.fct.spec]p6:
7195     //  The explicit specifier shall be used only in the declaration of a
7196     //  constructor or conversion function within its class definition;
7197     //  see 12.3.1 and 12.3.2.
7198     if (isExplicit && !NewFD->isInvalidDecl()) {
7199       if (!CurContext->isRecord()) {
7200         // 'explicit' was specified outside of the class.
7201         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7202              diag::err_explicit_out_of_class)
7203           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7204       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7205                  !isa<CXXConversionDecl>(NewFD)) {
7206         // 'explicit' was specified on a function that wasn't a constructor
7207         // or conversion function.
7208         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7209              diag::err_explicit_non_ctor_or_conv_function)
7210           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7211       }
7212     }
7213 
7214     if (isConstexpr) {
7215       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7216       // are implicitly inline.
7217       NewFD->setImplicitlyInline();
7218 
7219       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7220       // be either constructors or to return a literal type. Therefore,
7221       // destructors cannot be declared constexpr.
7222       if (isa<CXXDestructorDecl>(NewFD))
7223         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7224     }
7225 
7226     // If __module_private__ was specified, mark the function accordingly.
7227     if (D.getDeclSpec().isModulePrivateSpecified()) {
7228       if (isFunctionTemplateSpecialization) {
7229         SourceLocation ModulePrivateLoc
7230           = D.getDeclSpec().getModulePrivateSpecLoc();
7231         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7232           << 0
7233           << FixItHint::CreateRemoval(ModulePrivateLoc);
7234       } else {
7235         NewFD->setModulePrivate();
7236         if (FunctionTemplate)
7237           FunctionTemplate->setModulePrivate();
7238       }
7239     }
7240 
7241     if (isFriend) {
7242       if (FunctionTemplate) {
7243         FunctionTemplate->setObjectOfFriendDecl();
7244         FunctionTemplate->setAccess(AS_public);
7245       }
7246       NewFD->setObjectOfFriendDecl();
7247       NewFD->setAccess(AS_public);
7248     }
7249 
7250     // If a function is defined as defaulted or deleted, mark it as such now.
7251     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7252     // definition kind to FDK_Definition.
7253     switch (D.getFunctionDefinitionKind()) {
7254       case FDK_Declaration:
7255       case FDK_Definition:
7256         break;
7257 
7258       case FDK_Defaulted:
7259         NewFD->setDefaulted();
7260         break;
7261 
7262       case FDK_Deleted:
7263         NewFD->setDeletedAsWritten();
7264         break;
7265     }
7266 
7267     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7268         D.isFunctionDefinition()) {
7269       // C++ [class.mfct]p2:
7270       //   A member function may be defined (8.4) in its class definition, in
7271       //   which case it is an inline member function (7.1.2)
7272       NewFD->setImplicitlyInline();
7273     }
7274 
7275     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7276         !CurContext->isRecord()) {
7277       // C++ [class.static]p1:
7278       //   A data or function member of a class may be declared static
7279       //   in a class definition, in which case it is a static member of
7280       //   the class.
7281 
7282       // Complain about the 'static' specifier if it's on an out-of-line
7283       // member function definition.
7284       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7285            diag::err_static_out_of_line)
7286         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7287     }
7288 
7289     // C++11 [except.spec]p15:
7290     //   A deallocation function with no exception-specification is treated
7291     //   as if it were specified with noexcept(true).
7292     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7293     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7294          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7295         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7296       NewFD->setType(Context.getFunctionType(
7297           FPT->getReturnType(), FPT->getParamTypes(),
7298           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7299   }
7300 
7301   // Filter out previous declarations that don't match the scope.
7302   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7303                        D.getCXXScopeSpec().isNotEmpty() ||
7304                        isExplicitSpecialization ||
7305                        isFunctionTemplateSpecialization);
7306 
7307   // Handle GNU asm-label extension (encoded as an attribute).
7308   if (Expr *E = (Expr*) D.getAsmLabel()) {
7309     // The parser guarantees this is a string.
7310     StringLiteral *SE = cast<StringLiteral>(E);
7311     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7312                                                 SE->getString(), 0));
7313   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7314     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7315       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7316     if (I != ExtnameUndeclaredIdentifiers.end()) {
7317       NewFD->addAttr(I->second);
7318       ExtnameUndeclaredIdentifiers.erase(I);
7319     }
7320   }
7321 
7322   // Copy the parameter declarations from the declarator D to the function
7323   // declaration NewFD, if they are available.  First scavenge them into Params.
7324   SmallVector<ParmVarDecl*, 16> Params;
7325   if (D.isFunctionDeclarator()) {
7326     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7327 
7328     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7329     // function that takes no arguments, not a function that takes a
7330     // single void argument.
7331     // We let through "const void" here because Sema::GetTypeForDeclarator
7332     // already checks for that case.
7333     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7334       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7335         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7336         assert(Param->getDeclContext() != NewFD && "Was set before ?");
7337         Param->setDeclContext(NewFD);
7338         Params.push_back(Param);
7339 
7340         if (Param->isInvalidDecl())
7341           NewFD->setInvalidDecl();
7342       }
7343     }
7344 
7345   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7346     // When we're declaring a function with a typedef, typeof, etc as in the
7347     // following example, we'll need to synthesize (unnamed)
7348     // parameters for use in the declaration.
7349     //
7350     // @code
7351     // typedef void fn(int);
7352     // fn f;
7353     // @endcode
7354 
7355     // Synthesize a parameter for each argument type.
7356     for (const auto &AI : FT->param_types()) {
7357       ParmVarDecl *Param =
7358           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7359       Param->setScopeInfo(0, Params.size());
7360       Params.push_back(Param);
7361     }
7362   } else {
7363     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7364            "Should not need args for typedef of non-prototype fn");
7365   }
7366 
7367   // Finally, we know we have the right number of parameters, install them.
7368   NewFD->setParams(Params);
7369 
7370   // Find all anonymous symbols defined during the declaration of this function
7371   // and add to NewFD. This lets us track decls such 'enum Y' in:
7372   //
7373   //   void f(enum Y {AA} x) {}
7374   //
7375   // which would otherwise incorrectly end up in the translation unit scope.
7376   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7377   DeclsInPrototypeScope.clear();
7378 
7379   if (D.getDeclSpec().isNoreturnSpecified())
7380     NewFD->addAttr(
7381         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7382                                        Context, 0));
7383 
7384   // Functions returning a variably modified type violate C99 6.7.5.2p2
7385   // because all functions have linkage.
7386   if (!NewFD->isInvalidDecl() &&
7387       NewFD->getReturnType()->isVariablyModifiedType()) {
7388     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7389     NewFD->setInvalidDecl();
7390   }
7391 
7392   // Apply an implicit SectionAttr if #pragma code_seg is active.
7393   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
7394       !NewFD->hasAttr<SectionAttr>()) {
7395     NewFD->addAttr(
7396         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7397                                     CodeSegStack.CurrentValue->getString(),
7398                                     CodeSegStack.CurrentPragmaLocation));
7399     if (UnifySection(CodeSegStack.CurrentValue->getString(),
7400                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
7401                          ASTContext::PSF_Read,
7402                      NewFD))
7403       NewFD->dropAttr<SectionAttr>();
7404   }
7405 
7406   // Handle attributes.
7407   ProcessDeclAttributes(S, NewFD, D);
7408 
7409   QualType RetType = NewFD->getReturnType();
7410   const CXXRecordDecl *Ret = RetType->isRecordType() ?
7411       RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
7412   if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
7413       Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
7414     const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7415     // Attach WarnUnusedResult to functions returning types with that attribute.
7416     // Don't apply the attribute to that type's own non-static member functions
7417     // (to avoid warning on things like assignment operators)
7418     if (!MD || MD->getParent() != Ret)
7419       NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
7420   }
7421 
7422   if (getLangOpts().OpenCL) {
7423     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7424     // type declaration will generate a compilation error.
7425     unsigned AddressSpace = RetType.getAddressSpace();
7426     if (AddressSpace == LangAS::opencl_local ||
7427         AddressSpace == LangAS::opencl_global ||
7428         AddressSpace == LangAS::opencl_constant) {
7429       Diag(NewFD->getLocation(),
7430            diag::err_opencl_return_value_with_address_space);
7431       NewFD->setInvalidDecl();
7432     }
7433   }
7434 
7435   if (!getLangOpts().CPlusPlus) {
7436     // Perform semantic checking on the function declaration.
7437     bool isExplicitSpecialization=false;
7438     if (!NewFD->isInvalidDecl() && NewFD->isMain())
7439       CheckMain(NewFD, D.getDeclSpec());
7440 
7441     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7442       CheckMSVCRTEntryPoint(NewFD);
7443 
7444     if (!NewFD->isInvalidDecl())
7445       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7446                                                   isExplicitSpecialization));
7447     else if (!Previous.empty())
7448       // Recover gracefully from an invalid redeclaration.
7449       D.setRedeclaration(true);
7450     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7451             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7452            "previous declaration set still overloaded");
7453 
7454     // Diagnose no-prototype function declarations with calling conventions that
7455     // don't support variadic calls. Only do this in C and do it after merging
7456     // possibly prototyped redeclarations.
7457     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
7458     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
7459       CallingConv CC = FT->getExtInfo().getCC();
7460       if (!supportsVariadicCall(CC)) {
7461         // Windows system headers sometimes accidentally use stdcall without
7462         // (void) parameters, so we relax this to a warning.
7463         int DiagID =
7464             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
7465         Diag(NewFD->getLocation(), DiagID)
7466             << FunctionType::getNameForCallConv(CC);
7467       }
7468     }
7469   } else {
7470     // C++11 [replacement.functions]p3:
7471     //  The program's definitions shall not be specified as inline.
7472     //
7473     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7474     //
7475     // Suppress the diagnostic if the function is __attribute__((used)), since
7476     // that forces an external definition to be emitted.
7477     if (D.getDeclSpec().isInlineSpecified() &&
7478         NewFD->isReplaceableGlobalAllocationFunction() &&
7479         !NewFD->hasAttr<UsedAttr>())
7480       Diag(D.getDeclSpec().getInlineSpecLoc(),
7481            diag::ext_operator_new_delete_declared_inline)
7482         << NewFD->getDeclName();
7483 
7484     // If the declarator is a template-id, translate the parser's template
7485     // argument list into our AST format.
7486     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7487       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7488       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7489       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7490       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7491                                          TemplateId->NumArgs);
7492       translateTemplateArguments(TemplateArgsPtr,
7493                                  TemplateArgs);
7494 
7495       HasExplicitTemplateArgs = true;
7496 
7497       if (NewFD->isInvalidDecl()) {
7498         HasExplicitTemplateArgs = false;
7499       } else if (FunctionTemplate) {
7500         // Function template with explicit template arguments.
7501         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7502           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7503 
7504         HasExplicitTemplateArgs = false;
7505       } else {
7506         assert((isFunctionTemplateSpecialization ||
7507                 D.getDeclSpec().isFriendSpecified()) &&
7508                "should have a 'template<>' for this decl");
7509         // "friend void foo<>(int);" is an implicit specialization decl.
7510         isFunctionTemplateSpecialization = true;
7511       }
7512     } else if (isFriend && isFunctionTemplateSpecialization) {
7513       // This combination is only possible in a recovery case;  the user
7514       // wrote something like:
7515       //   template <> friend void foo(int);
7516       // which we're recovering from as if the user had written:
7517       //   friend void foo<>(int);
7518       // Go ahead and fake up a template id.
7519       HasExplicitTemplateArgs = true;
7520       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7521       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7522     }
7523 
7524     // If it's a friend (and only if it's a friend), it's possible
7525     // that either the specialized function type or the specialized
7526     // template is dependent, and therefore matching will fail.  In
7527     // this case, don't check the specialization yet.
7528     bool InstantiationDependent = false;
7529     if (isFunctionTemplateSpecialization && isFriend &&
7530         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7531          TemplateSpecializationType::anyDependentTemplateArguments(
7532             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7533             InstantiationDependent))) {
7534       assert(HasExplicitTemplateArgs &&
7535              "friend function specialization without template args");
7536       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7537                                                        Previous))
7538         NewFD->setInvalidDecl();
7539     } else if (isFunctionTemplateSpecialization) {
7540       if (CurContext->isDependentContext() && CurContext->isRecord()
7541           && !isFriend) {
7542         isDependentClassScopeExplicitSpecialization = true;
7543         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7544           diag::ext_function_specialization_in_class :
7545           diag::err_function_specialization_in_class)
7546           << NewFD->getDeclName();
7547       } else if (CheckFunctionTemplateSpecialization(NewFD,
7548                                   (HasExplicitTemplateArgs ? &TemplateArgs
7549                                                            : nullptr),
7550                                                      Previous))
7551         NewFD->setInvalidDecl();
7552 
7553       // C++ [dcl.stc]p1:
7554       //   A storage-class-specifier shall not be specified in an explicit
7555       //   specialization (14.7.3)
7556       FunctionTemplateSpecializationInfo *Info =
7557           NewFD->getTemplateSpecializationInfo();
7558       if (Info && SC != SC_None) {
7559         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7560           Diag(NewFD->getLocation(),
7561                diag::err_explicit_specialization_inconsistent_storage_class)
7562             << SC
7563             << FixItHint::CreateRemoval(
7564                                       D.getDeclSpec().getStorageClassSpecLoc());
7565 
7566         else
7567           Diag(NewFD->getLocation(),
7568                diag::ext_explicit_specialization_storage_class)
7569             << FixItHint::CreateRemoval(
7570                                       D.getDeclSpec().getStorageClassSpecLoc());
7571       }
7572 
7573     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7574       if (CheckMemberSpecialization(NewFD, Previous))
7575           NewFD->setInvalidDecl();
7576     }
7577 
7578     // Perform semantic checking on the function declaration.
7579     if (!isDependentClassScopeExplicitSpecialization) {
7580       if (!NewFD->isInvalidDecl() && NewFD->isMain())
7581         CheckMain(NewFD, D.getDeclSpec());
7582 
7583       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7584         CheckMSVCRTEntryPoint(NewFD);
7585 
7586       if (!NewFD->isInvalidDecl())
7587         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7588                                                     isExplicitSpecialization));
7589       else if (!Previous.empty())
7590         // Recover gracefully from an invalid redeclaration.
7591         D.setRedeclaration(true);
7592     }
7593 
7594     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7595             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7596            "previous declaration set still overloaded");
7597 
7598     NamedDecl *PrincipalDecl = (FunctionTemplate
7599                                 ? cast<NamedDecl>(FunctionTemplate)
7600                                 : NewFD);
7601 
7602     if (isFriend && D.isRedeclaration()) {
7603       AccessSpecifier Access = AS_public;
7604       if (!NewFD->isInvalidDecl())
7605         Access = NewFD->getPreviousDecl()->getAccess();
7606 
7607       NewFD->setAccess(Access);
7608       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7609     }
7610 
7611     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7612         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7613       PrincipalDecl->setNonMemberOperator();
7614 
7615     // If we have a function template, check the template parameter
7616     // list. This will check and merge default template arguments.
7617     if (FunctionTemplate) {
7618       FunctionTemplateDecl *PrevTemplate =
7619                                      FunctionTemplate->getPreviousDecl();
7620       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7621                        PrevTemplate ? PrevTemplate->getTemplateParameters()
7622                                     : nullptr,
7623                             D.getDeclSpec().isFriendSpecified()
7624                               ? (D.isFunctionDefinition()
7625                                    ? TPC_FriendFunctionTemplateDefinition
7626                                    : TPC_FriendFunctionTemplate)
7627                               : (D.getCXXScopeSpec().isSet() &&
7628                                  DC && DC->isRecord() &&
7629                                  DC->isDependentContext())
7630                                   ? TPC_ClassTemplateMember
7631                                   : TPC_FunctionTemplate);
7632     }
7633 
7634     if (NewFD->isInvalidDecl()) {
7635       // Ignore all the rest of this.
7636     } else if (!D.isRedeclaration()) {
7637       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7638                                        AddToScope };
7639       // Fake up an access specifier if it's supposed to be a class member.
7640       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7641         NewFD->setAccess(AS_public);
7642 
7643       // Qualified decls generally require a previous declaration.
7644       if (D.getCXXScopeSpec().isSet()) {
7645         // ...with the major exception of templated-scope or
7646         // dependent-scope friend declarations.
7647 
7648         // TODO: we currently also suppress this check in dependent
7649         // contexts because (1) the parameter depth will be off when
7650         // matching friend templates and (2) we might actually be
7651         // selecting a friend based on a dependent factor.  But there
7652         // are situations where these conditions don't apply and we
7653         // can actually do this check immediately.
7654         if (isFriend &&
7655             (TemplateParamLists.size() ||
7656              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7657              CurContext->isDependentContext())) {
7658           // ignore these
7659         } else {
7660           // The user tried to provide an out-of-line definition for a
7661           // function that is a member of a class or namespace, but there
7662           // was no such member function declared (C++ [class.mfct]p2,
7663           // C++ [namespace.memdef]p2). For example:
7664           //
7665           // class X {
7666           //   void f() const;
7667           // };
7668           //
7669           // void X::f() { } // ill-formed
7670           //
7671           // Complain about this problem, and attempt to suggest close
7672           // matches (e.g., those that differ only in cv-qualifiers and
7673           // whether the parameter types are references).
7674 
7675           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7676                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
7677             AddToScope = ExtraArgs.AddToScope;
7678             return Result;
7679           }
7680         }
7681 
7682         // Unqualified local friend declarations are required to resolve
7683         // to something.
7684       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7685         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7686                 *this, Previous, NewFD, ExtraArgs, true, S)) {
7687           AddToScope = ExtraArgs.AddToScope;
7688           return Result;
7689         }
7690       }
7691 
7692     } else if (!D.isFunctionDefinition() &&
7693                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
7694                !isFriend && !isFunctionTemplateSpecialization &&
7695                !isExplicitSpecialization) {
7696       // An out-of-line member function declaration must also be a
7697       // definition (C++ [class.mfct]p2).
7698       // Note that this is not the case for explicit specializations of
7699       // function templates or member functions of class templates, per
7700       // C++ [temp.expl.spec]p2. We also allow these declarations as an
7701       // extension for compatibility with old SWIG code which likes to
7702       // generate them.
7703       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7704         << D.getCXXScopeSpec().getRange();
7705     }
7706   }
7707 
7708   ProcessPragmaWeak(S, NewFD);
7709   checkAttributesAfterMerging(*this, *NewFD);
7710 
7711   AddKnownFunctionAttributes(NewFD);
7712 
7713   if (NewFD->hasAttr<OverloadableAttr>() &&
7714       !NewFD->getType()->getAs<FunctionProtoType>()) {
7715     Diag(NewFD->getLocation(),
7716          diag::err_attribute_overloadable_no_prototype)
7717       << NewFD;
7718 
7719     // Turn this into a variadic function with no parameters.
7720     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7721     FunctionProtoType::ExtProtoInfo EPI(
7722         Context.getDefaultCallingConvention(true, false));
7723     EPI.Variadic = true;
7724     EPI.ExtInfo = FT->getExtInfo();
7725 
7726     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
7727     NewFD->setType(R);
7728   }
7729 
7730   // If there's a #pragma GCC visibility in scope, and this isn't a class
7731   // member, set the visibility of this function.
7732   if (!DC->isRecord() && NewFD->isExternallyVisible())
7733     AddPushedVisibilityAttribute(NewFD);
7734 
7735   // If there's a #pragma clang arc_cf_code_audited in scope, consider
7736   // marking the function.
7737   AddCFAuditedAttribute(NewFD);
7738 
7739   // If this is a function definition, check if we have to apply optnone due to
7740   // a pragma.
7741   if(D.isFunctionDefinition())
7742     AddRangeBasedOptnone(NewFD);
7743 
7744   // If this is the first declaration of an extern C variable, update
7745   // the map of such variables.
7746   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
7747       isIncompleteDeclExternC(*this, NewFD))
7748     RegisterLocallyScopedExternCDecl(NewFD, S);
7749 
7750   // Set this FunctionDecl's range up to the right paren.
7751   NewFD->setRangeEnd(D.getSourceRange().getEnd());
7752 
7753   if (D.isRedeclaration() && !Previous.empty()) {
7754     checkDLLAttributeRedeclaration(
7755         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
7756         isExplicitSpecialization || isFunctionTemplateSpecialization);
7757   }
7758 
7759   if (getLangOpts().CPlusPlus) {
7760     if (FunctionTemplate) {
7761       if (NewFD->isInvalidDecl())
7762         FunctionTemplate->setInvalidDecl();
7763       return FunctionTemplate;
7764     }
7765   }
7766 
7767   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
7768     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7769     if ((getLangOpts().OpenCLVersion >= 120)
7770         && (SC == SC_Static)) {
7771       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7772       D.setInvalidType();
7773     }
7774 
7775     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7776     if (!NewFD->getReturnType()->isVoidType()) {
7777       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
7778       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
7779           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
7780                                 : FixItHint());
7781       D.setInvalidType();
7782     }
7783 
7784     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
7785     for (auto Param : NewFD->params())
7786       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
7787   }
7788 
7789   MarkUnusedFileScopedDecl(NewFD);
7790 
7791   if (getLangOpts().CUDA)
7792     if (IdentifierInfo *II = NewFD->getIdentifier())
7793       if (!NewFD->isInvalidDecl() &&
7794           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7795         if (II->isStr("cudaConfigureCall")) {
7796           if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
7797             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7798 
7799           Context.setcudaConfigureCallDecl(NewFD);
7800         }
7801       }
7802 
7803   // Here we have an function template explicit specialization at class scope.
7804   // The actually specialization will be postponed to template instatiation
7805   // time via the ClassScopeFunctionSpecializationDecl node.
7806   if (isDependentClassScopeExplicitSpecialization) {
7807     ClassScopeFunctionSpecializationDecl *NewSpec =
7808                          ClassScopeFunctionSpecializationDecl::Create(
7809                                 Context, CurContext, SourceLocation(),
7810                                 cast<CXXMethodDecl>(NewFD),
7811                                 HasExplicitTemplateArgs, TemplateArgs);
7812     CurContext->addDecl(NewSpec);
7813     AddToScope = false;
7814   }
7815 
7816   return NewFD;
7817 }
7818 
7819 /// \brief Perform semantic checking of a new function declaration.
7820 ///
7821 /// Performs semantic analysis of the new function declaration
7822 /// NewFD. This routine performs all semantic checking that does not
7823 /// require the actual declarator involved in the declaration, and is
7824 /// used both for the declaration of functions as they are parsed
7825 /// (called via ActOnDeclarator) and for the declaration of functions
7826 /// that have been instantiated via C++ template instantiation (called
7827 /// via InstantiateDecl).
7828 ///
7829 /// \param IsExplicitSpecialization whether this new function declaration is
7830 /// an explicit specialization of the previous declaration.
7831 ///
7832 /// This sets NewFD->isInvalidDecl() to true if there was an error.
7833 ///
7834 /// \returns true if the function declaration is a redeclaration.
7835 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
7836                                     LookupResult &Previous,
7837                                     bool IsExplicitSpecialization) {
7838   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7839          "Variably modified return types are not handled here");
7840 
7841   // Determine whether the type of this function should be merged with
7842   // a previous visible declaration. This never happens for functions in C++,
7843   // and always happens in C if the previous declaration was visible.
7844   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7845                                !Previous.isShadowed();
7846 
7847   // Filter out any non-conflicting previous declarations.
7848   filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7849 
7850   bool Redeclaration = false;
7851   NamedDecl *OldDecl = nullptr;
7852 
7853   // Merge or overload the declaration with an existing declaration of
7854   // the same name, if appropriate.
7855   if (!Previous.empty()) {
7856     // Determine whether NewFD is an overload of PrevDecl or
7857     // a declaration that requires merging. If it's an overload,
7858     // there's no more work to do here; we'll just add the new
7859     // function to the scope.
7860     if (!AllowOverloadingOfFunction(Previous, Context)) {
7861       NamedDecl *Candidate = Previous.getFoundDecl();
7862       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7863         Redeclaration = true;
7864         OldDecl = Candidate;
7865       }
7866     } else {
7867       switch (CheckOverload(S, NewFD, Previous, OldDecl,
7868                             /*NewIsUsingDecl*/ false)) {
7869       case Ovl_Match:
7870         Redeclaration = true;
7871         break;
7872 
7873       case Ovl_NonFunction:
7874         Redeclaration = true;
7875         break;
7876 
7877       case Ovl_Overload:
7878         Redeclaration = false;
7879         break;
7880       }
7881 
7882       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7883         // If a function name is overloadable in C, then every function
7884         // with that name must be marked "overloadable".
7885         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7886           << Redeclaration << NewFD;
7887         NamedDecl *OverloadedDecl = nullptr;
7888         if (Redeclaration)
7889           OverloadedDecl = OldDecl;
7890         else if (!Previous.empty())
7891           OverloadedDecl = Previous.getRepresentativeDecl();
7892         if (OverloadedDecl)
7893           Diag(OverloadedDecl->getLocation(),
7894                diag::note_attribute_overloadable_prev_overload);
7895         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7896       }
7897     }
7898   }
7899 
7900   // Check for a previous extern "C" declaration with this name.
7901   if (!Redeclaration &&
7902       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7903     filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7904     if (!Previous.empty()) {
7905       // This is an extern "C" declaration with the same name as a previous
7906       // declaration, and thus redeclares that entity...
7907       Redeclaration = true;
7908       OldDecl = Previous.getFoundDecl();
7909       MergeTypeWithPrevious = false;
7910 
7911       // ... except in the presence of __attribute__((overloadable)).
7912       if (OldDecl->hasAttr<OverloadableAttr>()) {
7913         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7914           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7915             << Redeclaration << NewFD;
7916           Diag(Previous.getFoundDecl()->getLocation(),
7917                diag::note_attribute_overloadable_prev_overload);
7918           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7919         }
7920         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7921           Redeclaration = false;
7922           OldDecl = nullptr;
7923         }
7924       }
7925     }
7926   }
7927 
7928   // C++11 [dcl.constexpr]p8:
7929   //   A constexpr specifier for a non-static member function that is not
7930   //   a constructor declares that member function to be const.
7931   //
7932   // This needs to be delayed until we know whether this is an out-of-line
7933   // definition of a static member function.
7934   //
7935   // This rule is not present in C++1y, so we produce a backwards
7936   // compatibility warning whenever it happens in C++11.
7937   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7938   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
7939       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
7940       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7941     CXXMethodDecl *OldMD = nullptr;
7942     if (OldDecl)
7943       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
7944     if (!OldMD || !OldMD->isStatic()) {
7945       const FunctionProtoType *FPT =
7946         MD->getType()->castAs<FunctionProtoType>();
7947       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7948       EPI.TypeQuals |= Qualifiers::Const;
7949       MD->setType(Context.getFunctionType(FPT->getReturnType(),
7950                                           FPT->getParamTypes(), EPI));
7951 
7952       // Warn that we did this, if we're not performing template instantiation.
7953       // In that case, we'll have warned already when the template was defined.
7954       if (ActiveTemplateInstantiations.empty()) {
7955         SourceLocation AddConstLoc;
7956         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7957                 .IgnoreParens().getAs<FunctionTypeLoc>())
7958           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
7959 
7960         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
7961           << FixItHint::CreateInsertion(AddConstLoc, " const");
7962       }
7963     }
7964   }
7965 
7966   if (Redeclaration) {
7967     // NewFD and OldDecl represent declarations that need to be
7968     // merged.
7969     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
7970       NewFD->setInvalidDecl();
7971       return Redeclaration;
7972     }
7973 
7974     Previous.clear();
7975     Previous.addDecl(OldDecl);
7976 
7977     if (FunctionTemplateDecl *OldTemplateDecl
7978                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7979       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7980       FunctionTemplateDecl *NewTemplateDecl
7981         = NewFD->getDescribedFunctionTemplate();
7982       assert(NewTemplateDecl && "Template/non-template mismatch");
7983       if (CXXMethodDecl *Method
7984             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7985         Method->setAccess(OldTemplateDecl->getAccess());
7986         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
7987       }
7988 
7989       // If this is an explicit specialization of a member that is a function
7990       // template, mark it as a member specialization.
7991       if (IsExplicitSpecialization &&
7992           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7993         NewTemplateDecl->setMemberSpecialization();
7994         assert(OldTemplateDecl->isMemberSpecialization());
7995       }
7996 
7997     } else {
7998       // This needs to happen first so that 'inline' propagates.
7999       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8000 
8001       if (isa<CXXMethodDecl>(NewFD))
8002         NewFD->setAccess(OldDecl->getAccess());
8003     }
8004   }
8005 
8006   // Semantic checking for this function declaration (in isolation).
8007 
8008   if (getLangOpts().CPlusPlus) {
8009     // C++-specific checks.
8010     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8011       CheckConstructor(Constructor);
8012     } else if (CXXDestructorDecl *Destructor =
8013                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8014       CXXRecordDecl *Record = Destructor->getParent();
8015       QualType ClassType = Context.getTypeDeclType(Record);
8016 
8017       // FIXME: Shouldn't we be able to perform this check even when the class
8018       // type is dependent? Both gcc and edg can handle that.
8019       if (!ClassType->isDependentType()) {
8020         DeclarationName Name
8021           = Context.DeclarationNames.getCXXDestructorName(
8022                                         Context.getCanonicalType(ClassType));
8023         if (NewFD->getDeclName() != Name) {
8024           Diag(NewFD->getLocation(), diag::err_destructor_name);
8025           NewFD->setInvalidDecl();
8026           return Redeclaration;
8027         }
8028       }
8029     } else if (CXXConversionDecl *Conversion
8030                = dyn_cast<CXXConversionDecl>(NewFD)) {
8031       ActOnConversionDeclarator(Conversion);
8032     }
8033 
8034     // Find any virtual functions that this function overrides.
8035     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8036       if (!Method->isFunctionTemplateSpecialization() &&
8037           !Method->getDescribedFunctionTemplate() &&
8038           Method->isCanonicalDecl()) {
8039         if (AddOverriddenMethods(Method->getParent(), Method)) {
8040           // If the function was marked as "static", we have a problem.
8041           if (NewFD->getStorageClass() == SC_Static) {
8042             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8043           }
8044         }
8045       }
8046 
8047       if (Method->isStatic())
8048         checkThisInStaticMemberFunctionType(Method);
8049     }
8050 
8051     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8052     if (NewFD->isOverloadedOperator() &&
8053         CheckOverloadedOperatorDeclaration(NewFD)) {
8054       NewFD->setInvalidDecl();
8055       return Redeclaration;
8056     }
8057 
8058     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8059     if (NewFD->getLiteralIdentifier() &&
8060         CheckLiteralOperatorDeclaration(NewFD)) {
8061       NewFD->setInvalidDecl();
8062       return Redeclaration;
8063     }
8064 
8065     // In C++, check default arguments now that we have merged decls. Unless
8066     // the lexical context is the class, because in this case this is done
8067     // during delayed parsing anyway.
8068     if (!CurContext->isRecord())
8069       CheckCXXDefaultArguments(NewFD);
8070 
8071     // If this function declares a builtin function, check the type of this
8072     // declaration against the expected type for the builtin.
8073     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8074       ASTContext::GetBuiltinTypeError Error;
8075       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8076       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8077       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8078         // The type of this function differs from the type of the builtin,
8079         // so forget about the builtin entirely.
8080         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
8081       }
8082     }
8083 
8084     // If this function is declared as being extern "C", then check to see if
8085     // the function returns a UDT (class, struct, or union type) that is not C
8086     // compatible, and if it does, warn the user.
8087     // But, issue any diagnostic on the first declaration only.
8088     if (Previous.empty() && NewFD->isExternC()) {
8089       QualType R = NewFD->getReturnType();
8090       if (R->isIncompleteType() && !R->isVoidType())
8091         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8092             << NewFD << R;
8093       else if (!R.isPODType(Context) && !R->isVoidType() &&
8094                !R->isObjCObjectPointerType())
8095         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8096     }
8097   }
8098   return Redeclaration;
8099 }
8100 
8101 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8102   // C++11 [basic.start.main]p3:
8103   //   A program that [...] declares main to be inline, static or
8104   //   constexpr is ill-formed.
8105   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8106   //   appear in a declaration of main.
8107   // static main is not an error under C99, but we should warn about it.
8108   // We accept _Noreturn main as an extension.
8109   if (FD->getStorageClass() == SC_Static)
8110     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8111          ? diag::err_static_main : diag::warn_static_main)
8112       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8113   if (FD->isInlineSpecified())
8114     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8115       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8116   if (DS.isNoreturnSpecified()) {
8117     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8118     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8119     Diag(NoreturnLoc, diag::ext_noreturn_main);
8120     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8121       << FixItHint::CreateRemoval(NoreturnRange);
8122   }
8123   if (FD->isConstexpr()) {
8124     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8125       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8126     FD->setConstexpr(false);
8127   }
8128 
8129   if (getLangOpts().OpenCL) {
8130     Diag(FD->getLocation(), diag::err_opencl_no_main)
8131         << FD->hasAttr<OpenCLKernelAttr>();
8132     FD->setInvalidDecl();
8133     return;
8134   }
8135 
8136   QualType T = FD->getType();
8137   assert(T->isFunctionType() && "function decl is not of function type");
8138   const FunctionType* FT = T->castAs<FunctionType>();
8139 
8140   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8141     // In C with GNU extensions we allow main() to have non-integer return
8142     // type, but we should warn about the extension, and we disable the
8143     // implicit-return-zero rule.
8144 
8145     // GCC in C mode accepts qualified 'int'.
8146     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8147       FD->setHasImplicitReturnZero(true);
8148     else {
8149       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8150       SourceRange RTRange = FD->getReturnTypeSourceRange();
8151       if (RTRange.isValid())
8152         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8153             << FixItHint::CreateReplacement(RTRange, "int");
8154     }
8155   } else {
8156     // In C and C++, main magically returns 0 if you fall off the end;
8157     // set the flag which tells us that.
8158     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8159 
8160     // All the standards say that main() should return 'int'.
8161     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8162       FD->setHasImplicitReturnZero(true);
8163     else {
8164       // Otherwise, this is just a flat-out error.
8165       SourceRange RTRange = FD->getReturnTypeSourceRange();
8166       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8167           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8168                                 : FixItHint());
8169       FD->setInvalidDecl(true);
8170     }
8171   }
8172 
8173   // Treat protoless main() as nullary.
8174   if (isa<FunctionNoProtoType>(FT)) return;
8175 
8176   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8177   unsigned nparams = FTP->getNumParams();
8178   assert(FD->getNumParams() == nparams);
8179 
8180   bool HasExtraParameters = (nparams > 3);
8181 
8182   // Darwin passes an undocumented fourth argument of type char**.  If
8183   // other platforms start sprouting these, the logic below will start
8184   // getting shifty.
8185   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8186     HasExtraParameters = false;
8187 
8188   if (HasExtraParameters) {
8189     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8190     FD->setInvalidDecl(true);
8191     nparams = 3;
8192   }
8193 
8194   // FIXME: a lot of the following diagnostics would be improved
8195   // if we had some location information about types.
8196 
8197   QualType CharPP =
8198     Context.getPointerType(Context.getPointerType(Context.CharTy));
8199   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8200 
8201   for (unsigned i = 0; i < nparams; ++i) {
8202     QualType AT = FTP->getParamType(i);
8203 
8204     bool mismatch = true;
8205 
8206     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8207       mismatch = false;
8208     else if (Expected[i] == CharPP) {
8209       // As an extension, the following forms are okay:
8210       //   char const **
8211       //   char const * const *
8212       //   char * const *
8213 
8214       QualifierCollector qs;
8215       const PointerType* PT;
8216       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8217           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8218           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8219                               Context.CharTy)) {
8220         qs.removeConst();
8221         mismatch = !qs.empty();
8222       }
8223     }
8224 
8225     if (mismatch) {
8226       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8227       // TODO: suggest replacing given type with expected type
8228       FD->setInvalidDecl(true);
8229     }
8230   }
8231 
8232   if (nparams == 1 && !FD->isInvalidDecl()) {
8233     Diag(FD->getLocation(), diag::warn_main_one_arg);
8234   }
8235 
8236   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8237     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8238     FD->setInvalidDecl();
8239   }
8240 }
8241 
8242 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8243   QualType T = FD->getType();
8244   assert(T->isFunctionType() && "function decl is not of function type");
8245   const FunctionType *FT = T->castAs<FunctionType>();
8246 
8247   // Set an implicit return of 'zero' if the function can return some integral,
8248   // enumeration, pointer or nullptr type.
8249   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8250       FT->getReturnType()->isAnyPointerType() ||
8251       FT->getReturnType()->isNullPtrType())
8252     // DllMain is exempt because a return value of zero means it failed.
8253     if (FD->getName() != "DllMain")
8254       FD->setHasImplicitReturnZero(true);
8255 
8256   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8257     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8258     FD->setInvalidDecl();
8259   }
8260 }
8261 
8262 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8263   // FIXME: Need strict checking.  In C89, we need to check for
8264   // any assignment, increment, decrement, function-calls, or
8265   // commas outside of a sizeof.  In C99, it's the same list,
8266   // except that the aforementioned are allowed in unevaluated
8267   // expressions.  Everything else falls under the
8268   // "may accept other forms of constant expressions" exception.
8269   // (We never end up here for C++, so the constant expression
8270   // rules there don't matter.)
8271   const Expr *Culprit;
8272   if (Init->isConstantInitializer(Context, false, &Culprit))
8273     return false;
8274   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8275     << Culprit->getSourceRange();
8276   return true;
8277 }
8278 
8279 namespace {
8280   // Visits an initialization expression to see if OrigDecl is evaluated in
8281   // its own initialization and throws a warning if it does.
8282   class SelfReferenceChecker
8283       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8284     Sema &S;
8285     Decl *OrigDecl;
8286     bool isRecordType;
8287     bool isPODType;
8288     bool isReferenceType;
8289 
8290     bool isInitList;
8291     llvm::SmallVector<unsigned, 4> InitFieldIndex;
8292   public:
8293     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8294 
8295     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8296                                                     S(S), OrigDecl(OrigDecl) {
8297       isPODType = false;
8298       isRecordType = false;
8299       isReferenceType = false;
8300       isInitList = false;
8301       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8302         isPODType = VD->getType().isPODType(S.Context);
8303         isRecordType = VD->getType()->isRecordType();
8304         isReferenceType = VD->getType()->isReferenceType();
8305       }
8306     }
8307 
8308     // For most expressions, just call the visitor.  For initializer lists,
8309     // track the index of the field being initialized since fields are
8310     // initialized in order allowing use of previously initialized fields.
8311     void CheckExpr(Expr *E) {
8312       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8313       if (!InitList) {
8314         Visit(E);
8315         return;
8316       }
8317 
8318       // Track and increment the index here.
8319       isInitList = true;
8320       InitFieldIndex.push_back(0);
8321       for (auto Child : InitList->children()) {
8322         CheckExpr(cast<Expr>(Child));
8323         ++InitFieldIndex.back();
8324       }
8325       InitFieldIndex.pop_back();
8326     }
8327 
8328     // Returns true if MemberExpr is checked and no futher checking is needed.
8329     // Returns false if additional checking is required.
8330     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8331       llvm::SmallVector<FieldDecl*, 4> Fields;
8332       Expr *Base = E;
8333       bool ReferenceField = false;
8334 
8335       // Get the field memebers used.
8336       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8337         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8338         if (!FD)
8339           return false;
8340         Fields.push_back(FD);
8341         if (FD->getType()->isReferenceType())
8342           ReferenceField = true;
8343         Base = ME->getBase()->IgnoreParenImpCasts();
8344       }
8345 
8346       // Keep checking only if the base Decl is the same.
8347       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8348       if (!DRE || DRE->getDecl() != OrigDecl)
8349         return false;
8350 
8351       // A reference field can be bound to an unininitialized field.
8352       if (CheckReference && !ReferenceField)
8353         return true;
8354 
8355       // Convert FieldDecls to their index number.
8356       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8357       for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) {
8358         UsedFieldIndex.push_back((*I)->getFieldIndex());
8359       }
8360 
8361       // See if a warning is needed by checking the first difference in index
8362       // numbers.  If field being used has index less than the field being
8363       // initialized, then the use is safe.
8364       for (auto UsedIter = UsedFieldIndex.begin(),
8365                 UsedEnd = UsedFieldIndex.end(),
8366                 OrigIter = InitFieldIndex.begin(),
8367                 OrigEnd = InitFieldIndex.end();
8368            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8369         if (*UsedIter < *OrigIter)
8370           return true;
8371         if (*UsedIter > *OrigIter)
8372           break;
8373       }
8374 
8375       // TODO: Add a different warning which will print the field names.
8376       HandleDeclRefExpr(DRE);
8377       return true;
8378     }
8379 
8380     // For most expressions, the cast is directly above the DeclRefExpr.
8381     // For conditional operators, the cast can be outside the conditional
8382     // operator if both expressions are DeclRefExpr's.
8383     void HandleValue(Expr *E) {
8384       E = E->IgnoreParens();
8385       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8386         HandleDeclRefExpr(DRE);
8387         return;
8388       }
8389 
8390       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8391         Visit(CO->getCond());
8392         HandleValue(CO->getTrueExpr());
8393         HandleValue(CO->getFalseExpr());
8394         return;
8395       }
8396 
8397       if (BinaryConditionalOperator *BCO =
8398               dyn_cast<BinaryConditionalOperator>(E)) {
8399         Visit(BCO->getCond());
8400         HandleValue(BCO->getFalseExpr());
8401         return;
8402       }
8403 
8404       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8405         HandleValue(OVE->getSourceExpr());
8406         return;
8407       }
8408 
8409       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8410         if (BO->getOpcode() == BO_Comma) {
8411           Visit(BO->getLHS());
8412           HandleValue(BO->getRHS());
8413           return;
8414         }
8415       }
8416 
8417       if (isa<MemberExpr>(E)) {
8418         if (isInitList) {
8419           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
8420                                       false /*CheckReference*/))
8421             return;
8422         }
8423 
8424         Expr *Base = E->IgnoreParenImpCasts();
8425         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8426           // Check for static member variables and don't warn on them.
8427           if (!isa<FieldDecl>(ME->getMemberDecl()))
8428             return;
8429           Base = ME->getBase()->IgnoreParenImpCasts();
8430         }
8431         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8432           HandleDeclRefExpr(DRE);
8433         return;
8434       }
8435 
8436       Visit(E);
8437     }
8438 
8439     // Reference types not handled in HandleValue are handled here since all
8440     // uses of references are bad, not just r-value uses.
8441     void VisitDeclRefExpr(DeclRefExpr *E) {
8442       if (isReferenceType)
8443         HandleDeclRefExpr(E);
8444     }
8445 
8446     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8447       if (E->getCastKind() == CK_LValueToRValue) {
8448         HandleValue(E->getSubExpr());
8449         return;
8450       }
8451 
8452       Inherited::VisitImplicitCastExpr(E);
8453     }
8454 
8455     void VisitMemberExpr(MemberExpr *E) {
8456       if (isInitList) {
8457         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
8458           return;
8459       }
8460 
8461       // Don't warn on arrays since they can be treated as pointers.
8462       if (E->getType()->canDecayToPointerType()) return;
8463 
8464       // Warn when a non-static method call is followed by non-static member
8465       // field accesses, which is followed by a DeclRefExpr.
8466       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8467       bool Warn = (MD && !MD->isStatic());
8468       Expr *Base = E->getBase()->IgnoreParenImpCasts();
8469       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8470         if (!isa<FieldDecl>(ME->getMemberDecl()))
8471           Warn = false;
8472         Base = ME->getBase()->IgnoreParenImpCasts();
8473       }
8474 
8475       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8476         if (Warn)
8477           HandleDeclRefExpr(DRE);
8478         return;
8479       }
8480 
8481       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8482       // Visit that expression.
8483       Visit(Base);
8484     }
8485 
8486     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8487       Expr *Callee = E->getCallee();
8488 
8489       if (isa<UnresolvedLookupExpr>(Callee))
8490         return Inherited::VisitCXXOperatorCallExpr(E);
8491 
8492       Visit(Callee);
8493       for (auto Arg: E->arguments())
8494         HandleValue(Arg->IgnoreParenImpCasts());
8495     }
8496 
8497     void VisitUnaryOperator(UnaryOperator *E) {
8498       // For POD record types, addresses of its own members are well-defined.
8499       if (E->getOpcode() == UO_AddrOf && isRecordType &&
8500           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8501         if (!isPODType)
8502           HandleValue(E->getSubExpr());
8503         return;
8504       }
8505 
8506       if (E->isIncrementDecrementOp()) {
8507         HandleValue(E->getSubExpr());
8508         return;
8509       }
8510 
8511       Inherited::VisitUnaryOperator(E);
8512     }
8513 
8514     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8515 
8516     void VisitCXXConstructExpr(CXXConstructExpr *E) {
8517       if (E->getConstructor()->isCopyConstructor()) {
8518         Expr *ArgExpr = E->getArg(0);
8519         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
8520           if (ILE->getNumInits() == 1)
8521             ArgExpr = ILE->getInit(0);
8522         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8523           if (ICE->getCastKind() == CK_NoOp)
8524             ArgExpr = ICE->getSubExpr();
8525         HandleValue(ArgExpr);
8526         return;
8527       }
8528       Inherited::VisitCXXConstructExpr(E);
8529     }
8530 
8531     void VisitCallExpr(CallExpr *E) {
8532       // Treat std::move as a use.
8533       if (E->getNumArgs() == 1) {
8534         if (FunctionDecl *FD = E->getDirectCallee()) {
8535           if (FD->isInStdNamespace() && FD->getIdentifier() &&
8536               FD->getIdentifier()->isStr("move")) {
8537             HandleValue(E->getArg(0));
8538             return;
8539           }
8540         }
8541       }
8542 
8543       Inherited::VisitCallExpr(E);
8544     }
8545 
8546     void VisitBinaryOperator(BinaryOperator *E) {
8547       if (E->isCompoundAssignmentOp()) {
8548         HandleValue(E->getLHS());
8549         Visit(E->getRHS());
8550         return;
8551       }
8552 
8553       Inherited::VisitBinaryOperator(E);
8554     }
8555 
8556     // A custom visitor for BinaryConditionalOperator is needed because the
8557     // regular visitor would check the condition and true expression separately
8558     // but both point to the same place giving duplicate diagnostics.
8559     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
8560       Visit(E->getCond());
8561       Visit(E->getFalseExpr());
8562     }
8563 
8564     void HandleDeclRefExpr(DeclRefExpr *DRE) {
8565       Decl* ReferenceDecl = DRE->getDecl();
8566       if (OrigDecl != ReferenceDecl) return;
8567       unsigned diag;
8568       if (isReferenceType) {
8569         diag = diag::warn_uninit_self_reference_in_reference_init;
8570       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8571         diag = diag::warn_static_self_reference_in_init;
8572       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
8573                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
8574                  DRE->getDecl()->getType()->isRecordType()) {
8575         diag = diag::warn_uninit_self_reference_in_init;
8576       } else {
8577         // Local variables will be handled by the CFG analysis.
8578         return;
8579       }
8580 
8581       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
8582                             S.PDiag(diag)
8583                               << DRE->getNameInfo().getName()
8584                               << OrigDecl->getLocation()
8585                               << DRE->getSourceRange());
8586     }
8587   };
8588 
8589   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8590   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8591                                  bool DirectInit) {
8592     // Parameters arguments are occassionially constructed with itself,
8593     // for instance, in recursive functions.  Skip them.
8594     if (isa<ParmVarDecl>(OrigDecl))
8595       return;
8596 
8597     E = E->IgnoreParens();
8598 
8599     // Skip checking T a = a where T is not a record or reference type.
8600     // Doing so is a way to silence uninitialized warnings.
8601     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8602       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8603         if (ICE->getCastKind() == CK_LValueToRValue)
8604           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8605             if (DRE->getDecl() == OrigDecl)
8606               return;
8607 
8608     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
8609   }
8610 }
8611 
8612 /// AddInitializerToDecl - Adds the initializer Init to the
8613 /// declaration dcl. If DirectInit is true, this is C++ direct
8614 /// initialization rather than copy initialization.
8615 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8616                                 bool DirectInit, bool TypeMayContainAuto) {
8617   // If there is no declaration, there was an error parsing it.  Just ignore
8618   // the initializer.
8619   if (!RealDecl || RealDecl->isInvalidDecl()) {
8620     CorrectDelayedTyposInExpr(Init);
8621     return;
8622   }
8623 
8624   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8625     // With declarators parsed the way they are, the parser cannot
8626     // distinguish between a normal initializer and a pure-specifier.
8627     // Thus this grotesque test.
8628     IntegerLiteral *IL;
8629     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
8630         Context.getCanonicalType(IL->getType()) == Context.IntTy)
8631       CheckPureMethod(Method, Init->getSourceRange());
8632     else {
8633       Diag(Method->getLocation(), diag::err_member_function_initialization)
8634         << Method->getDeclName() << Init->getSourceRange();
8635       Method->setInvalidDecl();
8636     }
8637     return;
8638   }
8639 
8640   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8641   if (!VDecl) {
8642     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8643     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8644     RealDecl->setInvalidDecl();
8645     return;
8646   }
8647   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8648 
8649   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8650   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
8651     Expr *DeduceInit = Init;
8652     // Initializer could be a C++ direct-initializer. Deduction only works if it
8653     // contains exactly one expression.
8654     if (CXXDirectInit) {
8655       if (CXXDirectInit->getNumExprs() == 0) {
8656         // It isn't possible to write this directly, but it is possible to
8657         // end up in this situation with "auto x(some_pack...);"
8658         Diag(CXXDirectInit->getLocStart(),
8659              VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8660                                     : diag::err_auto_var_init_no_expression)
8661           << VDecl->getDeclName() << VDecl->getType()
8662           << VDecl->getSourceRange();
8663         RealDecl->setInvalidDecl();
8664         return;
8665       } else if (CXXDirectInit->getNumExprs() > 1) {
8666         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
8667              VDecl->isInitCapture()
8668                  ? diag::err_init_capture_multiple_expressions
8669                  : diag::err_auto_var_init_multiple_expressions)
8670           << VDecl->getDeclName() << VDecl->getType()
8671           << VDecl->getSourceRange();
8672         RealDecl->setInvalidDecl();
8673         return;
8674       } else {
8675         DeduceInit = CXXDirectInit->getExpr(0);
8676         if (isa<InitListExpr>(DeduceInit))
8677           Diag(CXXDirectInit->getLocStart(),
8678                diag::err_auto_var_init_paren_braces)
8679             << VDecl->getDeclName() << VDecl->getType()
8680             << VDecl->getSourceRange();
8681       }
8682     }
8683 
8684     // Expressions default to 'id' when we're in a debugger.
8685     bool DefaultedToAuto = false;
8686     if (getLangOpts().DebuggerCastResultToId &&
8687         Init->getType() == Context.UnknownAnyTy) {
8688       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8689       if (Result.isInvalid()) {
8690         VDecl->setInvalidDecl();
8691         return;
8692       }
8693       Init = Result.get();
8694       DefaultedToAuto = true;
8695     }
8696 
8697     QualType DeducedType;
8698     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8699             DAR_Failed)
8700       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8701     if (DeducedType.isNull()) {
8702       RealDecl->setInvalidDecl();
8703       return;
8704     }
8705     VDecl->setType(DeducedType);
8706     assert(VDecl->isLinkageValid());
8707 
8708     // In ARC, infer lifetime.
8709     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8710       VDecl->setInvalidDecl();
8711 
8712     // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8713     // 'id' instead of a specific object type prevents most of our usual checks.
8714     // We only want to warn outside of template instantiations, though:
8715     // inside a template, the 'id' could have come from a parameter.
8716     if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8717         DeducedType->isObjCIdType()) {
8718       SourceLocation Loc =
8719           VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
8720       Diag(Loc, diag::warn_auto_var_is_id)
8721         << VDecl->getDeclName() << DeduceInit->getSourceRange();
8722     }
8723 
8724     // If this is a redeclaration, check that the type we just deduced matches
8725     // the previously declared type.
8726     if (VarDecl *Old = VDecl->getPreviousDecl()) {
8727       // We never need to merge the type, because we cannot form an incomplete
8728       // array of auto, nor deduce such a type.
8729       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8730     }
8731 
8732     // Check the deduced type is valid for a variable declaration.
8733     CheckVariableDeclarationType(VDecl);
8734     if (VDecl->isInvalidDecl())
8735       return;
8736 
8737     // If all looks well, warn if this is a case that will change meaning when
8738     // we implement N3922.
8739     if (DirectInit && !CXXDirectInit && isa<InitListExpr>(Init)) {
8740       Diag(Init->getLocStart(),
8741            diag::warn_auto_var_direct_list_init)
8742         << FixItHint::CreateInsertion(Init->getLocStart(), "=");
8743     }
8744   }
8745 
8746   // dllimport cannot be used on variable definitions.
8747   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8748     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8749     VDecl->setInvalidDecl();
8750     return;
8751   }
8752 
8753   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8754     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8755     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8756     VDecl->setInvalidDecl();
8757     return;
8758   }
8759 
8760   if (!VDecl->getType()->isDependentType()) {
8761     // A definition must end up with a complete type, which means it must be
8762     // complete with the restriction that an array type might be completed by
8763     // the initializer; note that later code assumes this restriction.
8764     QualType BaseDeclType = VDecl->getType();
8765     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8766       BaseDeclType = Array->getElementType();
8767     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8768                             diag::err_typecheck_decl_incomplete_type)) {
8769       RealDecl->setInvalidDecl();
8770       return;
8771     }
8772 
8773     // The variable can not have an abstract class type.
8774     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8775                                diag::err_abstract_type_in_decl,
8776                                AbstractVariableType))
8777       VDecl->setInvalidDecl();
8778   }
8779 
8780   const VarDecl *Def;
8781   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8782     Diag(VDecl->getLocation(), diag::err_redefinition)
8783       << VDecl->getDeclName();
8784     Diag(Def->getLocation(), diag::note_previous_definition);
8785     VDecl->setInvalidDecl();
8786     return;
8787   }
8788 
8789   const VarDecl *PrevInit = nullptr;
8790   if (getLangOpts().CPlusPlus) {
8791     // C++ [class.static.data]p4
8792     //   If a static data member is of const integral or const
8793     //   enumeration type, its declaration in the class definition can
8794     //   specify a constant-initializer which shall be an integral
8795     //   constant expression (5.19). In that case, the member can appear
8796     //   in integral constant expressions. The member shall still be
8797     //   defined in a namespace scope if it is used in the program and the
8798     //   namespace scope definition shall not contain an initializer.
8799     //
8800     // We already performed a redefinition check above, but for static
8801     // data members we also need to check whether there was an in-class
8802     // declaration with an initializer.
8803     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8804       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8805           << VDecl->getDeclName();
8806       Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
8807       return;
8808     }
8809 
8810     if (VDecl->hasLocalStorage())
8811       getCurFunction()->setHasBranchProtectedScope();
8812 
8813     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8814       VDecl->setInvalidDecl();
8815       return;
8816     }
8817   }
8818 
8819   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8820   // a kernel function cannot be initialized."
8821   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8822     Diag(VDecl->getLocation(), diag::err_local_cant_init);
8823     VDecl->setInvalidDecl();
8824     return;
8825   }
8826 
8827   // Get the decls type and save a reference for later, since
8828   // CheckInitializerTypes may change it.
8829   QualType DclT = VDecl->getType(), SavT = DclT;
8830 
8831   // Expressions default to 'id' when we're in a debugger
8832   // and we are assigning it to a variable of Objective-C pointer type.
8833   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8834       Init->getType() == Context.UnknownAnyTy) {
8835     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8836     if (Result.isInvalid()) {
8837       VDecl->setInvalidDecl();
8838       return;
8839     }
8840     Init = Result.get();
8841   }
8842 
8843   // Perform the initialization.
8844   if (!VDecl->isInvalidDecl()) {
8845     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8846     InitializationKind Kind
8847       = DirectInit ?
8848           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8849                                                            Init->getLocStart(),
8850                                                            Init->getLocEnd())
8851                         : InitializationKind::CreateDirectList(
8852                                                           VDecl->getLocation())
8853                    : InitializationKind::CreateCopy(VDecl->getLocation(),
8854                                                     Init->getLocStart());
8855 
8856     MultiExprArg Args = Init;
8857     if (CXXDirectInit)
8858       Args = MultiExprArg(CXXDirectInit->getExprs(),
8859                           CXXDirectInit->getNumExprs());
8860 
8861     // Try to correct any TypoExprs in the initialization arguments.
8862     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
8863       ExprResult Res =
8864           CorrectDelayedTyposInExpr(Args[Idx], [this, Entity, Kind](Expr *E) {
8865             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
8866             return Init.Failed() ? ExprError() : E;
8867           });
8868       if (Res.isInvalid()) {
8869         VDecl->setInvalidDecl();
8870       } else if (Res.get() != Args[Idx]) {
8871         Args[Idx] = Res.get();
8872       }
8873     }
8874     if (VDecl->isInvalidDecl())
8875       return;
8876 
8877     InitializationSequence InitSeq(*this, Entity, Kind, Args);
8878     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
8879     if (Result.isInvalid()) {
8880       VDecl->setInvalidDecl();
8881       return;
8882     }
8883 
8884     Init = Result.getAs<Expr>();
8885   }
8886 
8887   // Check for self-references within variable initializers.
8888   // Variables declared within a function/method body (except for references)
8889   // are handled by a dataflow analysis.
8890   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8891       VDecl->getType()->isReferenceType()) {
8892     CheckSelfReference(*this, RealDecl, Init, DirectInit);
8893   }
8894 
8895   // If the type changed, it means we had an incomplete type that was
8896   // completed by the initializer. For example:
8897   //   int ary[] = { 1, 3, 5 };
8898   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
8899   if (!VDecl->isInvalidDecl() && (DclT != SavT))
8900     VDecl->setType(DclT);
8901 
8902   if (!VDecl->isInvalidDecl()) {
8903     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8904 
8905     if (VDecl->hasAttr<BlocksAttr>())
8906       checkRetainCycles(VDecl, Init);
8907 
8908     // It is safe to assign a weak reference into a strong variable.
8909     // Although this code can still have problems:
8910     //   id x = self.weakProp;
8911     //   id y = self.weakProp;
8912     // we do not warn to warn spuriously when 'x' and 'y' are on separate
8913     // paths through the function. This should be revisited if
8914     // -Wrepeated-use-of-weak is made flow-sensitive.
8915     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
8916         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
8917                          Init->getLocStart()))
8918         getCurFunction()->markSafeWeakUse(Init);
8919   }
8920 
8921   // The initialization is usually a full-expression.
8922   //
8923   // FIXME: If this is a braced initialization of an aggregate, it is not
8924   // an expression, and each individual field initializer is a separate
8925   // full-expression. For instance, in:
8926   //
8927   //   struct Temp { ~Temp(); };
8928   //   struct S { S(Temp); };
8929   //   struct T { S a, b; } t = { Temp(), Temp() }
8930   //
8931   // we should destroy the first Temp before constructing the second.
8932   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8933                                           false,
8934                                           VDecl->isConstexpr());
8935   if (Result.isInvalid()) {
8936     VDecl->setInvalidDecl();
8937     return;
8938   }
8939   Init = Result.get();
8940 
8941   // Attach the initializer to the decl.
8942   VDecl->setInit(Init);
8943 
8944   if (VDecl->isLocalVarDecl()) {
8945     // C99 6.7.8p4: All the expressions in an initializer for an object that has
8946     // static storage duration shall be constant expressions or string literals.
8947     // C++ does not have this restriction.
8948     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8949       const Expr *Culprit;
8950       if (VDecl->getStorageClass() == SC_Static)
8951         CheckForConstantInitializer(Init, DclT);
8952       // C89 is stricter than C99 for non-static aggregate types.
8953       // C89 6.5.7p3: All the expressions [...] in an initializer list
8954       // for an object that has aggregate or union type shall be
8955       // constant expressions.
8956       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
8957                isa<InitListExpr>(Init) &&
8958                !Init->isConstantInitializer(Context, false, &Culprit))
8959         Diag(Culprit->getExprLoc(),
8960              diag::ext_aggregate_init_not_constant)
8961           << Culprit->getSourceRange();
8962     }
8963   } else if (VDecl->isStaticDataMember() &&
8964              VDecl->getLexicalDeclContext()->isRecord()) {
8965     // This is an in-class initialization for a static data member, e.g.,
8966     //
8967     // struct S {
8968     //   static const int value = 17;
8969     // };
8970 
8971     // C++ [class.mem]p4:
8972     //   A member-declarator can contain a constant-initializer only
8973     //   if it declares a static member (9.4) of const integral or
8974     //   const enumeration type, see 9.4.2.
8975     //
8976     // C++11 [class.static.data]p3:
8977     //   If a non-volatile const static data member is of integral or
8978     //   enumeration type, its declaration in the class definition can
8979     //   specify a brace-or-equal-initializer in which every initalizer-clause
8980     //   that is an assignment-expression is a constant expression. A static
8981     //   data member of literal type can be declared in the class definition
8982     //   with the constexpr specifier; if so, its declaration shall specify a
8983     //   brace-or-equal-initializer in which every initializer-clause that is
8984     //   an assignment-expression is a constant expression.
8985 
8986     // Do nothing on dependent types.
8987     if (DclT->isDependentType()) {
8988 
8989     // Allow any 'static constexpr' members, whether or not they are of literal
8990     // type. We separately check that every constexpr variable is of literal
8991     // type.
8992     } else if (VDecl->isConstexpr()) {
8993 
8994     // Require constness.
8995     } else if (!DclT.isConstQualified()) {
8996       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8997         << Init->getSourceRange();
8998       VDecl->setInvalidDecl();
8999 
9000     // We allow integer constant expressions in all cases.
9001     } else if (DclT->isIntegralOrEnumerationType()) {
9002       // Check whether the expression is a constant expression.
9003       SourceLocation Loc;
9004       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9005         // In C++11, a non-constexpr const static data member with an
9006         // in-class initializer cannot be volatile.
9007         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9008       else if (Init->isValueDependent())
9009         ; // Nothing to check.
9010       else if (Init->isIntegerConstantExpr(Context, &Loc))
9011         ; // Ok, it's an ICE!
9012       else if (Init->isEvaluatable(Context)) {
9013         // If we can constant fold the initializer through heroics, accept it,
9014         // but report this as a use of an extension for -pedantic.
9015         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9016           << Init->getSourceRange();
9017       } else {
9018         // Otherwise, this is some crazy unknown case.  Report the issue at the
9019         // location provided by the isIntegerConstantExpr failed check.
9020         Diag(Loc, diag::err_in_class_initializer_non_constant)
9021           << Init->getSourceRange();
9022         VDecl->setInvalidDecl();
9023       }
9024 
9025     // We allow foldable floating-point constants as an extension.
9026     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9027       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9028       // it anyway and provide a fixit to add the 'constexpr'.
9029       if (getLangOpts().CPlusPlus11) {
9030         Diag(VDecl->getLocation(),
9031              diag::ext_in_class_initializer_float_type_cxx11)
9032             << DclT << Init->getSourceRange();
9033         Diag(VDecl->getLocStart(),
9034              diag::note_in_class_initializer_float_type_cxx11)
9035             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9036       } else {
9037         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9038           << DclT << Init->getSourceRange();
9039 
9040         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9041           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9042             << Init->getSourceRange();
9043           VDecl->setInvalidDecl();
9044         }
9045       }
9046 
9047     // Suggest adding 'constexpr' in C++11 for literal types.
9048     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9049       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9050         << DclT << Init->getSourceRange()
9051         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9052       VDecl->setConstexpr(true);
9053 
9054     } else {
9055       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9056         << DclT << Init->getSourceRange();
9057       VDecl->setInvalidDecl();
9058     }
9059   } else if (VDecl->isFileVarDecl()) {
9060     if (VDecl->getStorageClass() == SC_Extern &&
9061         (!getLangOpts().CPlusPlus ||
9062          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9063            VDecl->isExternC())) &&
9064         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9065       Diag(VDecl->getLocation(), diag::warn_extern_init);
9066 
9067     // C99 6.7.8p4. All file scoped initializers need to be constant.
9068     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9069       CheckForConstantInitializer(Init, DclT);
9070   }
9071 
9072   // We will represent direct-initialization similarly to copy-initialization:
9073   //    int x(1);  -as-> int x = 1;
9074   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9075   //
9076   // Clients that want to distinguish between the two forms, can check for
9077   // direct initializer using VarDecl::getInitStyle().
9078   // A major benefit is that clients that don't particularly care about which
9079   // exactly form was it (like the CodeGen) can handle both cases without
9080   // special case code.
9081 
9082   // C++ 8.5p11:
9083   // The form of initialization (using parentheses or '=') is generally
9084   // insignificant, but does matter when the entity being initialized has a
9085   // class type.
9086   if (CXXDirectInit) {
9087     assert(DirectInit && "Call-style initializer must be direct init.");
9088     VDecl->setInitStyle(VarDecl::CallInit);
9089   } else if (DirectInit) {
9090     // This must be list-initialization. No other way is direct-initialization.
9091     VDecl->setInitStyle(VarDecl::ListInit);
9092   }
9093 
9094   CheckCompleteVariableDeclaration(VDecl);
9095 }
9096 
9097 /// ActOnInitializerError - Given that there was an error parsing an
9098 /// initializer for the given declaration, try to return to some form
9099 /// of sanity.
9100 void Sema::ActOnInitializerError(Decl *D) {
9101   // Our main concern here is re-establishing invariants like "a
9102   // variable's type is either dependent or complete".
9103   if (!D || D->isInvalidDecl()) return;
9104 
9105   VarDecl *VD = dyn_cast<VarDecl>(D);
9106   if (!VD) return;
9107 
9108   // Auto types are meaningless if we can't make sense of the initializer.
9109   if (ParsingInitForAutoVars.count(D)) {
9110     D->setInvalidDecl();
9111     return;
9112   }
9113 
9114   QualType Ty = VD->getType();
9115   if (Ty->isDependentType()) return;
9116 
9117   // Require a complete type.
9118   if (RequireCompleteType(VD->getLocation(),
9119                           Context.getBaseElementType(Ty),
9120                           diag::err_typecheck_decl_incomplete_type)) {
9121     VD->setInvalidDecl();
9122     return;
9123   }
9124 
9125   // Require a non-abstract type.
9126   if (RequireNonAbstractType(VD->getLocation(), Ty,
9127                              diag::err_abstract_type_in_decl,
9128                              AbstractVariableType)) {
9129     VD->setInvalidDecl();
9130     return;
9131   }
9132 
9133   // Don't bother complaining about constructors or destructors,
9134   // though.
9135 }
9136 
9137 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9138                                   bool TypeMayContainAuto) {
9139   // If there is no declaration, there was an error parsing it. Just ignore it.
9140   if (!RealDecl)
9141     return;
9142 
9143   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9144     QualType Type = Var->getType();
9145 
9146     // C++11 [dcl.spec.auto]p3
9147     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9148       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9149         << Var->getDeclName() << Type;
9150       Var->setInvalidDecl();
9151       return;
9152     }
9153 
9154     // C++11 [class.static.data]p3: A static data member can be declared with
9155     // the constexpr specifier; if so, its declaration shall specify
9156     // a brace-or-equal-initializer.
9157     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9158     // the definition of a variable [...] or the declaration of a static data
9159     // member.
9160     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9161       if (Var->isStaticDataMember())
9162         Diag(Var->getLocation(),
9163              diag::err_constexpr_static_mem_var_requires_init)
9164           << Var->getDeclName();
9165       else
9166         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9167       Var->setInvalidDecl();
9168       return;
9169     }
9170 
9171     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9172     // be initialized.
9173     if (!Var->isInvalidDecl() &&
9174         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9175         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9176       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9177       Var->setInvalidDecl();
9178       return;
9179     }
9180 
9181     switch (Var->isThisDeclarationADefinition()) {
9182     case VarDecl::Definition:
9183       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9184         break;
9185 
9186       // We have an out-of-line definition of a static data member
9187       // that has an in-class initializer, so we type-check this like
9188       // a declaration.
9189       //
9190       // Fall through
9191 
9192     case VarDecl::DeclarationOnly:
9193       // It's only a declaration.
9194 
9195       // Block scope. C99 6.7p7: If an identifier for an object is
9196       // declared with no linkage (C99 6.2.2p6), the type for the
9197       // object shall be complete.
9198       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9199           !Var->hasLinkage() && !Var->isInvalidDecl() &&
9200           RequireCompleteType(Var->getLocation(), Type,
9201                               diag::err_typecheck_decl_incomplete_type))
9202         Var->setInvalidDecl();
9203 
9204       // Make sure that the type is not abstract.
9205       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9206           RequireNonAbstractType(Var->getLocation(), Type,
9207                                  diag::err_abstract_type_in_decl,
9208                                  AbstractVariableType))
9209         Var->setInvalidDecl();
9210       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9211           Var->getStorageClass() == SC_PrivateExtern) {
9212         Diag(Var->getLocation(), diag::warn_private_extern);
9213         Diag(Var->getLocation(), diag::note_private_extern);
9214       }
9215 
9216       return;
9217 
9218     case VarDecl::TentativeDefinition:
9219       // File scope. C99 6.9.2p2: A declaration of an identifier for an
9220       // object that has file scope without an initializer, and without a
9221       // storage-class specifier or with the storage-class specifier "static",
9222       // constitutes a tentative definition. Note: A tentative definition with
9223       // external linkage is valid (C99 6.2.2p5).
9224       if (!Var->isInvalidDecl()) {
9225         if (const IncompleteArrayType *ArrayT
9226                                     = Context.getAsIncompleteArrayType(Type)) {
9227           if (RequireCompleteType(Var->getLocation(),
9228                                   ArrayT->getElementType(),
9229                                   diag::err_illegal_decl_array_incomplete_type))
9230             Var->setInvalidDecl();
9231         } else if (Var->getStorageClass() == SC_Static) {
9232           // C99 6.9.2p3: If the declaration of an identifier for an object is
9233           // a tentative definition and has internal linkage (C99 6.2.2p3), the
9234           // declared type shall not be an incomplete type.
9235           // NOTE: code such as the following
9236           //     static struct s;
9237           //     struct s { int a; };
9238           // is accepted by gcc. Hence here we issue a warning instead of
9239           // an error and we do not invalidate the static declaration.
9240           // NOTE: to avoid multiple warnings, only check the first declaration.
9241           if (Var->isFirstDecl())
9242             RequireCompleteType(Var->getLocation(), Type,
9243                                 diag::ext_typecheck_decl_incomplete_type);
9244         }
9245       }
9246 
9247       // Record the tentative definition; we're done.
9248       if (!Var->isInvalidDecl())
9249         TentativeDefinitions.push_back(Var);
9250       return;
9251     }
9252 
9253     // Provide a specific diagnostic for uninitialized variable
9254     // definitions with incomplete array type.
9255     if (Type->isIncompleteArrayType()) {
9256       Diag(Var->getLocation(),
9257            diag::err_typecheck_incomplete_array_needs_initializer);
9258       Var->setInvalidDecl();
9259       return;
9260     }
9261 
9262     // Provide a specific diagnostic for uninitialized variable
9263     // definitions with reference type.
9264     if (Type->isReferenceType()) {
9265       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9266         << Var->getDeclName()
9267         << SourceRange(Var->getLocation(), Var->getLocation());
9268       Var->setInvalidDecl();
9269       return;
9270     }
9271 
9272     // Do not attempt to type-check the default initializer for a
9273     // variable with dependent type.
9274     if (Type->isDependentType())
9275       return;
9276 
9277     if (Var->isInvalidDecl())
9278       return;
9279 
9280     if (!Var->hasAttr<AliasAttr>()) {
9281       if (RequireCompleteType(Var->getLocation(),
9282                               Context.getBaseElementType(Type),
9283                               diag::err_typecheck_decl_incomplete_type)) {
9284         Var->setInvalidDecl();
9285         return;
9286       }
9287     } else {
9288       return;
9289     }
9290 
9291     // The variable can not have an abstract class type.
9292     if (RequireNonAbstractType(Var->getLocation(), Type,
9293                                diag::err_abstract_type_in_decl,
9294                                AbstractVariableType)) {
9295       Var->setInvalidDecl();
9296       return;
9297     }
9298 
9299     // Check for jumps past the implicit initializer.  C++0x
9300     // clarifies that this applies to a "variable with automatic
9301     // storage duration", not a "local variable".
9302     // C++11 [stmt.dcl]p3
9303     //   A program that jumps from a point where a variable with automatic
9304     //   storage duration is not in scope to a point where it is in scope is
9305     //   ill-formed unless the variable has scalar type, class type with a
9306     //   trivial default constructor and a trivial destructor, a cv-qualified
9307     //   version of one of these types, or an array of one of the preceding
9308     //   types and is declared without an initializer.
9309     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9310       if (const RecordType *Record
9311             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
9312         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9313         // Mark the function for further checking even if the looser rules of
9314         // C++11 do not require such checks, so that we can diagnose
9315         // incompatibilities with C++98.
9316         if (!CXXRecord->isPOD())
9317           getCurFunction()->setHasBranchProtectedScope();
9318       }
9319     }
9320 
9321     // C++03 [dcl.init]p9:
9322     //   If no initializer is specified for an object, and the
9323     //   object is of (possibly cv-qualified) non-POD class type (or
9324     //   array thereof), the object shall be default-initialized; if
9325     //   the object is of const-qualified type, the underlying class
9326     //   type shall have a user-declared default
9327     //   constructor. Otherwise, if no initializer is specified for
9328     //   a non- static object, the object and its subobjects, if
9329     //   any, have an indeterminate initial value); if the object
9330     //   or any of its subobjects are of const-qualified type, the
9331     //   program is ill-formed.
9332     // C++0x [dcl.init]p11:
9333     //   If no initializer is specified for an object, the object is
9334     //   default-initialized; [...].
9335     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
9336     InitializationKind Kind
9337       = InitializationKind::CreateDefault(Var->getLocation());
9338 
9339     InitializationSequence InitSeq(*this, Entity, Kind, None);
9340     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
9341     if (Init.isInvalid())
9342       Var->setInvalidDecl();
9343     else if (Init.get()) {
9344       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
9345       // This is important for template substitution.
9346       Var->setInitStyle(VarDecl::CallInit);
9347     }
9348 
9349     CheckCompleteVariableDeclaration(Var);
9350   }
9351 }
9352 
9353 void Sema::ActOnCXXForRangeDecl(Decl *D) {
9354   VarDecl *VD = dyn_cast<VarDecl>(D);
9355   if (!VD) {
9356     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9357     D->setInvalidDecl();
9358     return;
9359   }
9360 
9361   VD->setCXXForRangeDecl(true);
9362 
9363   // for-range-declaration cannot be given a storage class specifier.
9364   int Error = -1;
9365   switch (VD->getStorageClass()) {
9366   case SC_None:
9367     break;
9368   case SC_Extern:
9369     Error = 0;
9370     break;
9371   case SC_Static:
9372     Error = 1;
9373     break;
9374   case SC_PrivateExtern:
9375     Error = 2;
9376     break;
9377   case SC_Auto:
9378     Error = 3;
9379     break;
9380   case SC_Register:
9381     Error = 4;
9382     break;
9383   case SC_OpenCLWorkGroupLocal:
9384     llvm_unreachable("Unexpected storage class");
9385   }
9386   if (Error != -1) {
9387     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
9388       << VD->getDeclName() << Error;
9389     D->setInvalidDecl();
9390   }
9391 }
9392 
9393 StmtResult
9394 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
9395                                  IdentifierInfo *Ident,
9396                                  ParsedAttributes &Attrs,
9397                                  SourceLocation AttrEnd) {
9398   // C++1y [stmt.iter]p1:
9399   //   A range-based for statement of the form
9400   //      for ( for-range-identifier : for-range-initializer ) statement
9401   //   is equivalent to
9402   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
9403   DeclSpec DS(Attrs.getPool().getFactory());
9404 
9405   const char *PrevSpec;
9406   unsigned DiagID;
9407   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
9408                      getPrintingPolicy());
9409 
9410   Declarator D(DS, Declarator::ForContext);
9411   D.SetIdentifier(Ident, IdentLoc);
9412   D.takeAttributes(Attrs, AttrEnd);
9413 
9414   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
9415   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
9416                 EmptyAttrs, IdentLoc);
9417   Decl *Var = ActOnDeclarator(S, D);
9418   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
9419   FinalizeDeclaration(Var);
9420   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
9421                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
9422 }
9423 
9424 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
9425   if (var->isInvalidDecl()) return;
9426 
9427   // In ARC, don't allow jumps past the implicit initialization of a
9428   // local retaining variable.
9429   if (getLangOpts().ObjCAutoRefCount &&
9430       var->hasLocalStorage()) {
9431     switch (var->getType().getObjCLifetime()) {
9432     case Qualifiers::OCL_None:
9433     case Qualifiers::OCL_ExplicitNone:
9434     case Qualifiers::OCL_Autoreleasing:
9435       break;
9436 
9437     case Qualifiers::OCL_Weak:
9438     case Qualifiers::OCL_Strong:
9439       getCurFunction()->setHasBranchProtectedScope();
9440       break;
9441     }
9442   }
9443 
9444   // Warn about externally-visible variables being defined without a
9445   // prior declaration.  We only want to do this for global
9446   // declarations, but we also specifically need to avoid doing it for
9447   // class members because the linkage of an anonymous class can
9448   // change if it's later given a typedef name.
9449   if (var->isThisDeclarationADefinition() &&
9450       var->getDeclContext()->getRedeclContext()->isFileContext() &&
9451       var->isExternallyVisible() && var->hasLinkage() &&
9452       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
9453                                   var->getLocation())) {
9454     // Find a previous declaration that's not a definition.
9455     VarDecl *prev = var->getPreviousDecl();
9456     while (prev && prev->isThisDeclarationADefinition())
9457       prev = prev->getPreviousDecl();
9458 
9459     if (!prev)
9460       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
9461   }
9462 
9463   if (var->getTLSKind() == VarDecl::TLS_Static) {
9464     const Expr *Culprit;
9465     if (var->getType().isDestructedType()) {
9466       // GNU C++98 edits for __thread, [basic.start.term]p3:
9467       //   The type of an object with thread storage duration shall not
9468       //   have a non-trivial destructor.
9469       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
9470       if (getLangOpts().CPlusPlus11)
9471         Diag(var->getLocation(), diag::note_use_thread_local);
9472     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
9473                !var->getInit()->isConstantInitializer(
9474                    Context, var->getType()->isReferenceType(), &Culprit)) {
9475       // GNU C++98 edits for __thread, [basic.start.init]p4:
9476       //   An object of thread storage duration shall not require dynamic
9477       //   initialization.
9478       // FIXME: Need strict checking here.
9479       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
9480         << Culprit->getSourceRange();
9481       if (getLangOpts().CPlusPlus11)
9482         Diag(var->getLocation(), diag::note_use_thread_local);
9483     }
9484 
9485   }
9486 
9487   // Apply section attributes and pragmas to global variables.
9488   bool GlobalStorage = var->hasGlobalStorage();
9489   if (GlobalStorage && var->isThisDeclarationADefinition() &&
9490       ActiveTemplateInstantiations.empty()) {
9491     PragmaStack<StringLiteral *> *Stack = nullptr;
9492     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
9493     if (var->getType().isConstQualified())
9494       Stack = &ConstSegStack;
9495     else if (!var->getInit()) {
9496       Stack = &BSSSegStack;
9497       SectionFlags |= ASTContext::PSF_Write;
9498     } else {
9499       Stack = &DataSegStack;
9500       SectionFlags |= ASTContext::PSF_Write;
9501     }
9502     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
9503       var->addAttr(SectionAttr::CreateImplicit(
9504           Context, SectionAttr::Declspec_allocate,
9505           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
9506     }
9507     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
9508       if (UnifySection(SA->getName(), SectionFlags, var))
9509         var->dropAttr<SectionAttr>();
9510 
9511     // Apply the init_seg attribute if this has an initializer.  If the
9512     // initializer turns out to not be dynamic, we'll end up ignoring this
9513     // attribute.
9514     if (CurInitSeg && var->getInit())
9515       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
9516                                                CurInitSegLoc));
9517   }
9518 
9519   // All the following checks are C++ only.
9520   if (!getLangOpts().CPlusPlus) return;
9521 
9522   QualType type = var->getType();
9523   if (type->isDependentType()) return;
9524 
9525   // __block variables might require us to capture a copy-initializer.
9526   if (var->hasAttr<BlocksAttr>()) {
9527     // It's currently invalid to ever have a __block variable with an
9528     // array type; should we diagnose that here?
9529 
9530     // Regardless, we don't want to ignore array nesting when
9531     // constructing this copy.
9532     if (type->isStructureOrClassType()) {
9533       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
9534       SourceLocation poi = var->getLocation();
9535       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
9536       ExprResult result
9537         = PerformMoveOrCopyInitialization(
9538             InitializedEntity::InitializeBlock(poi, type, false),
9539             var, var->getType(), varRef, /*AllowNRVO=*/true);
9540       if (!result.isInvalid()) {
9541         result = MaybeCreateExprWithCleanups(result);
9542         Expr *init = result.getAs<Expr>();
9543         Context.setBlockVarCopyInits(var, init);
9544       }
9545     }
9546   }
9547 
9548   Expr *Init = var->getInit();
9549   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
9550   QualType baseType = Context.getBaseElementType(type);
9551 
9552   if (!var->getDeclContext()->isDependentContext() &&
9553       Init && !Init->isValueDependent()) {
9554     if (IsGlobal && !var->isConstexpr() &&
9555         !getDiagnostics().isIgnored(diag::warn_global_constructor,
9556                                     var->getLocation())) {
9557       // Warn about globals which don't have a constant initializer.  Don't
9558       // warn about globals with a non-trivial destructor because we already
9559       // warned about them.
9560       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
9561       if (!(RD && !RD->hasTrivialDestructor()) &&
9562           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
9563         Diag(var->getLocation(), diag::warn_global_constructor)
9564           << Init->getSourceRange();
9565     }
9566 
9567     if (var->isConstexpr()) {
9568       SmallVector<PartialDiagnosticAt, 8> Notes;
9569       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
9570         SourceLocation DiagLoc = var->getLocation();
9571         // If the note doesn't add any useful information other than a source
9572         // location, fold it into the primary diagnostic.
9573         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9574               diag::note_invalid_subexpr_in_const_expr) {
9575           DiagLoc = Notes[0].first;
9576           Notes.clear();
9577         }
9578         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
9579           << var << Init->getSourceRange();
9580         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9581           Diag(Notes[I].first, Notes[I].second);
9582       }
9583     } else if (var->isUsableInConstantExpressions(Context)) {
9584       // Check whether the initializer of a const variable of integral or
9585       // enumeration type is an ICE now, since we can't tell whether it was
9586       // initialized by a constant expression if we check later.
9587       var->checkInitIsICE();
9588     }
9589   }
9590 
9591   // Require the destructor.
9592   if (const RecordType *recordType = baseType->getAs<RecordType>())
9593     FinalizeVarWithDestructor(var, recordType);
9594 }
9595 
9596 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
9597 /// any semantic actions necessary after any initializer has been attached.
9598 void
9599 Sema::FinalizeDeclaration(Decl *ThisDecl) {
9600   // Note that we are no longer parsing the initializer for this declaration.
9601   ParsingInitForAutoVars.erase(ThisDecl);
9602 
9603   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
9604   if (!VD)
9605     return;
9606 
9607   checkAttributesAfterMerging(*this, *VD);
9608 
9609   // Static locals inherit dll attributes from their function.
9610   if (VD->isStaticLocal()) {
9611     if (FunctionDecl *FD =
9612             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
9613       if (Attr *A = getDLLAttr(FD)) {
9614         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
9615         NewAttr->setInherited(true);
9616         VD->addAttr(NewAttr);
9617       }
9618     }
9619   }
9620 
9621   // Grab the dllimport or dllexport attribute off of the VarDecl.
9622   const InheritableAttr *DLLAttr = getDLLAttr(VD);
9623 
9624   // Imported static data members cannot be defined out-of-line.
9625   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
9626     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
9627         VD->isThisDeclarationADefinition()) {
9628       // We allow definitions of dllimport class template static data members
9629       // with a warning.
9630       CXXRecordDecl *Context =
9631         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
9632       bool IsClassTemplateMember =
9633           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
9634           Context->getDescribedClassTemplate();
9635 
9636       Diag(VD->getLocation(),
9637            IsClassTemplateMember
9638                ? diag::warn_attribute_dllimport_static_field_definition
9639                : diag::err_attribute_dllimport_static_field_definition);
9640       Diag(IA->getLocation(), diag::note_attribute);
9641       if (!IsClassTemplateMember)
9642         VD->setInvalidDecl();
9643     }
9644   }
9645 
9646   // dllimport/dllexport variables cannot be thread local, their TLS index
9647   // isn't exported with the variable.
9648   if (DLLAttr && VD->getTLSKind()) {
9649     Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
9650                                                                   << DLLAttr;
9651     VD->setInvalidDecl();
9652   }
9653 
9654   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
9655     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
9656       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
9657       VD->dropAttr<UsedAttr>();
9658     }
9659   }
9660 
9661   const DeclContext *DC = VD->getDeclContext();
9662   // If there's a #pragma GCC visibility in scope, and this isn't a class
9663   // member, set the visibility of this variable.
9664   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
9665     AddPushedVisibilityAttribute(VD);
9666 
9667   // FIXME: Warn on unused templates.
9668   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
9669       !isa<VarTemplatePartialSpecializationDecl>(VD))
9670     MarkUnusedFileScopedDecl(VD);
9671 
9672   // Now we have parsed the initializer and can update the table of magic
9673   // tag values.
9674   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
9675       !VD->getType()->isIntegralOrEnumerationType())
9676     return;
9677 
9678   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
9679     const Expr *MagicValueExpr = VD->getInit();
9680     if (!MagicValueExpr) {
9681       continue;
9682     }
9683     llvm::APSInt MagicValueInt;
9684     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
9685       Diag(I->getRange().getBegin(),
9686            diag::err_type_tag_for_datatype_not_ice)
9687         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9688       continue;
9689     }
9690     if (MagicValueInt.getActiveBits() > 64) {
9691       Diag(I->getRange().getBegin(),
9692            diag::err_type_tag_for_datatype_too_large)
9693         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9694       continue;
9695     }
9696     uint64_t MagicValue = MagicValueInt.getZExtValue();
9697     RegisterTypeTagForDatatype(I->getArgumentKind(),
9698                                MagicValue,
9699                                I->getMatchingCType(),
9700                                I->getLayoutCompatible(),
9701                                I->getMustBeNull());
9702   }
9703 }
9704 
9705 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
9706                                                    ArrayRef<Decl *> Group) {
9707   SmallVector<Decl*, 8> Decls;
9708 
9709   if (DS.isTypeSpecOwned())
9710     Decls.push_back(DS.getRepAsDecl());
9711 
9712   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
9713   for (unsigned i = 0, e = Group.size(); i != e; ++i)
9714     if (Decl *D = Group[i]) {
9715       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
9716         if (!FirstDeclaratorInGroup)
9717           FirstDeclaratorInGroup = DD;
9718       Decls.push_back(D);
9719     }
9720 
9721   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
9722     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
9723       HandleTagNumbering(*this, Tag, S);
9724       if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9725         Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9726     }
9727   }
9728 
9729   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
9730 }
9731 
9732 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
9733 /// group, performing any necessary semantic checking.
9734 Sema::DeclGroupPtrTy
9735 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
9736                            bool TypeMayContainAuto) {
9737   // C++0x [dcl.spec.auto]p7:
9738   //   If the type deduced for the template parameter U is not the same in each
9739   //   deduction, the program is ill-formed.
9740   // FIXME: When initializer-list support is added, a distinction is needed
9741   // between the deduced type U and the deduced type which 'auto' stands for.
9742   //   auto a = 0, b = { 1, 2, 3 };
9743   // is legal because the deduced type U is 'int' in both cases.
9744   if (TypeMayContainAuto && Group.size() > 1) {
9745     QualType Deduced;
9746     CanQualType DeducedCanon;
9747     VarDecl *DeducedDecl = nullptr;
9748     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
9749       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9750         AutoType *AT = D->getType()->getContainedAutoType();
9751         // Don't reissue diagnostics when instantiating a template.
9752         if (AT && D->isInvalidDecl())
9753           break;
9754         QualType U = AT ? AT->getDeducedType() : QualType();
9755         if (!U.isNull()) {
9756           CanQualType UCanon = Context.getCanonicalType(U);
9757           if (Deduced.isNull()) {
9758             Deduced = U;
9759             DeducedCanon = UCanon;
9760             DeducedDecl = D;
9761           } else if (DeducedCanon != UCanon) {
9762             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9763                  diag::err_auto_different_deductions)
9764               << (AT->isDecltypeAuto() ? 1 : 0)
9765               << Deduced << DeducedDecl->getDeclName()
9766               << U << D->getDeclName()
9767               << DeducedDecl->getInit()->getSourceRange()
9768               << D->getInit()->getSourceRange();
9769             D->setInvalidDecl();
9770             break;
9771           }
9772         }
9773       }
9774     }
9775   }
9776 
9777   ActOnDocumentableDecls(Group);
9778 
9779   return DeclGroupPtrTy::make(
9780       DeclGroupRef::Create(Context, Group.data(), Group.size()));
9781 }
9782 
9783 void Sema::ActOnDocumentableDecl(Decl *D) {
9784   ActOnDocumentableDecls(D);
9785 }
9786 
9787 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
9788   // Don't parse the comment if Doxygen diagnostics are ignored.
9789   if (Group.empty() || !Group[0])
9790    return;
9791 
9792   if (Diags.isIgnored(diag::warn_doc_param_not_found, Group[0]->getLocation()))
9793     return;
9794 
9795   if (Group.size() >= 2) {
9796     // This is a decl group.  Normally it will contain only declarations
9797     // produced from declarator list.  But in case we have any definitions or
9798     // additional declaration references:
9799     //   'typedef struct S {} S;'
9800     //   'typedef struct S *S;'
9801     //   'struct S *pS;'
9802     // FinalizeDeclaratorGroup adds these as separate declarations.
9803     Decl *MaybeTagDecl = Group[0];
9804     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
9805       Group = Group.slice(1);
9806     }
9807   }
9808 
9809   // See if there are any new comments that are not attached to a decl.
9810   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9811   if (!Comments.empty() &&
9812       !Comments.back()->isAttached()) {
9813     // There is at least one comment that not attached to a decl.
9814     // Maybe it should be attached to one of these decls?
9815     //
9816     // Note that this way we pick up not only comments that precede the
9817     // declaration, but also comments that *follow* the declaration -- thanks to
9818     // the lookahead in the lexer: we've consumed the semicolon and looked
9819     // ahead through comments.
9820     for (unsigned i = 0, e = Group.size(); i != e; ++i)
9821       Context.getCommentForDecl(Group[i], &PP);
9822   }
9823 }
9824 
9825 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9826 /// to introduce parameters into function prototype scope.
9827 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
9828   const DeclSpec &DS = D.getDeclSpec();
9829 
9830   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
9831 
9832   // C++03 [dcl.stc]p2 also permits 'auto'.
9833   StorageClass SC = SC_None;
9834   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
9835     SC = SC_Register;
9836   } else if (getLangOpts().CPlusPlus &&
9837              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9838     SC = SC_Auto;
9839   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
9840     Diag(DS.getStorageClassSpecLoc(),
9841          diag::err_invalid_storage_class_in_func_decl);
9842     D.getMutableDeclSpec().ClearStorageClassSpecs();
9843   }
9844 
9845   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9846     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9847       << DeclSpec::getSpecifierName(TSCS);
9848   if (DS.isConstexprSpecified())
9849     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
9850       << 0;
9851 
9852   DiagnoseFunctionSpecifiers(DS);
9853 
9854   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9855   QualType parmDeclType = TInfo->getType();
9856 
9857   if (getLangOpts().CPlusPlus) {
9858     // Check that there are no default arguments inside the type of this
9859     // parameter.
9860     CheckExtraCXXDefaultArguments(D);
9861 
9862     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9863     if (D.getCXXScopeSpec().isSet()) {
9864       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9865         << D.getCXXScopeSpec().getRange();
9866       D.getCXXScopeSpec().clear();
9867     }
9868   }
9869 
9870   // Ensure we have a valid name
9871   IdentifierInfo *II = nullptr;
9872   if (D.hasName()) {
9873     II = D.getIdentifier();
9874     if (!II) {
9875       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9876         << GetNameForDeclarator(D).getName();
9877       D.setInvalidType(true);
9878     }
9879   }
9880 
9881   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
9882   if (II) {
9883     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9884                    ForRedeclaration);
9885     LookupName(R, S);
9886     if (R.isSingleResult()) {
9887       NamedDecl *PrevDecl = R.getFoundDecl();
9888       if (PrevDecl->isTemplateParameter()) {
9889         // Maybe we will complain about the shadowed template parameter.
9890         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9891         // Just pretend that we didn't see the previous declaration.
9892         PrevDecl = nullptr;
9893       } else if (S->isDeclScope(PrevDecl)) {
9894         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
9895         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9896 
9897         // Recover by removing the name
9898         II = nullptr;
9899         D.SetIdentifier(nullptr, D.getIdentifierLoc());
9900         D.setInvalidType(true);
9901       }
9902     }
9903   }
9904 
9905   // Temporarily put parameter variables in the translation unit, not
9906   // the enclosing context.  This prevents them from accidentally
9907   // looking like class members in C++.
9908   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
9909                                     D.getLocStart(),
9910                                     D.getIdentifierLoc(), II,
9911                                     parmDeclType, TInfo,
9912                                     SC);
9913 
9914   if (D.isInvalidType())
9915     New->setInvalidDecl();
9916 
9917   assert(S->isFunctionPrototypeScope());
9918   assert(S->getFunctionPrototypeDepth() >= 1);
9919   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9920                     S->getNextFunctionPrototypeIndex());
9921 
9922   // Add the parameter declaration into this scope.
9923   S->AddDecl(New);
9924   if (II)
9925     IdResolver.AddDecl(New);
9926 
9927   ProcessDeclAttributes(S, New, D);
9928 
9929   if (D.getDeclSpec().isModulePrivateSpecified())
9930     Diag(New->getLocation(), diag::err_module_private_local)
9931       << 1 << New->getDeclName()
9932       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9933       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9934 
9935   if (New->hasAttr<BlocksAttr>()) {
9936     Diag(New->getLocation(), diag::err_block_on_nonlocal);
9937   }
9938   return New;
9939 }
9940 
9941 /// \brief Synthesizes a variable for a parameter arising from a
9942 /// typedef.
9943 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9944                                               SourceLocation Loc,
9945                                               QualType T) {
9946   /* FIXME: setting StartLoc == Loc.
9947      Would it be worth to modify callers so as to provide proper source
9948      location for the unnamed parameters, embedding the parameter's type? */
9949   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
9950                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
9951                                            SC_None, nullptr);
9952   Param->setImplicit();
9953   return Param;
9954 }
9955 
9956 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9957                                     ParmVarDecl * const *ParamEnd) {
9958   // Don't diagnose unused-parameter errors in template instantiations; we
9959   // will already have done so in the template itself.
9960   if (!ActiveTemplateInstantiations.empty())
9961     return;
9962 
9963   for (; Param != ParamEnd; ++Param) {
9964     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
9965         !(*Param)->hasAttr<UnusedAttr>()) {
9966       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9967         << (*Param)->getDeclName();
9968     }
9969   }
9970 }
9971 
9972 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9973                                                   ParmVarDecl * const *ParamEnd,
9974                                                   QualType ReturnTy,
9975                                                   NamedDecl *D) {
9976   if (LangOpts.NumLargeByValueCopy == 0) // No check.
9977     return;
9978 
9979   // Warn if the return value is pass-by-value and larger than the specified
9980   // threshold.
9981   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
9982     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
9983     if (Size > LangOpts.NumLargeByValueCopy)
9984       Diag(D->getLocation(), diag::warn_return_value_size)
9985           << D->getDeclName() << Size;
9986   }
9987 
9988   // Warn if any parameter is pass-by-value and larger than the specified
9989   // threshold.
9990   for (; Param != ParamEnd; ++Param) {
9991     QualType T = (*Param)->getType();
9992     if (T->isDependentType() || !T.isPODType(Context))
9993       continue;
9994     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
9995     if (Size > LangOpts.NumLargeByValueCopy)
9996       Diag((*Param)->getLocation(), diag::warn_parameter_size)
9997           << (*Param)->getDeclName() << Size;
9998   }
9999 }
10000 
10001 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10002                                   SourceLocation NameLoc, IdentifierInfo *Name,
10003                                   QualType T, TypeSourceInfo *TSInfo,
10004                                   StorageClass SC) {
10005   // In ARC, infer a lifetime qualifier for appropriate parameter types.
10006   if (getLangOpts().ObjCAutoRefCount &&
10007       T.getObjCLifetime() == Qualifiers::OCL_None &&
10008       T->isObjCLifetimeType()) {
10009 
10010     Qualifiers::ObjCLifetime lifetime;
10011 
10012     // Special cases for arrays:
10013     //   - if it's const, use __unsafe_unretained
10014     //   - otherwise, it's an error
10015     if (T->isArrayType()) {
10016       if (!T.isConstQualified()) {
10017         DelayedDiagnostics.add(
10018             sema::DelayedDiagnostic::makeForbiddenType(
10019             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10020       }
10021       lifetime = Qualifiers::OCL_ExplicitNone;
10022     } else {
10023       lifetime = T->getObjCARCImplicitLifetime();
10024     }
10025     T = Context.getLifetimeQualifiedType(T, lifetime);
10026   }
10027 
10028   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10029                                          Context.getAdjustedParameterType(T),
10030                                          TSInfo, SC, nullptr);
10031 
10032   // Parameters can not be abstract class types.
10033   // For record types, this is done by the AbstractClassUsageDiagnoser once
10034   // the class has been completely parsed.
10035   if (!CurContext->isRecord() &&
10036       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10037                              AbstractParamType))
10038     New->setInvalidDecl();
10039 
10040   // Parameter declarators cannot be interface types. All ObjC objects are
10041   // passed by reference.
10042   if (T->isObjCObjectType()) {
10043     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10044     Diag(NameLoc,
10045          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10046       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10047     T = Context.getObjCObjectPointerType(T);
10048     New->setType(T);
10049   }
10050 
10051   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10052   // duration shall not be qualified by an address-space qualifier."
10053   // Since all parameters have automatic store duration, they can not have
10054   // an address space.
10055   if (T.getAddressSpace() != 0) {
10056     // OpenCL allows function arguments declared to be an array of a type
10057     // to be qualified with an address space.
10058     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10059       Diag(NameLoc, diag::err_arg_with_address_space);
10060       New->setInvalidDecl();
10061     }
10062   }
10063 
10064   return New;
10065 }
10066 
10067 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10068                                            SourceLocation LocAfterDecls) {
10069   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10070 
10071   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10072   // for a K&R function.
10073   if (!FTI.hasPrototype) {
10074     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10075       --i;
10076       if (FTI.Params[i].Param == nullptr) {
10077         SmallString<256> Code;
10078         llvm::raw_svector_ostream(Code)
10079             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10080         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10081             << FTI.Params[i].Ident
10082             << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
10083 
10084         // Implicitly declare the argument as type 'int' for lack of a better
10085         // type.
10086         AttributeFactory attrs;
10087         DeclSpec DS(attrs);
10088         const char* PrevSpec; // unused
10089         unsigned DiagID; // unused
10090         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10091                            DiagID, Context.getPrintingPolicy());
10092         // Use the identifier location for the type source range.
10093         DS.SetRangeStart(FTI.Params[i].IdentLoc);
10094         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10095         Declarator ParamD(DS, Declarator::KNRTypeListContext);
10096         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10097         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10098       }
10099     }
10100   }
10101 }
10102 
10103 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
10104   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10105   assert(D.isFunctionDeclarator() && "Not a function declarator!");
10106   Scope *ParentScope = FnBodyScope->getParent();
10107 
10108   D.setFunctionDefinitionKind(FDK_Definition);
10109   Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
10110   return ActOnStartOfFunctionDef(FnBodyScope, DP);
10111 }
10112 
10113 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10114   Consumer.HandleInlineMethodDefinition(D);
10115 }
10116 
10117 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10118                              const FunctionDecl*& PossibleZeroParamPrototype) {
10119   // Don't warn about invalid declarations.
10120   if (FD->isInvalidDecl())
10121     return false;
10122 
10123   // Or declarations that aren't global.
10124   if (!FD->isGlobal())
10125     return false;
10126 
10127   // Don't warn about C++ member functions.
10128   if (isa<CXXMethodDecl>(FD))
10129     return false;
10130 
10131   // Don't warn about 'main'.
10132   if (FD->isMain())
10133     return false;
10134 
10135   // Don't warn about inline functions.
10136   if (FD->isInlined())
10137     return false;
10138 
10139   // Don't warn about function templates.
10140   if (FD->getDescribedFunctionTemplate())
10141     return false;
10142 
10143   // Don't warn about function template specializations.
10144   if (FD->isFunctionTemplateSpecialization())
10145     return false;
10146 
10147   // Don't warn for OpenCL kernels.
10148   if (FD->hasAttr<OpenCLKernelAttr>())
10149     return false;
10150 
10151   bool MissingPrototype = true;
10152   for (const FunctionDecl *Prev = FD->getPreviousDecl();
10153        Prev; Prev = Prev->getPreviousDecl()) {
10154     // Ignore any declarations that occur in function or method
10155     // scope, because they aren't visible from the header.
10156     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10157       continue;
10158 
10159     MissingPrototype = !Prev->getType()->isFunctionProtoType();
10160     if (FD->getNumParams() == 0)
10161       PossibleZeroParamPrototype = Prev;
10162     break;
10163   }
10164 
10165   return MissingPrototype;
10166 }
10167 
10168 void
10169 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10170                                    const FunctionDecl *EffectiveDefinition) {
10171   // Don't complain if we're in GNU89 mode and the previous definition
10172   // was an extern inline function.
10173   const FunctionDecl *Definition = EffectiveDefinition;
10174   if (!Definition)
10175     if (!FD->isDefined(Definition))
10176       return;
10177 
10178   if (canRedefineFunction(Definition, getLangOpts()))
10179     return;
10180 
10181   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10182       Definition->getStorageClass() == SC_Extern)
10183     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10184         << FD->getDeclName() << getLangOpts().CPlusPlus;
10185   else
10186     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10187 
10188   Diag(Definition->getLocation(), diag::note_previous_definition);
10189   FD->setInvalidDecl();
10190 }
10191 
10192 
10193 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10194                                    Sema &S) {
10195   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10196 
10197   LambdaScopeInfo *LSI = S.PushLambdaScope();
10198   LSI->CallOperator = CallOperator;
10199   LSI->Lambda = LambdaClass;
10200   LSI->ReturnType = CallOperator->getReturnType();
10201   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10202 
10203   if (LCD == LCD_None)
10204     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10205   else if (LCD == LCD_ByCopy)
10206     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10207   else if (LCD == LCD_ByRef)
10208     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10209   DeclarationNameInfo DNI = CallOperator->getNameInfo();
10210 
10211   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
10212   LSI->Mutable = !CallOperator->isConst();
10213 
10214   // Add the captures to the LSI so they can be noted as already
10215   // captured within tryCaptureVar.
10216   auto I = LambdaClass->field_begin();
10217   for (const auto &C : LambdaClass->captures()) {
10218     if (C.capturesVariable()) {
10219       VarDecl *VD = C.getCapturedVar();
10220       if (VD->isInitCapture())
10221         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10222       QualType CaptureType = VD->getType();
10223       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10224       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
10225           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
10226           /*EllipsisLoc*/C.isPackExpansion()
10227                          ? C.getEllipsisLoc() : SourceLocation(),
10228           CaptureType, /*Expr*/ nullptr);
10229 
10230     } else if (C.capturesThis()) {
10231       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
10232                               S.getCurrentThisType(), /*Expr*/ nullptr);
10233     } else {
10234       LSI->addVLATypeCapture(C.getLocation(), I->getType());
10235     }
10236     ++I;
10237   }
10238 }
10239 
10240 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
10241   // Clear the last template instantiation error context.
10242   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10243 
10244   if (!D)
10245     return D;
10246   FunctionDecl *FD = nullptr;
10247 
10248   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10249     FD = FunTmpl->getTemplatedDecl();
10250   else
10251     FD = cast<FunctionDecl>(D);
10252   // If we are instantiating a generic lambda call operator, push
10253   // a LambdaScopeInfo onto the function stack.  But use the information
10254   // that's already been calculated (ActOnLambdaExpr) to prime the current
10255   // LambdaScopeInfo.
10256   // When the template operator is being specialized, the LambdaScopeInfo,
10257   // has to be properly restored so that tryCaptureVariable doesn't try
10258   // and capture any new variables. In addition when calculating potential
10259   // captures during transformation of nested lambdas, it is necessary to
10260   // have the LSI properly restored.
10261   if (isGenericLambdaCallOperatorSpecialization(FD)) {
10262     assert(ActiveTemplateInstantiations.size() &&
10263       "There should be an active template instantiation on the stack "
10264       "when instantiating a generic lambda!");
10265     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
10266   }
10267   else
10268     // Enter a new function scope
10269     PushFunctionScope();
10270 
10271   // See if this is a redefinition.
10272   if (!FD->isLateTemplateParsed())
10273     CheckForFunctionRedefinition(FD);
10274 
10275   // Builtin functions cannot be defined.
10276   if (unsigned BuiltinID = FD->getBuiltinID()) {
10277     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10278         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
10279       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
10280       FD->setInvalidDecl();
10281     }
10282   }
10283 
10284   // The return type of a function definition must be complete
10285   // (C99 6.9.1p3, C++ [dcl.fct]p6).
10286   QualType ResultType = FD->getReturnType();
10287   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
10288       !FD->isInvalidDecl() &&
10289       RequireCompleteType(FD->getLocation(), ResultType,
10290                           diag::err_func_def_incomplete_result))
10291     FD->setInvalidDecl();
10292 
10293   // GNU warning -Wmissing-prototypes:
10294   //   Warn if a global function is defined without a previous
10295   //   prototype declaration. This warning is issued even if the
10296   //   definition itself provides a prototype. The aim is to detect
10297   //   global functions that fail to be declared in header files.
10298   const FunctionDecl *PossibleZeroParamPrototype = nullptr;
10299   if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
10300     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
10301 
10302     if (PossibleZeroParamPrototype) {
10303       // We found a declaration that is not a prototype,
10304       // but that could be a zero-parameter prototype
10305       if (TypeSourceInfo *TI =
10306               PossibleZeroParamPrototype->getTypeSourceInfo()) {
10307         TypeLoc TL = TI->getTypeLoc();
10308         if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
10309           Diag(PossibleZeroParamPrototype->getLocation(),
10310                diag::note_declaration_not_a_prototype)
10311             << PossibleZeroParamPrototype
10312             << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
10313       }
10314     }
10315   }
10316 
10317   if (FnBodyScope)
10318     PushDeclContext(FnBodyScope, FD);
10319 
10320   // Check the validity of our function parameters
10321   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10322                            /*CheckParameterNames=*/true);
10323 
10324   // Introduce our parameters into the function scope
10325   for (auto Param : FD->params()) {
10326     Param->setOwningFunction(FD);
10327 
10328     // If this has an identifier, add it to the scope stack.
10329     if (Param->getIdentifier() && FnBodyScope) {
10330       CheckShadow(FnBodyScope, Param);
10331 
10332       PushOnScopeChains(Param, FnBodyScope);
10333     }
10334   }
10335 
10336   // If we had any tags defined in the function prototype,
10337   // introduce them into the function scope.
10338   if (FnBodyScope) {
10339     for (ArrayRef<NamedDecl *>::iterator
10340              I = FD->getDeclsInPrototypeScope().begin(),
10341              E = FD->getDeclsInPrototypeScope().end();
10342          I != E; ++I) {
10343       NamedDecl *D = *I;
10344 
10345       // Some of these decls (like enums) may have been pinned to the
10346       // translation unit for lack of a real context earlier. If so, remove
10347       // from the translation unit and reattach to the current context.
10348       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
10349         // Is the decl actually in the context?
10350         for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
10351           if (DI == D) {
10352             Context.getTranslationUnitDecl()->removeDecl(D);
10353             break;
10354           }
10355         }
10356         // Either way, reassign the lexical decl context to our FunctionDecl.
10357         D->setLexicalDeclContext(CurContext);
10358       }
10359 
10360       // If the decl has a non-null name, make accessible in the current scope.
10361       if (!D->getName().empty())
10362         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10363 
10364       // Similarly, dive into enums and fish their constants out, making them
10365       // accessible in this scope.
10366       if (auto *ED = dyn_cast<EnumDecl>(D)) {
10367         for (auto *EI : ED->enumerators())
10368           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
10369       }
10370     }
10371   }
10372 
10373   // Ensure that the function's exception specification is instantiated.
10374   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10375     ResolveExceptionSpec(D->getLocation(), FPT);
10376 
10377   // dllimport cannot be applied to non-inline function definitions.
10378   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10379       !FD->isTemplateInstantiation()) {
10380     assert(!FD->hasAttr<DLLExportAttr>());
10381     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10382     FD->setInvalidDecl();
10383     return D;
10384   }
10385   // We want to attach documentation to original Decl (which might be
10386   // a function template).
10387   ActOnDocumentableDecl(D);
10388   if (getCurLexicalContext()->isObjCContainer() &&
10389       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10390       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10391     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10392 
10393   return D;
10394 }
10395 
10396 /// \brief Given the set of return statements within a function body,
10397 /// compute the variables that are subject to the named return value
10398 /// optimization.
10399 ///
10400 /// Each of the variables that is subject to the named return value
10401 /// optimization will be marked as NRVO variables in the AST, and any
10402 /// return statement that has a marked NRVO variable as its NRVO candidate can
10403 /// use the named return value optimization.
10404 ///
10405 /// This function applies a very simplistic algorithm for NRVO: if every return
10406 /// statement in the scope of a variable has the same NRVO candidate, that
10407 /// candidate is an NRVO variable.
10408 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
10409   ReturnStmt **Returns = Scope->Returns.data();
10410 
10411   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
10412     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
10413       if (!NRVOCandidate->isNRVOVariable())
10414         Returns[I]->setNRVOCandidate(nullptr);
10415     }
10416   }
10417 }
10418 
10419 bool Sema::canDelayFunctionBody(const Declarator &D) {
10420   // We can't delay parsing the body of a constexpr function template (yet).
10421   if (D.getDeclSpec().isConstexprSpecified())
10422     return false;
10423 
10424   // We can't delay parsing the body of a function template with a deduced
10425   // return type (yet).
10426   if (D.getDeclSpec().containsPlaceholderType()) {
10427     // If the placeholder introduces a non-deduced trailing return type,
10428     // we can still delay parsing it.
10429     if (D.getNumTypeObjects()) {
10430       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
10431       if (Outer.Kind == DeclaratorChunk::Function &&
10432           Outer.Fun.hasTrailingReturnType()) {
10433         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
10434         return Ty.isNull() || !Ty->isUndeducedType();
10435       }
10436     }
10437     return false;
10438   }
10439 
10440   return true;
10441 }
10442 
10443 bool Sema::canSkipFunctionBody(Decl *D) {
10444   // We cannot skip the body of a function (or function template) which is
10445   // constexpr, since we may need to evaluate its body in order to parse the
10446   // rest of the file.
10447   // We cannot skip the body of a function with an undeduced return type,
10448   // because any callers of that function need to know the type.
10449   if (const FunctionDecl *FD = D->getAsFunction())
10450     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
10451       return false;
10452   return Consumer.shouldSkipFunctionBody(D);
10453 }
10454 
10455 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
10456   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
10457     FD->setHasSkippedBody();
10458   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
10459     MD->setHasSkippedBody();
10460   return ActOnFinishFunctionBody(Decl, nullptr);
10461 }
10462 
10463 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
10464   return ActOnFinishFunctionBody(D, BodyArg, false);
10465 }
10466 
10467 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
10468                                     bool IsInstantiation) {
10469   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
10470 
10471   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10472   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
10473 
10474   if (FD) {
10475     FD->setBody(Body);
10476 
10477     if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
10478         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
10479       // If the function has a deduced result type but contains no 'return'
10480       // statements, the result type as written must be exactly 'auto', and
10481       // the deduced result type is 'void'.
10482       if (!FD->getReturnType()->getAs<AutoType>()) {
10483         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
10484             << FD->getReturnType();
10485         FD->setInvalidDecl();
10486       } else {
10487         // Substitute 'void' for the 'auto' in the type.
10488         TypeLoc ResultType = getReturnTypeLoc(FD);
10489         Context.adjustDeducedFunctionResultType(
10490             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
10491       }
10492     }
10493 
10494     // The only way to be included in UndefinedButUsed is if there is an
10495     // ODR use before the definition. Avoid the expensive map lookup if this
10496     // is the first declaration.
10497     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
10498       if (!FD->isExternallyVisible())
10499         UndefinedButUsed.erase(FD);
10500       else if (FD->isInlined() &&
10501                (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
10502                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
10503         UndefinedButUsed.erase(FD);
10504     }
10505 
10506     // If the function implicitly returns zero (like 'main') or is naked,
10507     // don't complain about missing return statements.
10508     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
10509       WP.disableCheckFallThrough();
10510 
10511     // MSVC permits the use of pure specifier (=0) on function definition,
10512     // defined at class scope, warn about this non-standard construct.
10513     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
10514       Diag(FD->getLocation(), diag::ext_pure_function_definition);
10515 
10516     if (!FD->isInvalidDecl()) {
10517       // Don't diagnose unused parameters of defaulted or deleted functions.
10518       if (Body)
10519         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
10520       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
10521                                              FD->getReturnType(), FD);
10522 
10523       // If this is a structor, we need a vtable.
10524       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
10525         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
10526       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
10527         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
10528 
10529       // Try to apply the named return value optimization. We have to check
10530       // if we can do this here because lambdas keep return statements around
10531       // to deduce an implicit return type.
10532       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
10533           !FD->isDependentContext())
10534         computeNRVO(Body, getCurFunction());
10535     }
10536 
10537     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
10538       const CXXMethodDecl *KeyFunction;
10539       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
10540           MD->isVirtual() &&
10541           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
10542           MD == KeyFunction->getCanonicalDecl()) {
10543         // Update the key-function state if necessary for this ABI.
10544         if (FD->isInlined() &&
10545             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
10546           Context.setNonKeyFunction(MD);
10547 
10548           // If the newly-chosen key function is already defined, then we
10549           // need to mark the vtable as used retroactively.
10550           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
10551           const FunctionDecl *Definition;
10552           if (KeyFunction && KeyFunction->isDefined(Definition))
10553             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
10554         } else {
10555           // We just defined they key function; mark the vtable as used.
10556           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
10557         }
10558       }
10559     }
10560 
10561     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
10562            "Function parsing confused");
10563   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
10564     assert(MD == getCurMethodDecl() && "Method parsing confused");
10565     MD->setBody(Body);
10566     if (!MD->isInvalidDecl()) {
10567       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
10568       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
10569                                              MD->getReturnType(), MD);
10570 
10571       if (Body)
10572         computeNRVO(Body, getCurFunction());
10573     }
10574     if (getCurFunction()->ObjCShouldCallSuper) {
10575       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
10576         << MD->getSelector().getAsString();
10577       getCurFunction()->ObjCShouldCallSuper = false;
10578     }
10579     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
10580       const ObjCMethodDecl *InitMethod = nullptr;
10581       bool isDesignated =
10582           MD->isDesignatedInitializerForTheInterface(&InitMethod);
10583       assert(isDesignated && InitMethod);
10584       (void)isDesignated;
10585 
10586       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
10587         auto IFace = MD->getClassInterface();
10588         if (!IFace)
10589           return false;
10590         auto SuperD = IFace->getSuperClass();
10591         if (!SuperD)
10592           return false;
10593         return SuperD->getIdentifier() ==
10594             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
10595       };
10596       // Don't issue this warning for unavailable inits or direct subclasses
10597       // of NSObject.
10598       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
10599         Diag(MD->getLocation(),
10600              diag::warn_objc_designated_init_missing_super_call);
10601         Diag(InitMethod->getLocation(),
10602              diag::note_objc_designated_init_marked_here);
10603       }
10604       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
10605     }
10606     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
10607       // Don't issue this warning for unavaialable inits.
10608       if (!MD->isUnavailable())
10609         Diag(MD->getLocation(),
10610              diag::warn_objc_secondary_init_missing_init_call);
10611       getCurFunction()->ObjCWarnForNoInitDelegation = false;
10612     }
10613   } else {
10614     return nullptr;
10615   }
10616 
10617   assert(!getCurFunction()->ObjCShouldCallSuper &&
10618          "This should only be set for ObjC methods, which should have been "
10619          "handled in the block above.");
10620 
10621   // Verify and clean out per-function state.
10622   if (Body) {
10623     // C++ constructors that have function-try-blocks can't have return
10624     // statements in the handlers of that block. (C++ [except.handle]p14)
10625     // Verify this.
10626     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
10627       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
10628 
10629     // Verify that gotos and switch cases don't jump into scopes illegally.
10630     if (getCurFunction()->NeedsScopeChecking() &&
10631         !PP.isCodeCompletionEnabled())
10632       DiagnoseInvalidJumps(Body);
10633 
10634     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
10635       if (!Destructor->getParent()->isDependentType())
10636         CheckDestructor(Destructor);
10637 
10638       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10639                                              Destructor->getParent());
10640     }
10641 
10642     // If any errors have occurred, clear out any temporaries that may have
10643     // been leftover. This ensures that these temporaries won't be picked up for
10644     // deletion in some later function.
10645     if (getDiagnostics().hasErrorOccurred() ||
10646         getDiagnostics().getSuppressAllDiagnostics()) {
10647       DiscardCleanupsInEvaluationContext();
10648     }
10649     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
10650         !isa<FunctionTemplateDecl>(dcl)) {
10651       // Since the body is valid, issue any analysis-based warnings that are
10652       // enabled.
10653       ActivePolicy = &WP;
10654     }
10655 
10656     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
10657         (!CheckConstexprFunctionDecl(FD) ||
10658          !CheckConstexprFunctionBody(FD, Body)))
10659       FD->setInvalidDecl();
10660 
10661     if (FD && FD->hasAttr<NakedAttr>()) {
10662       for (const Stmt *S : Body->children()) {
10663         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
10664           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
10665           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
10666           FD->setInvalidDecl();
10667           break;
10668         }
10669       }
10670     }
10671 
10672     assert(ExprCleanupObjects.size() ==
10673                ExprEvalContexts.back().NumCleanupObjects &&
10674            "Leftover temporaries in function");
10675     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
10676     assert(MaybeODRUseExprs.empty() &&
10677            "Leftover expressions for odr-use checking");
10678   }
10679 
10680   if (!IsInstantiation)
10681     PopDeclContext();
10682 
10683   PopFunctionScopeInfo(ActivePolicy, dcl);
10684   // If any errors have occurred, clear out any temporaries that may have
10685   // been leftover. This ensures that these temporaries won't be picked up for
10686   // deletion in some later function.
10687   if (getDiagnostics().hasErrorOccurred()) {
10688     DiscardCleanupsInEvaluationContext();
10689   }
10690 
10691   return dcl;
10692 }
10693 
10694 
10695 /// When we finish delayed parsing of an attribute, we must attach it to the
10696 /// relevant Decl.
10697 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
10698                                        ParsedAttributes &Attrs) {
10699   // Always attach attributes to the underlying decl.
10700   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
10701     D = TD->getTemplatedDecl();
10702   ProcessDeclAttributeList(S, D, Attrs.getList());
10703 
10704   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
10705     if (Method->isStatic())
10706       checkThisInStaticMemberFunctionAttributes(Method);
10707 }
10708 
10709 
10710 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
10711 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
10712 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
10713                                           IdentifierInfo &II, Scope *S) {
10714   // Before we produce a declaration for an implicitly defined
10715   // function, see whether there was a locally-scoped declaration of
10716   // this name as a function or variable. If so, use that
10717   // (non-visible) declaration, and complain about it.
10718   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
10719     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
10720     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
10721     return ExternCPrev;
10722   }
10723 
10724   // Extension in C99.  Legal in C90, but warn about it.
10725   unsigned diag_id;
10726   if (II.getName().startswith("__builtin_"))
10727     diag_id = diag::warn_builtin_unknown;
10728   else if (getLangOpts().C99)
10729     diag_id = diag::ext_implicit_function_decl;
10730   else
10731     diag_id = diag::warn_implicit_function_decl;
10732   Diag(Loc, diag_id) << &II;
10733 
10734   // Because typo correction is expensive, only do it if the implicit
10735   // function declaration is going to be treated as an error.
10736   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
10737     TypoCorrection Corrected;
10738     if (S &&
10739         (Corrected = CorrectTypo(
10740              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
10741              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
10742       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
10743                    /*ErrorRecovery*/false);
10744   }
10745 
10746   // Set a Declarator for the implicit definition: int foo();
10747   const char *Dummy;
10748   AttributeFactory attrFactory;
10749   DeclSpec DS(attrFactory);
10750   unsigned DiagID;
10751   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
10752                                   Context.getPrintingPolicy());
10753   (void)Error; // Silence warning.
10754   assert(!Error && "Error setting up implicit decl!");
10755   SourceLocation NoLoc;
10756   Declarator D(DS, Declarator::BlockContext);
10757   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
10758                                              /*IsAmbiguous=*/false,
10759                                              /*LParenLoc=*/NoLoc,
10760                                              /*Params=*/nullptr,
10761                                              /*NumParams=*/0,
10762                                              /*EllipsisLoc=*/NoLoc,
10763                                              /*RParenLoc=*/NoLoc,
10764                                              /*TypeQuals=*/0,
10765                                              /*RefQualifierIsLvalueRef=*/true,
10766                                              /*RefQualifierLoc=*/NoLoc,
10767                                              /*ConstQualifierLoc=*/NoLoc,
10768                                              /*VolatileQualifierLoc=*/NoLoc,
10769                                              /*RestrictQualifierLoc=*/NoLoc,
10770                                              /*MutableLoc=*/NoLoc,
10771                                              EST_None,
10772                                              /*ESpecLoc=*/NoLoc,
10773                                              /*Exceptions=*/nullptr,
10774                                              /*ExceptionRanges=*/nullptr,
10775                                              /*NumExceptions=*/0,
10776                                              /*NoexceptExpr=*/nullptr,
10777                                              /*ExceptionSpecTokens=*/nullptr,
10778                                              Loc, Loc, D),
10779                 DS.getAttributes(),
10780                 SourceLocation());
10781   D.SetIdentifier(&II, Loc);
10782 
10783   // Insert this function into translation-unit scope.
10784 
10785   DeclContext *PrevDC = CurContext;
10786   CurContext = Context.getTranslationUnitDecl();
10787 
10788   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
10789   FD->setImplicit();
10790 
10791   CurContext = PrevDC;
10792 
10793   AddKnownFunctionAttributes(FD);
10794 
10795   return FD;
10796 }
10797 
10798 /// \brief Adds any function attributes that we know a priori based on
10799 /// the declaration of this function.
10800 ///
10801 /// These attributes can apply both to implicitly-declared builtins
10802 /// (like __builtin___printf_chk) or to library-declared functions
10803 /// like NSLog or printf.
10804 ///
10805 /// We need to check for duplicate attributes both here and where user-written
10806 /// attributes are applied to declarations.
10807 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10808   if (FD->isInvalidDecl())
10809     return;
10810 
10811   // If this is a built-in function, map its builtin attributes to
10812   // actual attributes.
10813   if (unsigned BuiltinID = FD->getBuiltinID()) {
10814     // Handle printf-formatting attributes.
10815     unsigned FormatIdx;
10816     bool HasVAListArg;
10817     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
10818       if (!FD->hasAttr<FormatAttr>()) {
10819         const char *fmt = "printf";
10820         unsigned int NumParams = FD->getNumParams();
10821         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10822             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10823           fmt = "NSString";
10824         FD->addAttr(FormatAttr::CreateImplicit(Context,
10825                                                &Context.Idents.get(fmt),
10826                                                FormatIdx+1,
10827                                                HasVAListArg ? 0 : FormatIdx+2,
10828                                                FD->getLocation()));
10829       }
10830     }
10831     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10832                                              HasVAListArg)) {
10833      if (!FD->hasAttr<FormatAttr>())
10834        FD->addAttr(FormatAttr::CreateImplicit(Context,
10835                                               &Context.Idents.get("scanf"),
10836                                               FormatIdx+1,
10837                                               HasVAListArg ? 0 : FormatIdx+2,
10838                                               FD->getLocation()));
10839     }
10840 
10841     // Mark const if we don't care about errno and that is the only
10842     // thing preventing the function from being const. This allows
10843     // IRgen to use LLVM intrinsics for such functions.
10844     if (!getLangOpts().MathErrno &&
10845         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
10846       if (!FD->hasAttr<ConstAttr>())
10847         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10848     }
10849 
10850     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10851         !FD->hasAttr<ReturnsTwiceAttr>())
10852       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10853                                          FD->getLocation()));
10854     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
10855       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
10856     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
10857       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10858   }
10859 
10860   IdentifierInfo *Name = FD->getIdentifier();
10861   if (!Name)
10862     return;
10863   if ((!getLangOpts().CPlusPlus &&
10864        FD->getDeclContext()->isTranslationUnit()) ||
10865       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
10866        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
10867        LinkageSpecDecl::lang_c)) {
10868     // Okay: this could be a libc/libm/Objective-C function we know
10869     // about.
10870   } else
10871     return;
10872 
10873   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
10874     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
10875     // target-specific builtins, perhaps?
10876     if (!FD->hasAttr<FormatAttr>())
10877       FD->addAttr(FormatAttr::CreateImplicit(Context,
10878                                              &Context.Idents.get("printf"), 2,
10879                                              Name->isStr("vasprintf") ? 0 : 3,
10880                                              FD->getLocation()));
10881   }
10882 
10883   if (Name->isStr("__CFStringMakeConstantString")) {
10884     // We already have a __builtin___CFStringMakeConstantString,
10885     // but builds that use -fno-constant-cfstrings don't go through that.
10886     if (!FD->hasAttr<FormatArgAttr>())
10887       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10888                                                 FD->getLocation()));
10889   }
10890 }
10891 
10892 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
10893                                     TypeSourceInfo *TInfo) {
10894   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
10895   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
10896 
10897   if (!TInfo) {
10898     assert(D.isInvalidType() && "no declarator info for valid type");
10899     TInfo = Context.getTrivialTypeSourceInfo(T);
10900   }
10901 
10902   // Scope manipulation handled by caller.
10903   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
10904                                            D.getLocStart(),
10905                                            D.getIdentifierLoc(),
10906                                            D.getIdentifier(),
10907                                            TInfo);
10908 
10909   // Bail out immediately if we have an invalid declaration.
10910   if (D.isInvalidType()) {
10911     NewTD->setInvalidDecl();
10912     return NewTD;
10913   }
10914 
10915   if (D.getDeclSpec().isModulePrivateSpecified()) {
10916     if (CurContext->isFunctionOrMethod())
10917       Diag(NewTD->getLocation(), diag::err_module_private_local)
10918         << 2 << NewTD->getDeclName()
10919         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10920         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10921     else
10922       NewTD->setModulePrivate();
10923   }
10924 
10925   // C++ [dcl.typedef]p8:
10926   //   If the typedef declaration defines an unnamed class (or
10927   //   enum), the first typedef-name declared by the declaration
10928   //   to be that class type (or enum type) is used to denote the
10929   //   class type (or enum type) for linkage purposes only.
10930   // We need to check whether the type was declared in the declaration.
10931   switch (D.getDeclSpec().getTypeSpecType()) {
10932   case TST_enum:
10933   case TST_struct:
10934   case TST_interface:
10935   case TST_union:
10936   case TST_class: {
10937     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10938 
10939     // Do nothing if the tag is not anonymous or already has an
10940     // associated typedef (from an earlier typedef in this decl group).
10941     if (tagFromDeclSpec->getIdentifier()) break;
10942     if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
10943 
10944     // A well-formed anonymous tag must always be a TUK_Definition.
10945     assert(tagFromDeclSpec->isThisDeclarationADefinition());
10946 
10947     // The type must match the tag exactly;  no qualifiers allowed.
10948     if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10949       break;
10950 
10951     // If we've already computed linkage for the anonymous tag, then
10952     // adding a typedef name for the anonymous decl can change that
10953     // linkage, which might be a serious problem.  Diagnose this as
10954     // unsupported and ignore the typedef name.  TODO: we should
10955     // pursue this as a language defect and establish a formal rule
10956     // for how to handle it.
10957     if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10958       Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10959 
10960       SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
10961       tagLoc = getLocForEndOfToken(tagLoc);
10962 
10963       llvm::SmallString<40> textToInsert;
10964       textToInsert += ' ';
10965       textToInsert += D.getIdentifier()->getName();
10966       Diag(tagLoc, diag::note_typedef_changes_linkage)
10967         << FixItHint::CreateInsertion(tagLoc, textToInsert);
10968       break;
10969     }
10970 
10971     // Otherwise, set this is the anon-decl typedef for the tag.
10972     tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
10973     break;
10974   }
10975 
10976   default:
10977     break;
10978   }
10979 
10980   return NewTD;
10981 }
10982 
10983 
10984 /// \brief Check that this is a valid underlying type for an enum declaration.
10985 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10986   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10987   QualType T = TI->getType();
10988 
10989   if (T->isDependentType())
10990     return false;
10991 
10992   if (const BuiltinType *BT = T->getAs<BuiltinType>())
10993     if (BT->isInteger())
10994       return false;
10995 
10996   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10997   return true;
10998 }
10999 
11000 /// Check whether this is a valid redeclaration of a previous enumeration.
11001 /// \return true if the redeclaration was invalid.
11002 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
11003                                   QualType EnumUnderlyingTy,
11004                                   const EnumDecl *Prev) {
11005   bool IsFixed = !EnumUnderlyingTy.isNull();
11006 
11007   if (IsScoped != Prev->isScoped()) {
11008     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11009       << Prev->isScoped();
11010     Diag(Prev->getLocation(), diag::note_previous_declaration);
11011     return true;
11012   }
11013 
11014   if (IsFixed && Prev->isFixed()) {
11015     if (!EnumUnderlyingTy->isDependentType() &&
11016         !Prev->getIntegerType()->isDependentType() &&
11017         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11018                                         Prev->getIntegerType())) {
11019       // TODO: Highlight the underlying type of the redeclaration.
11020       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11021         << EnumUnderlyingTy << Prev->getIntegerType();
11022       Diag(Prev->getLocation(), diag::note_previous_declaration)
11023           << Prev->getIntegerTypeRange();
11024       return true;
11025     }
11026   } else if (IsFixed != Prev->isFixed()) {
11027     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11028       << Prev->isFixed();
11029     Diag(Prev->getLocation(), diag::note_previous_declaration);
11030     return true;
11031   }
11032 
11033   return false;
11034 }
11035 
11036 /// \brief Get diagnostic %select index for tag kind for
11037 /// redeclaration diagnostic message.
11038 /// WARNING: Indexes apply to particular diagnostics only!
11039 ///
11040 /// \returns diagnostic %select index.
11041 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
11042   switch (Tag) {
11043   case TTK_Struct: return 0;
11044   case TTK_Interface: return 1;
11045   case TTK_Class:  return 2;
11046   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11047   }
11048 }
11049 
11050 /// \brief Determine if tag kind is a class-key compatible with
11051 /// class for redeclaration (class, struct, or __interface).
11052 ///
11053 /// \returns true iff the tag kind is compatible.
11054 static bool isClassCompatTagKind(TagTypeKind Tag)
11055 {
11056   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11057 }
11058 
11059 /// \brief Determine whether a tag with a given kind is acceptable
11060 /// as a redeclaration of the given tag declaration.
11061 ///
11062 /// \returns true if the new tag kind is acceptable, false otherwise.
11063 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11064                                         TagTypeKind NewTag, bool isDefinition,
11065                                         SourceLocation NewTagLoc,
11066                                         const IdentifierInfo &Name) {
11067   // C++ [dcl.type.elab]p3:
11068   //   The class-key or enum keyword present in the
11069   //   elaborated-type-specifier shall agree in kind with the
11070   //   declaration to which the name in the elaborated-type-specifier
11071   //   refers. This rule also applies to the form of
11072   //   elaborated-type-specifier that declares a class-name or
11073   //   friend class since it can be construed as referring to the
11074   //   definition of the class. Thus, in any
11075   //   elaborated-type-specifier, the enum keyword shall be used to
11076   //   refer to an enumeration (7.2), the union class-key shall be
11077   //   used to refer to a union (clause 9), and either the class or
11078   //   struct class-key shall be used to refer to a class (clause 9)
11079   //   declared using the class or struct class-key.
11080   TagTypeKind OldTag = Previous->getTagKind();
11081   if (!isDefinition || !isClassCompatTagKind(NewTag))
11082     if (OldTag == NewTag)
11083       return true;
11084 
11085   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11086     // Warn about the struct/class tag mismatch.
11087     bool isTemplate = false;
11088     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11089       isTemplate = Record->getDescribedClassTemplate();
11090 
11091     if (!ActiveTemplateInstantiations.empty()) {
11092       // In a template instantiation, do not offer fix-its for tag mismatches
11093       // since they usually mess up the template instead of fixing the problem.
11094       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11095         << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11096         << getRedeclDiagFromTagKind(OldTag);
11097       return true;
11098     }
11099 
11100     if (isDefinition) {
11101       // On definitions, check previous tags and issue a fix-it for each
11102       // one that doesn't match the current tag.
11103       if (Previous->getDefinition()) {
11104         // Don't suggest fix-its for redefinitions.
11105         return true;
11106       }
11107 
11108       bool previousMismatch = false;
11109       for (auto I : Previous->redecls()) {
11110         if (I->getTagKind() != NewTag) {
11111           if (!previousMismatch) {
11112             previousMismatch = true;
11113             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11114               << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11115               << getRedeclDiagFromTagKind(I->getTagKind());
11116           }
11117           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11118             << getRedeclDiagFromTagKind(NewTag)
11119             << FixItHint::CreateReplacement(I->getInnerLocStart(),
11120                  TypeWithKeyword::getTagTypeKindName(NewTag));
11121         }
11122       }
11123       return true;
11124     }
11125 
11126     // Check for a previous definition.  If current tag and definition
11127     // are same type, do nothing.  If no definition, but disagree with
11128     // with previous tag type, give a warning, but no fix-it.
11129     const TagDecl *Redecl = Previous->getDefinition() ?
11130                             Previous->getDefinition() : Previous;
11131     if (Redecl->getTagKind() == NewTag) {
11132       return true;
11133     }
11134 
11135     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11136       << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
11137       << getRedeclDiagFromTagKind(OldTag);
11138     Diag(Redecl->getLocation(), diag::note_previous_use);
11139 
11140     // If there is a previous definition, suggest a fix-it.
11141     if (Previous->getDefinition()) {
11142         Diag(NewTagLoc, diag::note_struct_class_suggestion)
11143           << getRedeclDiagFromTagKind(Redecl->getTagKind())
11144           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11145                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11146     }
11147 
11148     return true;
11149   }
11150   return false;
11151 }
11152 
11153 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11154 /// from an outer enclosing namespace or file scope inside a friend declaration.
11155 /// This should provide the commented out code in the following snippet:
11156 ///   namespace N {
11157 ///     struct X;
11158 ///     namespace M {
11159 ///       struct Y { friend struct /*N::*/ X; };
11160 ///     }
11161 ///   }
11162 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11163                                          SourceLocation NameLoc) {
11164   // While the decl is in a namespace, do repeated lookup of that name and see
11165   // if we get the same namespace back.  If we do not, continue until
11166   // translation unit scope, at which point we have a fully qualified NNS.
11167   SmallVector<IdentifierInfo *, 4> Namespaces;
11168   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11169   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11170     // This tag should be declared in a namespace, which can only be enclosed by
11171     // other namespaces.  Bail if there's an anonymous namespace in the chain.
11172     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11173     if (!Namespace || Namespace->isAnonymousNamespace())
11174       return FixItHint();
11175     IdentifierInfo *II = Namespace->getIdentifier();
11176     Namespaces.push_back(II);
11177     NamedDecl *Lookup = SemaRef.LookupSingleName(
11178         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11179     if (Lookup == Namespace)
11180       break;
11181   }
11182 
11183   // Once we have all the namespaces, reverse them to go outermost first, and
11184   // build an NNS.
11185   SmallString<64> Insertion;
11186   llvm::raw_svector_ostream OS(Insertion);
11187   if (DC->isTranslationUnit())
11188     OS << "::";
11189   std::reverse(Namespaces.begin(), Namespaces.end());
11190   for (auto *II : Namespaces)
11191     OS << II->getName() << "::";
11192   OS.flush();
11193   return FixItHint::CreateInsertion(NameLoc, Insertion);
11194 }
11195 
11196 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
11197 /// former case, Name will be non-null.  In the later case, Name will be null.
11198 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
11199 /// reference/declaration/definition of a tag.
11200 ///
11201 /// IsTypeSpecifier is true if this is a type-specifier (or
11202 /// trailing-type-specifier) other than one in an alias-declaration.
11203 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11204                      SourceLocation KWLoc, CXXScopeSpec &SS,
11205                      IdentifierInfo *Name, SourceLocation NameLoc,
11206                      AttributeList *Attr, AccessSpecifier AS,
11207                      SourceLocation ModulePrivateLoc,
11208                      MultiTemplateParamsArg TemplateParameterLists,
11209                      bool &OwnedDecl, bool &IsDependent,
11210                      SourceLocation ScopedEnumKWLoc,
11211                      bool ScopedEnumUsesClassTag,
11212                      TypeResult UnderlyingType,
11213                      bool IsTypeSpecifier) {
11214   // If this is not a definition, it must have a name.
11215   IdentifierInfo *OrigName = Name;
11216   assert((Name != nullptr || TUK == TUK_Definition) &&
11217          "Nameless record must be a definition!");
11218   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
11219 
11220   OwnedDecl = false;
11221   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11222   bool ScopedEnum = ScopedEnumKWLoc.isValid();
11223 
11224   // FIXME: Check explicit specializations more carefully.
11225   bool isExplicitSpecialization = false;
11226   bool Invalid = false;
11227 
11228   // We only need to do this matching if we have template parameters
11229   // or a scope specifier, which also conveniently avoids this work
11230   // for non-C++ cases.
11231   if (TemplateParameterLists.size() > 0 ||
11232       (SS.isNotEmpty() && TUK != TUK_Reference)) {
11233     if (TemplateParameterList *TemplateParams =
11234             MatchTemplateParametersToScopeSpecifier(
11235                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
11236                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
11237       if (Kind == TTK_Enum) {
11238         Diag(KWLoc, diag::err_enum_template);
11239         return nullptr;
11240       }
11241 
11242       if (TemplateParams->size() > 0) {
11243         // This is a declaration or definition of a class template (which may
11244         // be a member of another template).
11245 
11246         if (Invalid)
11247           return nullptr;
11248 
11249         OwnedDecl = false;
11250         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
11251                                                SS, Name, NameLoc, Attr,
11252                                                TemplateParams, AS,
11253                                                ModulePrivateLoc,
11254                                                /*FriendLoc*/SourceLocation(),
11255                                                TemplateParameterLists.size()-1,
11256                                                TemplateParameterLists.data());
11257         return Result.get();
11258       } else {
11259         // The "template<>" header is extraneous.
11260         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11261           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11262         isExplicitSpecialization = true;
11263       }
11264     }
11265   }
11266 
11267   // Figure out the underlying type if this a enum declaration. We need to do
11268   // this early, because it's needed to detect if this is an incompatible
11269   // redeclaration.
11270   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11271 
11272   if (Kind == TTK_Enum) {
11273     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11274       // No underlying type explicitly specified, or we failed to parse the
11275       // type, default to int.
11276       EnumUnderlying = Context.IntTy.getTypePtr();
11277     else if (UnderlyingType.get()) {
11278       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11279       // integral type; any cv-qualification is ignored.
11280       TypeSourceInfo *TI = nullptr;
11281       GetTypeFromParser(UnderlyingType.get(), &TI);
11282       EnumUnderlying = TI;
11283 
11284       if (CheckEnumUnderlyingType(TI))
11285         // Recover by falling back to int.
11286         EnumUnderlying = Context.IntTy.getTypePtr();
11287 
11288       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
11289                                           UPPC_FixedUnderlyingType))
11290         EnumUnderlying = Context.IntTy.getTypePtr();
11291 
11292     } else if (getLangOpts().MSVCCompat)
11293       // Microsoft enums are always of int type.
11294       EnumUnderlying = Context.IntTy.getTypePtr();
11295   }
11296 
11297   DeclContext *SearchDC = CurContext;
11298   DeclContext *DC = CurContext;
11299   bool isStdBadAlloc = false;
11300 
11301   RedeclarationKind Redecl = ForRedeclaration;
11302   if (TUK == TUK_Friend || TUK == TUK_Reference)
11303     Redecl = NotForRedeclaration;
11304 
11305   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
11306   if (Name && SS.isNotEmpty()) {
11307     // We have a nested-name tag ('struct foo::bar').
11308 
11309     // Check for invalid 'foo::'.
11310     if (SS.isInvalid()) {
11311       Name = nullptr;
11312       goto CreateNewDecl;
11313     }
11314 
11315     // If this is a friend or a reference to a class in a dependent
11316     // context, don't try to make a decl for it.
11317     if (TUK == TUK_Friend || TUK == TUK_Reference) {
11318       DC = computeDeclContext(SS, false);
11319       if (!DC) {
11320         IsDependent = true;
11321         return nullptr;
11322       }
11323     } else {
11324       DC = computeDeclContext(SS, true);
11325       if (!DC) {
11326         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11327           << SS.getRange();
11328         return nullptr;
11329       }
11330     }
11331 
11332     if (RequireCompleteDeclContext(SS, DC))
11333       return nullptr;
11334 
11335     SearchDC = DC;
11336     // Look-up name inside 'foo::'.
11337     LookupQualifiedName(Previous, DC);
11338 
11339     if (Previous.isAmbiguous())
11340       return nullptr;
11341 
11342     if (Previous.empty()) {
11343       // Name lookup did not find anything. However, if the
11344       // nested-name-specifier refers to the current instantiation,
11345       // and that current instantiation has any dependent base
11346       // classes, we might find something at instantiation time: treat
11347       // this as a dependent elaborated-type-specifier.
11348       // But this only makes any sense for reference-like lookups.
11349       if (Previous.wasNotFoundInCurrentInstantiation() &&
11350           (TUK == TUK_Reference || TUK == TUK_Friend)) {
11351         IsDependent = true;
11352         return nullptr;
11353       }
11354 
11355       // A tag 'foo::bar' must already exist.
11356       Diag(NameLoc, diag::err_not_tag_in_scope)
11357         << Kind << Name << DC << SS.getRange();
11358       Name = nullptr;
11359       Invalid = true;
11360       goto CreateNewDecl;
11361     }
11362   } else if (Name) {
11363     // If this is a named struct, check to see if there was a previous forward
11364     // declaration or definition.
11365     // FIXME: We're looking into outer scopes here, even when we
11366     // shouldn't be. Doing so can result in ambiguities that we
11367     // shouldn't be diagnosing.
11368     LookupName(Previous, S);
11369 
11370     // When declaring or defining a tag, ignore ambiguities introduced
11371     // by types using'ed into this scope.
11372     if (Previous.isAmbiguous() &&
11373         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
11374       LookupResult::Filter F = Previous.makeFilter();
11375       while (F.hasNext()) {
11376         NamedDecl *ND = F.next();
11377         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
11378           F.erase();
11379       }
11380       F.done();
11381     }
11382 
11383     // C++11 [namespace.memdef]p3:
11384     //   If the name in a friend declaration is neither qualified nor
11385     //   a template-id and the declaration is a function or an
11386     //   elaborated-type-specifier, the lookup to determine whether
11387     //   the entity has been previously declared shall not consider
11388     //   any scopes outside the innermost enclosing namespace.
11389     //
11390     // MSVC doesn't implement the above rule for types, so a friend tag
11391     // declaration may be a redeclaration of a type declared in an enclosing
11392     // scope.  They do implement this rule for friend functions.
11393     //
11394     // Does it matter that this should be by scope instead of by
11395     // semantic context?
11396     if (!Previous.empty() && TUK == TUK_Friend) {
11397       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
11398       LookupResult::Filter F = Previous.makeFilter();
11399       bool FriendSawTagOutsideEnclosingNamespace = false;
11400       while (F.hasNext()) {
11401         NamedDecl *ND = F.next();
11402         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11403         if (DC->isFileContext() &&
11404             !EnclosingNS->Encloses(ND->getDeclContext())) {
11405           if (getLangOpts().MSVCCompat)
11406             FriendSawTagOutsideEnclosingNamespace = true;
11407           else
11408             F.erase();
11409         }
11410       }
11411       F.done();
11412 
11413       // Diagnose this MSVC extension in the easy case where lookup would have
11414       // unambiguously found something outside the enclosing namespace.
11415       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
11416         NamedDecl *ND = Previous.getFoundDecl();
11417         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
11418             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
11419       }
11420     }
11421 
11422     // Note:  there used to be some attempt at recovery here.
11423     if (Previous.isAmbiguous())
11424       return nullptr;
11425 
11426     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
11427       // FIXME: This makes sure that we ignore the contexts associated
11428       // with C structs, unions, and enums when looking for a matching
11429       // tag declaration or definition. See the similar lookup tweak
11430       // in Sema::LookupName; is there a better way to deal with this?
11431       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
11432         SearchDC = SearchDC->getParent();
11433     }
11434   }
11435 
11436   if (Previous.isSingleResult() &&
11437       Previous.getFoundDecl()->isTemplateParameter()) {
11438     // Maybe we will complain about the shadowed template parameter.
11439     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
11440     // Just pretend that we didn't see the previous declaration.
11441     Previous.clear();
11442   }
11443 
11444   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
11445       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
11446     // This is a declaration of or a reference to "std::bad_alloc".
11447     isStdBadAlloc = true;
11448 
11449     if (Previous.empty() && StdBadAlloc) {
11450       // std::bad_alloc has been implicitly declared (but made invisible to
11451       // name lookup). Fill in this implicit declaration as the previous
11452       // declaration, so that the declarations get chained appropriately.
11453       Previous.addDecl(getStdBadAlloc());
11454     }
11455   }
11456 
11457   // If we didn't find a previous declaration, and this is a reference
11458   // (or friend reference), move to the correct scope.  In C++, we
11459   // also need to do a redeclaration lookup there, just in case
11460   // there's a shadow friend decl.
11461   if (Name && Previous.empty() &&
11462       (TUK == TUK_Reference || TUK == TUK_Friend)) {
11463     if (Invalid) goto CreateNewDecl;
11464     assert(SS.isEmpty());
11465 
11466     if (TUK == TUK_Reference) {
11467       // C++ [basic.scope.pdecl]p5:
11468       //   -- for an elaborated-type-specifier of the form
11469       //
11470       //          class-key identifier
11471       //
11472       //      if the elaborated-type-specifier is used in the
11473       //      decl-specifier-seq or parameter-declaration-clause of a
11474       //      function defined in namespace scope, the identifier is
11475       //      declared as a class-name in the namespace that contains
11476       //      the declaration; otherwise, except as a friend
11477       //      declaration, the identifier is declared in the smallest
11478       //      non-class, non-function-prototype scope that contains the
11479       //      declaration.
11480       //
11481       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
11482       // C structs and unions.
11483       //
11484       // It is an error in C++ to declare (rather than define) an enum
11485       // type, including via an elaborated type specifier.  We'll
11486       // diagnose that later; for now, declare the enum in the same
11487       // scope as we would have picked for any other tag type.
11488       //
11489       // GNU C also supports this behavior as part of its incomplete
11490       // enum types extension, while GNU C++ does not.
11491       //
11492       // Find the context where we'll be declaring the tag.
11493       // FIXME: We would like to maintain the current DeclContext as the
11494       // lexical context,
11495       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
11496         SearchDC = SearchDC->getParent();
11497 
11498       // Find the scope where we'll be declaring the tag.
11499       while (S->isClassScope() ||
11500              (getLangOpts().CPlusPlus &&
11501               S->isFunctionPrototypeScope()) ||
11502              ((S->getFlags() & Scope::DeclScope) == 0) ||
11503              (S->getEntity() && S->getEntity()->isTransparentContext()))
11504         S = S->getParent();
11505     } else {
11506       assert(TUK == TUK_Friend);
11507       // C++ [namespace.memdef]p3:
11508       //   If a friend declaration in a non-local class first declares a
11509       //   class or function, the friend class or function is a member of
11510       //   the innermost enclosing namespace.
11511       SearchDC = SearchDC->getEnclosingNamespaceContext();
11512     }
11513 
11514     // In C++, we need to do a redeclaration lookup to properly
11515     // diagnose some problems.
11516     if (getLangOpts().CPlusPlus) {
11517       Previous.setRedeclarationKind(ForRedeclaration);
11518       LookupQualifiedName(Previous, SearchDC);
11519     }
11520   }
11521 
11522   if (!Previous.empty()) {
11523     NamedDecl *PrevDecl = Previous.getFoundDecl();
11524     NamedDecl *DirectPrevDecl =
11525         getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
11526 
11527     // It's okay to have a tag decl in the same scope as a typedef
11528     // which hides a tag decl in the same scope.  Finding this
11529     // insanity with a redeclaration lookup can only actually happen
11530     // in C++.
11531     //
11532     // This is also okay for elaborated-type-specifiers, which is
11533     // technically forbidden by the current standard but which is
11534     // okay according to the likely resolution of an open issue;
11535     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
11536     if (getLangOpts().CPlusPlus) {
11537       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11538         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
11539           TagDecl *Tag = TT->getDecl();
11540           if (Tag->getDeclName() == Name &&
11541               Tag->getDeclContext()->getRedeclContext()
11542                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
11543             PrevDecl = Tag;
11544             Previous.clear();
11545             Previous.addDecl(Tag);
11546             Previous.resolveKind();
11547           }
11548         }
11549       }
11550     }
11551 
11552     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
11553       // If this is a use of a previous tag, or if the tag is already declared
11554       // in the same scope (so that the definition/declaration completes or
11555       // rementions the tag), reuse the decl.
11556       if (TUK == TUK_Reference || TUK == TUK_Friend ||
11557           isDeclInScope(DirectPrevDecl, SearchDC, S,
11558                         SS.isNotEmpty() || isExplicitSpecialization)) {
11559         // Make sure that this wasn't declared as an enum and now used as a
11560         // struct or something similar.
11561         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
11562                                           TUK == TUK_Definition, KWLoc,
11563                                           *Name)) {
11564           bool SafeToContinue
11565             = (PrevTagDecl->getTagKind() != TTK_Enum &&
11566                Kind != TTK_Enum);
11567           if (SafeToContinue)
11568             Diag(KWLoc, diag::err_use_with_wrong_tag)
11569               << Name
11570               << FixItHint::CreateReplacement(SourceRange(KWLoc),
11571                                               PrevTagDecl->getKindName());
11572           else
11573             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
11574           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
11575 
11576           if (SafeToContinue)
11577             Kind = PrevTagDecl->getTagKind();
11578           else {
11579             // Recover by making this an anonymous redefinition.
11580             Name = nullptr;
11581             Previous.clear();
11582             Invalid = true;
11583           }
11584         }
11585 
11586         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
11587           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
11588 
11589           // If this is an elaborated-type-specifier for a scoped enumeration,
11590           // the 'class' keyword is not necessary and not permitted.
11591           if (TUK == TUK_Reference || TUK == TUK_Friend) {
11592             if (ScopedEnum)
11593               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
11594                 << PrevEnum->isScoped()
11595                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
11596             return PrevTagDecl;
11597           }
11598 
11599           QualType EnumUnderlyingTy;
11600           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11601             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
11602           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
11603             EnumUnderlyingTy = QualType(T, 0);
11604 
11605           // All conflicts with previous declarations are recovered by
11606           // returning the previous declaration, unless this is a definition,
11607           // in which case we want the caller to bail out.
11608           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
11609                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
11610             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
11611         }
11612 
11613         // C++11 [class.mem]p1:
11614         //   A member shall not be declared twice in the member-specification,
11615         //   except that a nested class or member class template can be declared
11616         //   and then later defined.
11617         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
11618             S->isDeclScope(PrevDecl)) {
11619           Diag(NameLoc, diag::ext_member_redeclared);
11620           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
11621         }
11622 
11623         if (!Invalid) {
11624           // If this is a use, just return the declaration we found, unless
11625           // we have attributes.
11626 
11627           // FIXME: In the future, return a variant or some other clue
11628           // for the consumer of this Decl to know it doesn't own it.
11629           // For our current ASTs this shouldn't be a problem, but will
11630           // need to be changed with DeclGroups.
11631           if (!Attr &&
11632               ((TUK == TUK_Reference &&
11633                 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
11634                || TUK == TUK_Friend))
11635             return PrevTagDecl;
11636 
11637           // Diagnose attempts to redefine a tag.
11638           if (TUK == TUK_Definition) {
11639             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
11640               // If we're defining a specialization and the previous definition
11641               // is from an implicit instantiation, don't emit an error
11642               // here; we'll catch this in the general case below.
11643               bool IsExplicitSpecializationAfterInstantiation = false;
11644               if (isExplicitSpecialization) {
11645                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
11646                   IsExplicitSpecializationAfterInstantiation =
11647                     RD->getTemplateSpecializationKind() !=
11648                     TSK_ExplicitSpecialization;
11649                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
11650                   IsExplicitSpecializationAfterInstantiation =
11651                     ED->getTemplateSpecializationKind() !=
11652                     TSK_ExplicitSpecialization;
11653               }
11654 
11655               if (!IsExplicitSpecializationAfterInstantiation) {
11656                 // A redeclaration in function prototype scope in C isn't
11657                 // visible elsewhere, so merely issue a warning.
11658                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
11659                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
11660                 else
11661                   Diag(NameLoc, diag::err_redefinition) << Name;
11662                 Diag(Def->getLocation(), diag::note_previous_definition);
11663                 // If this is a redefinition, recover by making this
11664                 // struct be anonymous, which will make any later
11665                 // references get the previous definition.
11666                 Name = nullptr;
11667                 Previous.clear();
11668                 Invalid = true;
11669               }
11670             } else {
11671               // If the type is currently being defined, complain
11672               // about a nested redefinition.
11673               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
11674               if (TD->isBeingDefined()) {
11675                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
11676                 Diag(PrevTagDecl->getLocation(),
11677                      diag::note_previous_definition);
11678                 Name = nullptr;
11679                 Previous.clear();
11680                 Invalid = true;
11681               }
11682             }
11683 
11684             // Okay, this is definition of a previously declared or referenced
11685             // tag. We're going to create a new Decl for it.
11686           }
11687 
11688           // Okay, we're going to make a redeclaration.  If this is some kind
11689           // of reference, make sure we build the redeclaration in the same DC
11690           // as the original, and ignore the current access specifier.
11691           if (TUK == TUK_Friend || TUK == TUK_Reference) {
11692             SearchDC = PrevTagDecl->getDeclContext();
11693             AS = AS_none;
11694           }
11695         }
11696         // If we get here we have (another) forward declaration or we
11697         // have a definition.  Just create a new decl.
11698 
11699       } else {
11700         // If we get here, this is a definition of a new tag type in a nested
11701         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
11702         // new decl/type.  We set PrevDecl to NULL so that the entities
11703         // have distinct types.
11704         Previous.clear();
11705       }
11706       // If we get here, we're going to create a new Decl. If PrevDecl
11707       // is non-NULL, it's a definition of the tag declared by
11708       // PrevDecl. If it's NULL, we have a new definition.
11709 
11710 
11711     // Otherwise, PrevDecl is not a tag, but was found with tag
11712     // lookup.  This is only actually possible in C++, where a few
11713     // things like templates still live in the tag namespace.
11714     } else {
11715       // Use a better diagnostic if an elaborated-type-specifier
11716       // found the wrong kind of type on the first
11717       // (non-redeclaration) lookup.
11718       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
11719           !Previous.isForRedeclaration()) {
11720         unsigned Kind = 0;
11721         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11722         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11723         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11724         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
11725         Diag(PrevDecl->getLocation(), diag::note_declared_at);
11726         Invalid = true;
11727 
11728       // Otherwise, only diagnose if the declaration is in scope.
11729       } else if (!isDeclInScope(PrevDecl, SearchDC, S,
11730                                 SS.isNotEmpty() || isExplicitSpecialization)) {
11731         // do nothing
11732 
11733       // Diagnose implicit declarations introduced by elaborated types.
11734       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
11735         unsigned Kind = 0;
11736         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11737         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11738         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11739         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
11740         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11741         Invalid = true;
11742 
11743       // Otherwise it's a declaration.  Call out a particularly common
11744       // case here.
11745       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11746         unsigned Kind = 0;
11747         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
11748         Diag(NameLoc, diag::err_tag_definition_of_typedef)
11749           << Name << Kind << TND->getUnderlyingType();
11750         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11751         Invalid = true;
11752 
11753       // Otherwise, diagnose.
11754       } else {
11755         // The tag name clashes with something else in the target scope,
11756         // issue an error and recover by making this tag be anonymous.
11757         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
11758         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11759         Name = nullptr;
11760         Invalid = true;
11761       }
11762 
11763       // The existing declaration isn't relevant to us; we're in a
11764       // new scope, so clear out the previous declaration.
11765       Previous.clear();
11766     }
11767   }
11768 
11769 CreateNewDecl:
11770 
11771   TagDecl *PrevDecl = nullptr;
11772   if (Previous.isSingleResult())
11773     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
11774 
11775   // If there is an identifier, use the location of the identifier as the
11776   // location of the decl, otherwise use the location of the struct/union
11777   // keyword.
11778   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
11779 
11780   // Otherwise, create a new declaration. If there is a previous
11781   // declaration of the same entity, the two will be linked via
11782   // PrevDecl.
11783   TagDecl *New;
11784 
11785   bool IsForwardReference = false;
11786   if (Kind == TTK_Enum) {
11787     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11788     // enum X { A, B, C } D;    D should chain to X.
11789     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
11790                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
11791                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
11792     // If this is an undefined enum, warn.
11793     if (TUK != TUK_Definition && !Invalid) {
11794       TagDecl *Def;
11795       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
11796           cast<EnumDecl>(New)->isFixed()) {
11797         // C++0x: 7.2p2: opaque-enum-declaration.
11798         // Conflicts are diagnosed above. Do nothing.
11799       }
11800       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
11801         Diag(Loc, diag::ext_forward_ref_enum_def)
11802           << New;
11803         Diag(Def->getLocation(), diag::note_previous_definition);
11804       } else {
11805         unsigned DiagID = diag::ext_forward_ref_enum;
11806         if (getLangOpts().MSVCCompat)
11807           DiagID = diag::ext_ms_forward_ref_enum;
11808         else if (getLangOpts().CPlusPlus)
11809           DiagID = diag::err_forward_ref_enum;
11810         Diag(Loc, DiagID);
11811 
11812         // If this is a forward-declared reference to an enumeration, make a
11813         // note of it; we won't actually be introducing the declaration into
11814         // the declaration context.
11815         if (TUK == TUK_Reference)
11816           IsForwardReference = true;
11817       }
11818     }
11819 
11820     if (EnumUnderlying) {
11821       EnumDecl *ED = cast<EnumDecl>(New);
11822       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11823         ED->setIntegerTypeSourceInfo(TI);
11824       else
11825         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
11826       ED->setPromotionType(ED->getIntegerType());
11827     }
11828 
11829   } else {
11830     // struct/union/class
11831 
11832     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11833     // struct X { int A; } D;    D should chain to X.
11834     if (getLangOpts().CPlusPlus) {
11835       // FIXME: Look for a way to use RecordDecl for simple structs.
11836       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11837                                   cast_or_null<CXXRecordDecl>(PrevDecl));
11838 
11839       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
11840         StdBadAlloc = cast<CXXRecordDecl>(New);
11841     } else
11842       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11843                                cast_or_null<RecordDecl>(PrevDecl));
11844   }
11845 
11846   // C++11 [dcl.type]p3:
11847   //   A type-specifier-seq shall not define a class or enumeration [...].
11848   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11849     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11850       << Context.getTagDeclType(New);
11851     Invalid = true;
11852   }
11853 
11854   // Maybe add qualifier info.
11855   if (SS.isNotEmpty()) {
11856     if (SS.isSet()) {
11857       // If this is either a declaration or a definition, check the
11858       // nested-name-specifier against the current context. We don't do this
11859       // for explicit specializations, because they have similar checking
11860       // (with more specific diagnostics) in the call to
11861       // CheckMemberSpecialization, below.
11862       if (!isExplicitSpecialization &&
11863           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11864           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
11865         Invalid = true;
11866 
11867       New->setQualifierInfo(SS.getWithLocInContext(Context));
11868       if (TemplateParameterLists.size() > 0) {
11869         New->setTemplateParameterListsInfo(Context,
11870                                            TemplateParameterLists.size(),
11871                                            TemplateParameterLists.data());
11872       }
11873     }
11874     else
11875       Invalid = true;
11876   }
11877 
11878   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11879     // Add alignment attributes if necessary; these attributes are checked when
11880     // the ASTContext lays out the structure.
11881     //
11882     // It is important for implementing the correct semantics that this
11883     // happen here (in act on tag decl). The #pragma pack stack is
11884     // maintained as a result of parser callbacks which can occur at
11885     // many points during the parsing of a struct declaration (because
11886     // the #pragma tokens are effectively skipped over during the
11887     // parsing of the struct).
11888     if (TUK == TUK_Definition) {
11889       AddAlignmentAttributesForRecord(RD);
11890       AddMsStructLayoutForRecord(RD);
11891     }
11892   }
11893 
11894   if (ModulePrivateLoc.isValid()) {
11895     if (isExplicitSpecialization)
11896       Diag(New->getLocation(), diag::err_module_private_specialization)
11897         << 2
11898         << FixItHint::CreateRemoval(ModulePrivateLoc);
11899     // __module_private__ does not apply to local classes. However, we only
11900     // diagnose this as an error when the declaration specifiers are
11901     // freestanding. Here, we just ignore the __module_private__.
11902     else if (!SearchDC->isFunctionOrMethod())
11903       New->setModulePrivate();
11904   }
11905 
11906   // If this is a specialization of a member class (of a class template),
11907   // check the specialization.
11908   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
11909     Invalid = true;
11910 
11911   // If we're declaring or defining a tag in function prototype scope in C,
11912   // note that this type can only be used within the function and add it to
11913   // the list of decls to inject into the function definition scope.
11914   if ((Name || Kind == TTK_Enum) &&
11915       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
11916     if (getLangOpts().CPlusPlus) {
11917       // C++ [dcl.fct]p6:
11918       //   Types shall not be defined in return or parameter types.
11919       if (TUK == TUK_Definition && !IsTypeSpecifier) {
11920         Diag(Loc, diag::err_type_defined_in_param_type)
11921             << Name;
11922         Invalid = true;
11923       }
11924     } else {
11925       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11926     }
11927     DeclsInPrototypeScope.push_back(New);
11928   }
11929 
11930   if (Invalid)
11931     New->setInvalidDecl();
11932 
11933   if (Attr)
11934     ProcessDeclAttributeList(S, New, Attr);
11935 
11936   // Set the lexical context. If the tag has a C++ scope specifier, the
11937   // lexical context will be different from the semantic context.
11938   New->setLexicalDeclContext(CurContext);
11939 
11940   // Mark this as a friend decl if applicable.
11941   // In Microsoft mode, a friend declaration also acts as a forward
11942   // declaration so we always pass true to setObjectOfFriendDecl to make
11943   // the tag name visible.
11944   if (TUK == TUK_Friend)
11945     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
11946 
11947   // Set the access specifier.
11948   if (!Invalid && SearchDC->isRecord())
11949     SetMemberAccessSpecifier(New, PrevDecl, AS);
11950 
11951   if (TUK == TUK_Definition)
11952     New->startDefinition();
11953 
11954   // If this has an identifier, add it to the scope stack.
11955   if (TUK == TUK_Friend) {
11956     // We might be replacing an existing declaration in the lookup tables;
11957     // if so, borrow its access specifier.
11958     if (PrevDecl)
11959       New->setAccess(PrevDecl->getAccess());
11960 
11961     DeclContext *DC = New->getDeclContext()->getRedeclContext();
11962     DC->makeDeclVisibleInContext(New);
11963     if (Name) // can be null along some error paths
11964       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11965         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
11966   } else if (Name) {
11967     S = getNonFieldDeclScope(S);
11968     PushOnScopeChains(New, S, !IsForwardReference);
11969     if (IsForwardReference)
11970       SearchDC->makeDeclVisibleInContext(New);
11971 
11972   } else {
11973     CurContext->addDecl(New);
11974   }
11975 
11976   // If this is the C FILE type, notify the AST context.
11977   if (IdentifierInfo *II = New->getIdentifier())
11978     if (!New->isInvalidDecl() &&
11979         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
11980         II->isStr("FILE"))
11981       Context.setFILEDecl(New);
11982 
11983   if (PrevDecl)
11984     mergeDeclAttributes(New, PrevDecl);
11985 
11986   // If there's a #pragma GCC visibility in scope, set the visibility of this
11987   // record.
11988   AddPushedVisibilityAttribute(New);
11989 
11990   OwnedDecl = true;
11991   // In C++, don't return an invalid declaration. We can't recover well from
11992   // the cases where we make the type anonymous.
11993   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
11994 }
11995 
11996 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
11997   AdjustDeclIfTemplate(TagD);
11998   TagDecl *Tag = cast<TagDecl>(TagD);
11999 
12000   // Enter the tag context.
12001   PushDeclContext(S, Tag);
12002 
12003   ActOnDocumentableDecl(TagD);
12004 
12005   // If there's a #pragma GCC visibility in scope, set the visibility of this
12006   // record.
12007   AddPushedVisibilityAttribute(Tag);
12008 }
12009 
12010 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
12011   assert(isa<ObjCContainerDecl>(IDecl) &&
12012          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
12013   DeclContext *OCD = cast<DeclContext>(IDecl);
12014   assert(getContainingDC(OCD) == CurContext &&
12015       "The next DeclContext should be lexically contained in the current one.");
12016   CurContext = OCD;
12017   return IDecl;
12018 }
12019 
12020 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
12021                                            SourceLocation FinalLoc,
12022                                            bool IsFinalSpelledSealed,
12023                                            SourceLocation LBraceLoc) {
12024   AdjustDeclIfTemplate(TagD);
12025   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
12026 
12027   FieldCollector->StartClass();
12028 
12029   if (!Record->getIdentifier())
12030     return;
12031 
12032   if (FinalLoc.isValid())
12033     Record->addAttr(new (Context)
12034                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
12035 
12036   // C++ [class]p2:
12037   //   [...] The class-name is also inserted into the scope of the
12038   //   class itself; this is known as the injected-class-name. For
12039   //   purposes of access checking, the injected-class-name is treated
12040   //   as if it were a public member name.
12041   CXXRecordDecl *InjectedClassName
12042     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
12043                             Record->getLocStart(), Record->getLocation(),
12044                             Record->getIdentifier(),
12045                             /*PrevDecl=*/nullptr,
12046                             /*DelayTypeCreation=*/true);
12047   Context.getTypeDeclType(InjectedClassName, Record);
12048   InjectedClassName->setImplicit();
12049   InjectedClassName->setAccess(AS_public);
12050   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
12051       InjectedClassName->setDescribedClassTemplate(Template);
12052   PushOnScopeChains(InjectedClassName, S);
12053   assert(InjectedClassName->isInjectedClassName() &&
12054          "Broken injected-class-name");
12055 }
12056 
12057 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
12058                                     SourceLocation RBraceLoc) {
12059   AdjustDeclIfTemplate(TagD);
12060   TagDecl *Tag = cast<TagDecl>(TagD);
12061   Tag->setRBraceLoc(RBraceLoc);
12062 
12063   // Make sure we "complete" the definition even it is invalid.
12064   if (Tag->isBeingDefined()) {
12065     assert(Tag->isInvalidDecl() && "We should already have completed it");
12066     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12067       RD->completeDefinition();
12068   }
12069 
12070   if (isa<CXXRecordDecl>(Tag))
12071     FieldCollector->FinishClass();
12072 
12073   // Exit this scope of this tag's definition.
12074   PopDeclContext();
12075 
12076   if (getCurLexicalContext()->isObjCContainer() &&
12077       Tag->getDeclContext()->isFileContext())
12078     Tag->setTopLevelDeclInObjCContainer();
12079 
12080   // Notify the consumer that we've defined a tag.
12081   if (!Tag->isInvalidDecl())
12082     Consumer.HandleTagDeclDefinition(Tag);
12083 }
12084 
12085 void Sema::ActOnObjCContainerFinishDefinition() {
12086   // Exit this scope of this interface definition.
12087   PopDeclContext();
12088 }
12089 
12090 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
12091   assert(DC == CurContext && "Mismatch of container contexts");
12092   OriginalLexicalContext = DC;
12093   ActOnObjCContainerFinishDefinition();
12094 }
12095 
12096 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
12097   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
12098   OriginalLexicalContext = nullptr;
12099 }
12100 
12101 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
12102   AdjustDeclIfTemplate(TagD);
12103   TagDecl *Tag = cast<TagDecl>(TagD);
12104   Tag->setInvalidDecl();
12105 
12106   // Make sure we "complete" the definition even it is invalid.
12107   if (Tag->isBeingDefined()) {
12108     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12109       RD->completeDefinition();
12110   }
12111 
12112   // We're undoing ActOnTagStartDefinition here, not
12113   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
12114   // the FieldCollector.
12115 
12116   PopDeclContext();
12117 }
12118 
12119 // Note that FieldName may be null for anonymous bitfields.
12120 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
12121                                 IdentifierInfo *FieldName,
12122                                 QualType FieldTy, bool IsMsStruct,
12123                                 Expr *BitWidth, bool *ZeroWidth) {
12124   // Default to true; that shouldn't confuse checks for emptiness
12125   if (ZeroWidth)
12126     *ZeroWidth = true;
12127 
12128   // C99 6.7.2.1p4 - verify the field type.
12129   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
12130   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
12131     // Handle incomplete types with specific error.
12132     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
12133       return ExprError();
12134     if (FieldName)
12135       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12136         << FieldName << FieldTy << BitWidth->getSourceRange();
12137     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12138       << FieldTy << BitWidth->getSourceRange();
12139   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12140                                              UPPC_BitFieldWidth))
12141     return ExprError();
12142 
12143   // If the bit-width is type- or value-dependent, don't try to check
12144   // it now.
12145   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
12146     return BitWidth;
12147 
12148   llvm::APSInt Value;
12149   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
12150   if (ICE.isInvalid())
12151     return ICE;
12152   BitWidth = ICE.get();
12153 
12154   if (Value != 0 && ZeroWidth)
12155     *ZeroWidth = false;
12156 
12157   // Zero-width bitfield is ok for anonymous field.
12158   if (Value == 0 && FieldName)
12159     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
12160 
12161   if (Value.isSigned() && Value.isNegative()) {
12162     if (FieldName)
12163       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
12164                << FieldName << Value.toString(10);
12165     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
12166       << Value.toString(10);
12167   }
12168 
12169   if (!FieldTy->isDependentType()) {
12170     uint64_t TypeSize = Context.getTypeSize(FieldTy);
12171     if (Value.getZExtValue() > TypeSize) {
12172       if (!getLangOpts().CPlusPlus || IsMsStruct ||
12173           Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12174         if (FieldName)
12175           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
12176             << FieldName << (unsigned)Value.getZExtValue()
12177             << (unsigned)TypeSize;
12178 
12179         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
12180           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12181       }
12182 
12183       if (FieldName)
12184         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
12185           << FieldName << (unsigned)Value.getZExtValue()
12186           << (unsigned)TypeSize;
12187       else
12188         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
12189           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12190     }
12191   }
12192 
12193   return BitWidth;
12194 }
12195 
12196 /// ActOnField - Each field of a C struct/union is passed into this in order
12197 /// to create a FieldDecl object for it.
12198 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
12199                        Declarator &D, Expr *BitfieldWidth) {
12200   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
12201                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
12202                                /*InitStyle=*/ICIS_NoInit, AS_public);
12203   return Res;
12204 }
12205 
12206 /// HandleField - Analyze a field of a C struct or a C++ data member.
12207 ///
12208 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
12209                              SourceLocation DeclStart,
12210                              Declarator &D, Expr *BitWidth,
12211                              InClassInitStyle InitStyle,
12212                              AccessSpecifier AS) {
12213   IdentifierInfo *II = D.getIdentifier();
12214   SourceLocation Loc = DeclStart;
12215   if (II) Loc = D.getIdentifierLoc();
12216 
12217   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12218   QualType T = TInfo->getType();
12219   if (getLangOpts().CPlusPlus) {
12220     CheckExtraCXXDefaultArguments(D);
12221 
12222     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12223                                         UPPC_DataMemberType)) {
12224       D.setInvalidType();
12225       T = Context.IntTy;
12226       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12227     }
12228   }
12229 
12230   // TR 18037 does not allow fields to be declared with address spaces.
12231   if (T.getQualifiers().hasAddressSpace()) {
12232     Diag(Loc, diag::err_field_with_address_space);
12233     D.setInvalidType();
12234   }
12235 
12236   // OpenCL 1.2 spec, s6.9 r:
12237   // The event type cannot be used to declare a structure or union field.
12238   if (LangOpts.OpenCL && T->isEventT()) {
12239     Diag(Loc, diag::err_event_t_struct_field);
12240     D.setInvalidType();
12241   }
12242 
12243   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12244 
12245   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12246     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12247          diag::err_invalid_thread)
12248       << DeclSpec::getSpecifierName(TSCS);
12249 
12250   // Check to see if this name was declared as a member previously
12251   NamedDecl *PrevDecl = nullptr;
12252   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12253   LookupName(Previous, S);
12254   switch (Previous.getResultKind()) {
12255     case LookupResult::Found:
12256     case LookupResult::FoundUnresolvedValue:
12257       PrevDecl = Previous.getAsSingle<NamedDecl>();
12258       break;
12259 
12260     case LookupResult::FoundOverloaded:
12261       PrevDecl = Previous.getRepresentativeDecl();
12262       break;
12263 
12264     case LookupResult::NotFound:
12265     case LookupResult::NotFoundInCurrentInstantiation:
12266     case LookupResult::Ambiguous:
12267       break;
12268   }
12269   Previous.suppressDiagnostics();
12270 
12271   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12272     // Maybe we will complain about the shadowed template parameter.
12273     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12274     // Just pretend that we didn't see the previous declaration.
12275     PrevDecl = nullptr;
12276   }
12277 
12278   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12279     PrevDecl = nullptr;
12280 
12281   bool Mutable
12282     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
12283   SourceLocation TSSL = D.getLocStart();
12284   FieldDecl *NewFD
12285     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
12286                      TSSL, AS, PrevDecl, &D);
12287 
12288   if (NewFD->isInvalidDecl())
12289     Record->setInvalidDecl();
12290 
12291   if (D.getDeclSpec().isModulePrivateSpecified())
12292     NewFD->setModulePrivate();
12293 
12294   if (NewFD->isInvalidDecl() && PrevDecl) {
12295     // Don't introduce NewFD into scope; there's already something
12296     // with the same name in the same scope.
12297   } else if (II) {
12298     PushOnScopeChains(NewFD, S);
12299   } else
12300     Record->addDecl(NewFD);
12301 
12302   return NewFD;
12303 }
12304 
12305 /// \brief Build a new FieldDecl and check its well-formedness.
12306 ///
12307 /// This routine builds a new FieldDecl given the fields name, type,
12308 /// record, etc. \p PrevDecl should refer to any previous declaration
12309 /// with the same name and in the same scope as the field to be
12310 /// created.
12311 ///
12312 /// \returns a new FieldDecl.
12313 ///
12314 /// \todo The Declarator argument is a hack. It will be removed once
12315 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
12316                                 TypeSourceInfo *TInfo,
12317                                 RecordDecl *Record, SourceLocation Loc,
12318                                 bool Mutable, Expr *BitWidth,
12319                                 InClassInitStyle InitStyle,
12320                                 SourceLocation TSSL,
12321                                 AccessSpecifier AS, NamedDecl *PrevDecl,
12322                                 Declarator *D) {
12323   IdentifierInfo *II = Name.getAsIdentifierInfo();
12324   bool InvalidDecl = false;
12325   if (D) InvalidDecl = D->isInvalidType();
12326 
12327   // If we receive a broken type, recover by assuming 'int' and
12328   // marking this declaration as invalid.
12329   if (T.isNull()) {
12330     InvalidDecl = true;
12331     T = Context.IntTy;
12332   }
12333 
12334   QualType EltTy = Context.getBaseElementType(T);
12335   if (!EltTy->isDependentType()) {
12336     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
12337       // Fields of incomplete type force their record to be invalid.
12338       Record->setInvalidDecl();
12339       InvalidDecl = true;
12340     } else {
12341       NamedDecl *Def;
12342       EltTy->isIncompleteType(&Def);
12343       if (Def && Def->isInvalidDecl()) {
12344         Record->setInvalidDecl();
12345         InvalidDecl = true;
12346       }
12347     }
12348   }
12349 
12350   // OpenCL v1.2 s6.9.c: bitfields are not supported.
12351   if (BitWidth && getLangOpts().OpenCL) {
12352     Diag(Loc, diag::err_opencl_bitfields);
12353     InvalidDecl = true;
12354   }
12355 
12356   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12357   // than a variably modified type.
12358   if (!InvalidDecl && T->isVariablyModifiedType()) {
12359     bool SizeIsNegative;
12360     llvm::APSInt Oversized;
12361 
12362     TypeSourceInfo *FixedTInfo =
12363       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
12364                                                     SizeIsNegative,
12365                                                     Oversized);
12366     if (FixedTInfo) {
12367       Diag(Loc, diag::warn_illegal_constant_array_size);
12368       TInfo = FixedTInfo;
12369       T = FixedTInfo->getType();
12370     } else {
12371       if (SizeIsNegative)
12372         Diag(Loc, diag::err_typecheck_negative_array_size);
12373       else if (Oversized.getBoolValue())
12374         Diag(Loc, diag::err_array_too_large)
12375           << Oversized.toString(10);
12376       else
12377         Diag(Loc, diag::err_typecheck_field_variable_size);
12378       InvalidDecl = true;
12379     }
12380   }
12381 
12382   // Fields can not have abstract class types
12383   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
12384                                              diag::err_abstract_type_in_decl,
12385                                              AbstractFieldType))
12386     InvalidDecl = true;
12387 
12388   bool ZeroWidth = false;
12389   // If this is declared as a bit-field, check the bit-field.
12390   if (!InvalidDecl && BitWidth) {
12391     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
12392                               &ZeroWidth).get();
12393     if (!BitWidth) {
12394       InvalidDecl = true;
12395       BitWidth = nullptr;
12396       ZeroWidth = false;
12397     }
12398   }
12399 
12400   // Check that 'mutable' is consistent with the type of the declaration.
12401   if (!InvalidDecl && Mutable) {
12402     unsigned DiagID = 0;
12403     if (T->isReferenceType())
12404       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
12405                                         : diag::err_mutable_reference;
12406     else if (T.isConstQualified())
12407       DiagID = diag::err_mutable_const;
12408 
12409     if (DiagID) {
12410       SourceLocation ErrLoc = Loc;
12411       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
12412         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
12413       Diag(ErrLoc, DiagID);
12414       if (DiagID != diag::ext_mutable_reference) {
12415         Mutable = false;
12416         InvalidDecl = true;
12417       }
12418     }
12419   }
12420 
12421   // C++11 [class.union]p8 (DR1460):
12422   //   At most one variant member of a union may have a
12423   //   brace-or-equal-initializer.
12424   if (InitStyle != ICIS_NoInit)
12425     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
12426 
12427   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
12428                                        BitWidth, Mutable, InitStyle);
12429   if (InvalidDecl)
12430     NewFD->setInvalidDecl();
12431 
12432   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
12433     Diag(Loc, diag::err_duplicate_member) << II;
12434     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12435     NewFD->setInvalidDecl();
12436   }
12437 
12438   if (!InvalidDecl && getLangOpts().CPlusPlus) {
12439     if (Record->isUnion()) {
12440       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12441         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
12442         if (RDecl->getDefinition()) {
12443           // C++ [class.union]p1: An object of a class with a non-trivial
12444           // constructor, a non-trivial copy constructor, a non-trivial
12445           // destructor, or a non-trivial copy assignment operator
12446           // cannot be a member of a union, nor can an array of such
12447           // objects.
12448           if (CheckNontrivialField(NewFD))
12449             NewFD->setInvalidDecl();
12450         }
12451       }
12452 
12453       // C++ [class.union]p1: If a union contains a member of reference type,
12454       // the program is ill-formed, except when compiling with MSVC extensions
12455       // enabled.
12456       if (EltTy->isReferenceType()) {
12457         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
12458                                     diag::ext_union_member_of_reference_type :
12459                                     diag::err_union_member_of_reference_type)
12460           << NewFD->getDeclName() << EltTy;
12461         if (!getLangOpts().MicrosoftExt)
12462           NewFD->setInvalidDecl();
12463       }
12464     }
12465   }
12466 
12467   // FIXME: We need to pass in the attributes given an AST
12468   // representation, not a parser representation.
12469   if (D) {
12470     // FIXME: The current scope is almost... but not entirely... correct here.
12471     ProcessDeclAttributes(getCurScope(), NewFD, *D);
12472 
12473     if (NewFD->hasAttrs())
12474       CheckAlignasUnderalignment(NewFD);
12475   }
12476 
12477   // In auto-retain/release, infer strong retension for fields of
12478   // retainable type.
12479   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
12480     NewFD->setInvalidDecl();
12481 
12482   if (T.isObjCGCWeak())
12483     Diag(Loc, diag::warn_attribute_weak_on_field);
12484 
12485   NewFD->setAccess(AS);
12486   return NewFD;
12487 }
12488 
12489 bool Sema::CheckNontrivialField(FieldDecl *FD) {
12490   assert(FD);
12491   assert(getLangOpts().CPlusPlus && "valid check only for C++");
12492 
12493   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
12494     return false;
12495 
12496   QualType EltTy = Context.getBaseElementType(FD->getType());
12497   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12498     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
12499     if (RDecl->getDefinition()) {
12500       // We check for copy constructors before constructors
12501       // because otherwise we'll never get complaints about
12502       // copy constructors.
12503 
12504       CXXSpecialMember member = CXXInvalid;
12505       // We're required to check for any non-trivial constructors. Since the
12506       // implicit default constructor is suppressed if there are any
12507       // user-declared constructors, we just need to check that there is a
12508       // trivial default constructor and a trivial copy constructor. (We don't
12509       // worry about move constructors here, since this is a C++98 check.)
12510       if (RDecl->hasNonTrivialCopyConstructor())
12511         member = CXXCopyConstructor;
12512       else if (!RDecl->hasTrivialDefaultConstructor())
12513         member = CXXDefaultConstructor;
12514       else if (RDecl->hasNonTrivialCopyAssignment())
12515         member = CXXCopyAssignment;
12516       else if (RDecl->hasNonTrivialDestructor())
12517         member = CXXDestructor;
12518 
12519       if (member != CXXInvalid) {
12520         if (!getLangOpts().CPlusPlus11 &&
12521             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
12522           // Objective-C++ ARC: it is an error to have a non-trivial field of
12523           // a union. However, system headers in Objective-C programs
12524           // occasionally have Objective-C lifetime objects within unions,
12525           // and rather than cause the program to fail, we make those
12526           // members unavailable.
12527           SourceLocation Loc = FD->getLocation();
12528           if (getSourceManager().isInSystemHeader(Loc)) {
12529             if (!FD->hasAttr<UnavailableAttr>())
12530               FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12531                                   "this system field has retaining ownership",
12532                                   Loc));
12533             return false;
12534           }
12535         }
12536 
12537         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
12538                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
12539                diag::err_illegal_union_or_anon_struct_member)
12540           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
12541         DiagnoseNontrivial(RDecl, member);
12542         return !getLangOpts().CPlusPlus11;
12543       }
12544     }
12545   }
12546 
12547   return false;
12548 }
12549 
12550 /// TranslateIvarVisibility - Translate visibility from a token ID to an
12551 ///  AST enum value.
12552 static ObjCIvarDecl::AccessControl
12553 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
12554   switch (ivarVisibility) {
12555   default: llvm_unreachable("Unknown visitibility kind");
12556   case tok::objc_private: return ObjCIvarDecl::Private;
12557   case tok::objc_public: return ObjCIvarDecl::Public;
12558   case tok::objc_protected: return ObjCIvarDecl::Protected;
12559   case tok::objc_package: return ObjCIvarDecl::Package;
12560   }
12561 }
12562 
12563 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
12564 /// in order to create an IvarDecl object for it.
12565 Decl *Sema::ActOnIvar(Scope *S,
12566                                 SourceLocation DeclStart,
12567                                 Declarator &D, Expr *BitfieldWidth,
12568                                 tok::ObjCKeywordKind Visibility) {
12569 
12570   IdentifierInfo *II = D.getIdentifier();
12571   Expr *BitWidth = (Expr*)BitfieldWidth;
12572   SourceLocation Loc = DeclStart;
12573   if (II) Loc = D.getIdentifierLoc();
12574 
12575   // FIXME: Unnamed fields can be handled in various different ways, for
12576   // example, unnamed unions inject all members into the struct namespace!
12577 
12578   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12579   QualType T = TInfo->getType();
12580 
12581   if (BitWidth) {
12582     // 6.7.2.1p3, 6.7.2.1p4
12583     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
12584     if (!BitWidth)
12585       D.setInvalidType();
12586   } else {
12587     // Not a bitfield.
12588 
12589     // validate II.
12590 
12591   }
12592   if (T->isReferenceType()) {
12593     Diag(Loc, diag::err_ivar_reference_type);
12594     D.setInvalidType();
12595   }
12596   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12597   // than a variably modified type.
12598   else if (T->isVariablyModifiedType()) {
12599     Diag(Loc, diag::err_typecheck_ivar_variable_size);
12600     D.setInvalidType();
12601   }
12602 
12603   // Get the visibility (access control) for this ivar.
12604   ObjCIvarDecl::AccessControl ac =
12605     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
12606                                         : ObjCIvarDecl::None;
12607   // Must set ivar's DeclContext to its enclosing interface.
12608   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
12609   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
12610     return nullptr;
12611   ObjCContainerDecl *EnclosingContext;
12612   if (ObjCImplementationDecl *IMPDecl =
12613       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12614     if (LangOpts.ObjCRuntime.isFragile()) {
12615     // Case of ivar declared in an implementation. Context is that of its class.
12616       EnclosingContext = IMPDecl->getClassInterface();
12617       assert(EnclosingContext && "Implementation has no class interface!");
12618     }
12619     else
12620       EnclosingContext = EnclosingDecl;
12621   } else {
12622     if (ObjCCategoryDecl *CDecl =
12623         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12624       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
12625         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
12626         return nullptr;
12627       }
12628     }
12629     EnclosingContext = EnclosingDecl;
12630   }
12631 
12632   // Construct the decl.
12633   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
12634                                              DeclStart, Loc, II, T,
12635                                              TInfo, ac, (Expr *)BitfieldWidth);
12636 
12637   if (II) {
12638     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
12639                                            ForRedeclaration);
12640     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
12641         && !isa<TagDecl>(PrevDecl)) {
12642       Diag(Loc, diag::err_duplicate_member) << II;
12643       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12644       NewID->setInvalidDecl();
12645     }
12646   }
12647 
12648   // Process attributes attached to the ivar.
12649   ProcessDeclAttributes(S, NewID, D);
12650 
12651   if (D.isInvalidType())
12652     NewID->setInvalidDecl();
12653 
12654   // In ARC, infer 'retaining' for ivars of retainable type.
12655   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
12656     NewID->setInvalidDecl();
12657 
12658   if (D.getDeclSpec().isModulePrivateSpecified())
12659     NewID->setModulePrivate();
12660 
12661   if (II) {
12662     // FIXME: When interfaces are DeclContexts, we'll need to add
12663     // these to the interface.
12664     S->AddDecl(NewID);
12665     IdResolver.AddDecl(NewID);
12666   }
12667 
12668   if (LangOpts.ObjCRuntime.isNonFragile() &&
12669       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
12670     Diag(Loc, diag::warn_ivars_in_interface);
12671 
12672   return NewID;
12673 }
12674 
12675 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
12676 /// class and class extensions. For every class \@interface and class
12677 /// extension \@interface, if the last ivar is a bitfield of any type,
12678 /// then add an implicit `char :0` ivar to the end of that interface.
12679 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
12680                              SmallVectorImpl<Decl *> &AllIvarDecls) {
12681   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
12682     return;
12683 
12684   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
12685   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
12686 
12687   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
12688     return;
12689   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
12690   if (!ID) {
12691     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
12692       if (!CD->IsClassExtension())
12693         return;
12694     }
12695     // No need to add this to end of @implementation.
12696     else
12697       return;
12698   }
12699   // All conditions are met. Add a new bitfield to the tail end of ivars.
12700   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
12701   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
12702 
12703   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
12704                               DeclLoc, DeclLoc, nullptr,
12705                               Context.CharTy,
12706                               Context.getTrivialTypeSourceInfo(Context.CharTy,
12707                                                                DeclLoc),
12708                               ObjCIvarDecl::Private, BW,
12709                               true);
12710   AllIvarDecls.push_back(Ivar);
12711 }
12712 
12713 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
12714                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
12715                        SourceLocation RBrac, AttributeList *Attr) {
12716   assert(EnclosingDecl && "missing record or interface decl");
12717 
12718   // If this is an Objective-C @implementation or category and we have
12719   // new fields here we should reset the layout of the interface since
12720   // it will now change.
12721   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
12722     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
12723     switch (DC->getKind()) {
12724     default: break;
12725     case Decl::ObjCCategory:
12726       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
12727       break;
12728     case Decl::ObjCImplementation:
12729       Context.
12730         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
12731       break;
12732     }
12733   }
12734 
12735   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
12736 
12737   // Start counting up the number of named members; make sure to include
12738   // members of anonymous structs and unions in the total.
12739   unsigned NumNamedMembers = 0;
12740   if (Record) {
12741     for (const auto *I : Record->decls()) {
12742       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
12743         if (IFD->getDeclName())
12744           ++NumNamedMembers;
12745     }
12746   }
12747 
12748   // Verify that all the fields are okay.
12749   SmallVector<FieldDecl*, 32> RecFields;
12750 
12751   bool ARCErrReported = false;
12752   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
12753        i != end; ++i) {
12754     FieldDecl *FD = cast<FieldDecl>(*i);
12755 
12756     // Get the type for the field.
12757     const Type *FDTy = FD->getType().getTypePtr();
12758 
12759     if (!FD->isAnonymousStructOrUnion()) {
12760       // Remember all fields written by the user.
12761       RecFields.push_back(FD);
12762     }
12763 
12764     // If the field is already invalid for some reason, don't emit more
12765     // diagnostics about it.
12766     if (FD->isInvalidDecl()) {
12767       EnclosingDecl->setInvalidDecl();
12768       continue;
12769     }
12770 
12771     // C99 6.7.2.1p2:
12772     //   A structure or union shall not contain a member with
12773     //   incomplete or function type (hence, a structure shall not
12774     //   contain an instance of itself, but may contain a pointer to
12775     //   an instance of itself), except that the last member of a
12776     //   structure with more than one named member may have incomplete
12777     //   array type; such a structure (and any union containing,
12778     //   possibly recursively, a member that is such a structure)
12779     //   shall not be a member of a structure or an element of an
12780     //   array.
12781     if (FDTy->isFunctionType()) {
12782       // Field declared as a function.
12783       Diag(FD->getLocation(), diag::err_field_declared_as_function)
12784         << FD->getDeclName();
12785       FD->setInvalidDecl();
12786       EnclosingDecl->setInvalidDecl();
12787       continue;
12788     } else if (FDTy->isIncompleteArrayType() && Record &&
12789                ((i + 1 == Fields.end() && !Record->isUnion()) ||
12790                 ((getLangOpts().MicrosoftExt ||
12791                   getLangOpts().CPlusPlus) &&
12792                  (i + 1 == Fields.end() || Record->isUnion())))) {
12793       // Flexible array member.
12794       // Microsoft and g++ is more permissive regarding flexible array.
12795       // It will accept flexible array in union and also
12796       // as the sole element of a struct/class.
12797       unsigned DiagID = 0;
12798       if (Record->isUnion())
12799         DiagID = getLangOpts().MicrosoftExt
12800                      ? diag::ext_flexible_array_union_ms
12801                      : getLangOpts().CPlusPlus
12802                            ? diag::ext_flexible_array_union_gnu
12803                            : diag::err_flexible_array_union;
12804       else if (Fields.size() == 1)
12805         DiagID = getLangOpts().MicrosoftExt
12806                      ? diag::ext_flexible_array_empty_aggregate_ms
12807                      : getLangOpts().CPlusPlus
12808                            ? diag::ext_flexible_array_empty_aggregate_gnu
12809                            : NumNamedMembers < 1
12810                                  ? diag::err_flexible_array_empty_aggregate
12811                                  : 0;
12812 
12813       if (DiagID)
12814         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
12815                                         << Record->getTagKind();
12816       // While the layout of types that contain virtual bases is not specified
12817       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
12818       // virtual bases after the derived members.  This would make a flexible
12819       // array member declared at the end of an object not adjacent to the end
12820       // of the type.
12821       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
12822         if (RD->getNumVBases() != 0)
12823           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
12824             << FD->getDeclName() << Record->getTagKind();
12825       if (!getLangOpts().C99)
12826         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
12827           << FD->getDeclName() << Record->getTagKind();
12828 
12829       // If the element type has a non-trivial destructor, we would not
12830       // implicitly destroy the elements, so disallow it for now.
12831       //
12832       // FIXME: GCC allows this. We should probably either implicitly delete
12833       // the destructor of the containing class, or just allow this.
12834       QualType BaseElem = Context.getBaseElementType(FD->getType());
12835       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
12836         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
12837           << FD->getDeclName() << FD->getType();
12838         FD->setInvalidDecl();
12839         EnclosingDecl->setInvalidDecl();
12840         continue;
12841       }
12842       // Okay, we have a legal flexible array member at the end of the struct.
12843       Record->setHasFlexibleArrayMember(true);
12844     } else if (!FDTy->isDependentType() &&
12845                RequireCompleteType(FD->getLocation(), FD->getType(),
12846                                    diag::err_field_incomplete)) {
12847       // Incomplete type
12848       FD->setInvalidDecl();
12849       EnclosingDecl->setInvalidDecl();
12850       continue;
12851     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
12852       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
12853         // A type which contains a flexible array member is considered to be a
12854         // flexible array member.
12855         Record->setHasFlexibleArrayMember(true);
12856         if (!Record->isUnion()) {
12857           // If this is a struct/class and this is not the last element, reject
12858           // it.  Note that GCC supports variable sized arrays in the middle of
12859           // structures.
12860           if (i + 1 != Fields.end())
12861             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
12862               << FD->getDeclName() << FD->getType();
12863           else {
12864             // We support flexible arrays at the end of structs in
12865             // other structs as an extension.
12866             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12867               << FD->getDeclName();
12868           }
12869         }
12870       }
12871       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12872           RequireNonAbstractType(FD->getLocation(), FD->getType(),
12873                                  diag::err_abstract_type_in_decl,
12874                                  AbstractIvarType)) {
12875         // Ivars can not have abstract class types
12876         FD->setInvalidDecl();
12877       }
12878       if (Record && FDTTy->getDecl()->hasObjectMember())
12879         Record->setHasObjectMember(true);
12880       if (Record && FDTTy->getDecl()->hasVolatileMember())
12881         Record->setHasVolatileMember(true);
12882     } else if (FDTy->isObjCObjectType()) {
12883       /// A field cannot be an Objective-c object
12884       Diag(FD->getLocation(), diag::err_statically_allocated_object)
12885         << FixItHint::CreateInsertion(FD->getLocation(), "*");
12886       QualType T = Context.getObjCObjectPointerType(FD->getType());
12887       FD->setType(T);
12888     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12889                (!getLangOpts().CPlusPlus || Record->isUnion())) {
12890       // It's an error in ARC if a field has lifetime.
12891       // We don't want to report this in a system header, though,
12892       // so we just make the field unavailable.
12893       // FIXME: that's really not sufficient; we need to make the type
12894       // itself invalid to, say, initialize or copy.
12895       QualType T = FD->getType();
12896       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12897       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12898         SourceLocation loc = FD->getLocation();
12899         if (getSourceManager().isInSystemHeader(loc)) {
12900           if (!FD->hasAttr<UnavailableAttr>()) {
12901             FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12902                               "this system field has retaining ownership",
12903                               loc));
12904           }
12905         } else {
12906           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
12907             << T->isBlockPointerType() << Record->getTagKind();
12908         }
12909         ARCErrReported = true;
12910       }
12911     } else if (getLangOpts().ObjC1 &&
12912                getLangOpts().getGC() != LangOptions::NonGC &&
12913                Record && !Record->hasObjectMember()) {
12914       if (FD->getType()->isObjCObjectPointerType() ||
12915           FD->getType().isObjCGCStrong())
12916         Record->setHasObjectMember(true);
12917       else if (Context.getAsArrayType(FD->getType())) {
12918         QualType BaseType = Context.getBaseElementType(FD->getType());
12919         if (BaseType->isRecordType() &&
12920             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
12921           Record->setHasObjectMember(true);
12922         else if (BaseType->isObjCObjectPointerType() ||
12923                  BaseType.isObjCGCStrong())
12924                Record->setHasObjectMember(true);
12925       }
12926     }
12927     if (Record && FD->getType().isVolatileQualified())
12928       Record->setHasVolatileMember(true);
12929     // Keep track of the number of named members.
12930     if (FD->getIdentifier())
12931       ++NumNamedMembers;
12932   }
12933 
12934   // Okay, we successfully defined 'Record'.
12935   if (Record) {
12936     bool Completed = false;
12937     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12938       if (!CXXRecord->isInvalidDecl()) {
12939         // Set access bits correctly on the directly-declared conversions.
12940         for (CXXRecordDecl::conversion_iterator
12941                I = CXXRecord->conversion_begin(),
12942                E = CXXRecord->conversion_end(); I != E; ++I)
12943           I.setAccess((*I)->getAccess());
12944 
12945         if (!CXXRecord->isDependentType()) {
12946           if (CXXRecord->hasUserDeclaredDestructor()) {
12947             // Adjust user-defined destructor exception spec.
12948             if (getLangOpts().CPlusPlus11)
12949               AdjustDestructorExceptionSpec(CXXRecord,
12950                                             CXXRecord->getDestructor());
12951           }
12952 
12953           // Add any implicitly-declared members to this class.
12954           AddImplicitlyDeclaredMembersToClass(CXXRecord);
12955 
12956           // If we have virtual base classes, we may end up finding multiple
12957           // final overriders for a given virtual function. Check for this
12958           // problem now.
12959           if (CXXRecord->getNumVBases()) {
12960             CXXFinalOverriderMap FinalOverriders;
12961             CXXRecord->getFinalOverriders(FinalOverriders);
12962 
12963             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12964                                              MEnd = FinalOverriders.end();
12965                  M != MEnd; ++M) {
12966               for (OverridingMethods::iterator SO = M->second.begin(),
12967                                             SOEnd = M->second.end();
12968                    SO != SOEnd; ++SO) {
12969                 assert(SO->second.size() > 0 &&
12970                        "Virtual function without overridding functions?");
12971                 if (SO->second.size() == 1)
12972                   continue;
12973 
12974                 // C++ [class.virtual]p2:
12975                 //   In a derived class, if a virtual member function of a base
12976                 //   class subobject has more than one final overrider the
12977                 //   program is ill-formed.
12978                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
12979                   << (const NamedDecl *)M->first << Record;
12980                 Diag(M->first->getLocation(),
12981                      diag::note_overridden_virtual_function);
12982                 for (OverridingMethods::overriding_iterator
12983                           OM = SO->second.begin(),
12984                        OMEnd = SO->second.end();
12985                      OM != OMEnd; ++OM)
12986                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
12987                     << (const NamedDecl *)M->first << OM->Method->getParent();
12988 
12989                 Record->setInvalidDecl();
12990               }
12991             }
12992             CXXRecord->completeDefinition(&FinalOverriders);
12993             Completed = true;
12994           }
12995         }
12996       }
12997     }
12998 
12999     if (!Completed)
13000       Record->completeDefinition();
13001 
13002     if (Record->hasAttrs()) {
13003       CheckAlignasUnderalignment(Record);
13004 
13005       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
13006         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
13007                                            IA->getRange(), IA->getBestCase(),
13008                                            IA->getSemanticSpelling());
13009     }
13010 
13011     // Check if the structure/union declaration is a type that can have zero
13012     // size in C. For C this is a language extension, for C++ it may cause
13013     // compatibility problems.
13014     bool CheckForZeroSize;
13015     if (!getLangOpts().CPlusPlus) {
13016       CheckForZeroSize = true;
13017     } else {
13018       // For C++ filter out types that cannot be referenced in C code.
13019       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
13020       CheckForZeroSize =
13021           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
13022           !CXXRecord->isDependentType() &&
13023           CXXRecord->isCLike();
13024     }
13025     if (CheckForZeroSize) {
13026       bool ZeroSize = true;
13027       bool IsEmpty = true;
13028       unsigned NonBitFields = 0;
13029       for (RecordDecl::field_iterator I = Record->field_begin(),
13030                                       E = Record->field_end();
13031            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
13032         IsEmpty = false;
13033         if (I->isUnnamedBitfield()) {
13034           if (I->getBitWidthValue(Context) > 0)
13035             ZeroSize = false;
13036         } else {
13037           ++NonBitFields;
13038           QualType FieldType = I->getType();
13039           if (FieldType->isIncompleteType() ||
13040               !Context.getTypeSizeInChars(FieldType).isZero())
13041             ZeroSize = false;
13042         }
13043       }
13044 
13045       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
13046       // allowed in C++, but warn if its declaration is inside
13047       // extern "C" block.
13048       if (ZeroSize) {
13049         Diag(RecLoc, getLangOpts().CPlusPlus ?
13050                          diag::warn_zero_size_struct_union_in_extern_c :
13051                          diag::warn_zero_size_struct_union_compat)
13052           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
13053       }
13054 
13055       // Structs without named members are extension in C (C99 6.7.2.1p7),
13056       // but are accepted by GCC.
13057       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
13058         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
13059                                diag::ext_no_named_members_in_struct_union)
13060           << Record->isUnion();
13061       }
13062     }
13063   } else {
13064     ObjCIvarDecl **ClsFields =
13065       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
13066     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
13067       ID->setEndOfDefinitionLoc(RBrac);
13068       // Add ivar's to class's DeclContext.
13069       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13070         ClsFields[i]->setLexicalDeclContext(ID);
13071         ID->addDecl(ClsFields[i]);
13072       }
13073       // Must enforce the rule that ivars in the base classes may not be
13074       // duplicates.
13075       if (ID->getSuperClass())
13076         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
13077     } else if (ObjCImplementationDecl *IMPDecl =
13078                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13079       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
13080       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
13081         // Ivar declared in @implementation never belongs to the implementation.
13082         // Only it is in implementation's lexical context.
13083         ClsFields[I]->setLexicalDeclContext(IMPDecl);
13084       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
13085       IMPDecl->setIvarLBraceLoc(LBrac);
13086       IMPDecl->setIvarRBraceLoc(RBrac);
13087     } else if (ObjCCategoryDecl *CDecl =
13088                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13089       // case of ivars in class extension; all other cases have been
13090       // reported as errors elsewhere.
13091       // FIXME. Class extension does not have a LocEnd field.
13092       // CDecl->setLocEnd(RBrac);
13093       // Add ivar's to class extension's DeclContext.
13094       // Diagnose redeclaration of private ivars.
13095       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
13096       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13097         if (IDecl) {
13098           if (const ObjCIvarDecl *ClsIvar =
13099               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
13100             Diag(ClsFields[i]->getLocation(),
13101                  diag::err_duplicate_ivar_declaration);
13102             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
13103             continue;
13104           }
13105           for (const auto *Ext : IDecl->known_extensions()) {
13106             if (const ObjCIvarDecl *ClsExtIvar
13107                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
13108               Diag(ClsFields[i]->getLocation(),
13109                    diag::err_duplicate_ivar_declaration);
13110               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
13111               continue;
13112             }
13113           }
13114         }
13115         ClsFields[i]->setLexicalDeclContext(CDecl);
13116         CDecl->addDecl(ClsFields[i]);
13117       }
13118       CDecl->setIvarLBraceLoc(LBrac);
13119       CDecl->setIvarRBraceLoc(RBrac);
13120     }
13121   }
13122 
13123   if (Attr)
13124     ProcessDeclAttributeList(S, Record, Attr);
13125 }
13126 
13127 /// \brief Determine whether the given integral value is representable within
13128 /// the given type T.
13129 static bool isRepresentableIntegerValue(ASTContext &Context,
13130                                         llvm::APSInt &Value,
13131                                         QualType T) {
13132   assert(T->isIntegralType(Context) && "Integral type required!");
13133   unsigned BitWidth = Context.getIntWidth(T);
13134 
13135   if (Value.isUnsigned() || Value.isNonNegative()) {
13136     if (T->isSignedIntegerOrEnumerationType())
13137       --BitWidth;
13138     return Value.getActiveBits() <= BitWidth;
13139   }
13140   return Value.getMinSignedBits() <= BitWidth;
13141 }
13142 
13143 // \brief Given an integral type, return the next larger integral type
13144 // (or a NULL type of no such type exists).
13145 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
13146   // FIXME: Int128/UInt128 support, which also needs to be introduced into
13147   // enum checking below.
13148   assert(T->isIntegralType(Context) && "Integral type required!");
13149   const unsigned NumTypes = 4;
13150   QualType SignedIntegralTypes[NumTypes] = {
13151     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
13152   };
13153   QualType UnsignedIntegralTypes[NumTypes] = {
13154     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
13155     Context.UnsignedLongLongTy
13156   };
13157 
13158   unsigned BitWidth = Context.getTypeSize(T);
13159   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
13160                                                         : UnsignedIntegralTypes;
13161   for (unsigned I = 0; I != NumTypes; ++I)
13162     if (Context.getTypeSize(Types[I]) > BitWidth)
13163       return Types[I];
13164 
13165   return QualType();
13166 }
13167 
13168 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
13169                                           EnumConstantDecl *LastEnumConst,
13170                                           SourceLocation IdLoc,
13171                                           IdentifierInfo *Id,
13172                                           Expr *Val) {
13173   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13174   llvm::APSInt EnumVal(IntWidth);
13175   QualType EltTy;
13176 
13177   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
13178     Val = nullptr;
13179 
13180   if (Val)
13181     Val = DefaultLvalueConversion(Val).get();
13182 
13183   if (Val) {
13184     if (Enum->isDependentType() || Val->isTypeDependent())
13185       EltTy = Context.DependentTy;
13186     else {
13187       SourceLocation ExpLoc;
13188       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
13189           !getLangOpts().MSVCCompat) {
13190         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
13191         // constant-expression in the enumerator-definition shall be a converted
13192         // constant expression of the underlying type.
13193         EltTy = Enum->getIntegerType();
13194         ExprResult Converted =
13195           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
13196                                            CCEK_Enumerator);
13197         if (Converted.isInvalid())
13198           Val = nullptr;
13199         else
13200           Val = Converted.get();
13201       } else if (!Val->isValueDependent() &&
13202                  !(Val = VerifyIntegerConstantExpression(Val,
13203                                                          &EnumVal).get())) {
13204         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
13205       } else {
13206         if (Enum->isFixed()) {
13207           EltTy = Enum->getIntegerType();
13208 
13209           // In Obj-C and Microsoft mode, require the enumeration value to be
13210           // representable in the underlying type of the enumeration. In C++11,
13211           // we perform a non-narrowing conversion as part of converted constant
13212           // expression checking.
13213           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13214             if (getLangOpts().MSVCCompat) {
13215               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
13216               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13217             } else
13218               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
13219           } else
13220             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13221         } else if (getLangOpts().CPlusPlus) {
13222           // C++11 [dcl.enum]p5:
13223           //   If the underlying type is not fixed, the type of each enumerator
13224           //   is the type of its initializing value:
13225           //     - If an initializer is specified for an enumerator, the
13226           //       initializing value has the same type as the expression.
13227           EltTy = Val->getType();
13228         } else {
13229           // C99 6.7.2.2p2:
13230           //   The expression that defines the value of an enumeration constant
13231           //   shall be an integer constant expression that has a value
13232           //   representable as an int.
13233 
13234           // Complain if the value is not representable in an int.
13235           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
13236             Diag(IdLoc, diag::ext_enum_value_not_int)
13237               << EnumVal.toString(10) << Val->getSourceRange()
13238               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13239           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13240             // Force the type of the expression to 'int'.
13241             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
13242           }
13243           EltTy = Val->getType();
13244         }
13245       }
13246     }
13247   }
13248 
13249   if (!Val) {
13250     if (Enum->isDependentType())
13251       EltTy = Context.DependentTy;
13252     else if (!LastEnumConst) {
13253       // C++0x [dcl.enum]p5:
13254       //   If the underlying type is not fixed, the type of each enumerator
13255       //   is the type of its initializing value:
13256       //     - If no initializer is specified for the first enumerator, the
13257       //       initializing value has an unspecified integral type.
13258       //
13259       // GCC uses 'int' for its unspecified integral type, as does
13260       // C99 6.7.2.2p3.
13261       if (Enum->isFixed()) {
13262         EltTy = Enum->getIntegerType();
13263       }
13264       else {
13265         EltTy = Context.IntTy;
13266       }
13267     } else {
13268       // Assign the last value + 1.
13269       EnumVal = LastEnumConst->getInitVal();
13270       ++EnumVal;
13271       EltTy = LastEnumConst->getType();
13272 
13273       // Check for overflow on increment.
13274       if (EnumVal < LastEnumConst->getInitVal()) {
13275         // C++0x [dcl.enum]p5:
13276         //   If the underlying type is not fixed, the type of each enumerator
13277         //   is the type of its initializing value:
13278         //
13279         //     - Otherwise the type of the initializing value is the same as
13280         //       the type of the initializing value of the preceding enumerator
13281         //       unless the incremented value is not representable in that type,
13282         //       in which case the type is an unspecified integral type
13283         //       sufficient to contain the incremented value. If no such type
13284         //       exists, the program is ill-formed.
13285         QualType T = getNextLargerIntegralType(Context, EltTy);
13286         if (T.isNull() || Enum->isFixed()) {
13287           // There is no integral type larger enough to represent this
13288           // value. Complain, then allow the value to wrap around.
13289           EnumVal = LastEnumConst->getInitVal();
13290           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
13291           ++EnumVal;
13292           if (Enum->isFixed())
13293             // When the underlying type is fixed, this is ill-formed.
13294             Diag(IdLoc, diag::err_enumerator_wrapped)
13295               << EnumVal.toString(10)
13296               << EltTy;
13297           else
13298             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
13299               << EnumVal.toString(10);
13300         } else {
13301           EltTy = T;
13302         }
13303 
13304         // Retrieve the last enumerator's value, extent that type to the
13305         // type that is supposed to be large enough to represent the incremented
13306         // value, then increment.
13307         EnumVal = LastEnumConst->getInitVal();
13308         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13309         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
13310         ++EnumVal;
13311 
13312         // If we're not in C++, diagnose the overflow of enumerator values,
13313         // which in C99 means that the enumerator value is not representable in
13314         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
13315         // permits enumerator values that are representable in some larger
13316         // integral type.
13317         if (!getLangOpts().CPlusPlus && !T.isNull())
13318           Diag(IdLoc, diag::warn_enum_value_overflow);
13319       } else if (!getLangOpts().CPlusPlus &&
13320                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13321         // Enforce C99 6.7.2.2p2 even when we compute the next value.
13322         Diag(IdLoc, diag::ext_enum_value_not_int)
13323           << EnumVal.toString(10) << 1;
13324       }
13325     }
13326   }
13327 
13328   if (!EltTy->isDependentType()) {
13329     // Make the enumerator value match the signedness and size of the
13330     // enumerator's type.
13331     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
13332     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13333   }
13334 
13335   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
13336                                   Val, EnumVal);
13337 }
13338 
13339 
13340 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
13341                               SourceLocation IdLoc, IdentifierInfo *Id,
13342                               AttributeList *Attr,
13343                               SourceLocation EqualLoc, Expr *Val) {
13344   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
13345   EnumConstantDecl *LastEnumConst =
13346     cast_or_null<EnumConstantDecl>(lastEnumConst);
13347 
13348   // The scope passed in may not be a decl scope.  Zip up the scope tree until
13349   // we find one that is.
13350   S = getNonFieldDeclScope(S);
13351 
13352   // Verify that there isn't already something declared with this name in this
13353   // scope.
13354   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
13355                                          ForRedeclaration);
13356   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13357     // Maybe we will complain about the shadowed template parameter.
13358     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
13359     // Just pretend that we didn't see the previous declaration.
13360     PrevDecl = nullptr;
13361   }
13362 
13363   if (PrevDecl) {
13364     // When in C++, we may get a TagDecl with the same name; in this case the
13365     // enum constant will 'hide' the tag.
13366     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
13367            "Received TagDecl when not in C++!");
13368     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
13369       if (isa<EnumConstantDecl>(PrevDecl))
13370         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
13371       else
13372         Diag(IdLoc, diag::err_redefinition) << Id;
13373       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13374       return nullptr;
13375     }
13376   }
13377 
13378   // C++ [class.mem]p15:
13379   // If T is the name of a class, then each of the following shall have a name
13380   // different from T:
13381   // - every enumerator of every member of class T that is an unscoped
13382   // enumerated type
13383   if (CXXRecordDecl *Record
13384                       = dyn_cast<CXXRecordDecl>(
13385                              TheEnumDecl->getDeclContext()->getRedeclContext()))
13386     if (!TheEnumDecl->isScoped() &&
13387         Record->getIdentifier() && Record->getIdentifier() == Id)
13388       Diag(IdLoc, diag::err_member_name_of_class) << Id;
13389 
13390   EnumConstantDecl *New =
13391     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
13392 
13393   if (New) {
13394     // Process attributes.
13395     if (Attr) ProcessDeclAttributeList(S, New, Attr);
13396 
13397     // Register this decl in the current scope stack.
13398     New->setAccess(TheEnumDecl->getAccess());
13399     PushOnScopeChains(New, S);
13400   }
13401 
13402   ActOnDocumentableDecl(New);
13403 
13404   return New;
13405 }
13406 
13407 // Returns true when the enum initial expression does not trigger the
13408 // duplicate enum warning.  A few common cases are exempted as follows:
13409 // Element2 = Element1
13410 // Element2 = Element1 + 1
13411 // Element2 = Element1 - 1
13412 // Where Element2 and Element1 are from the same enum.
13413 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
13414   Expr *InitExpr = ECD->getInitExpr();
13415   if (!InitExpr)
13416     return true;
13417   InitExpr = InitExpr->IgnoreImpCasts();
13418 
13419   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
13420     if (!BO->isAdditiveOp())
13421       return true;
13422     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
13423     if (!IL)
13424       return true;
13425     if (IL->getValue() != 1)
13426       return true;
13427 
13428     InitExpr = BO->getLHS();
13429   }
13430 
13431   // This checks if the elements are from the same enum.
13432   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
13433   if (!DRE)
13434     return true;
13435 
13436   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
13437   if (!EnumConstant)
13438     return true;
13439 
13440   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
13441       Enum)
13442     return true;
13443 
13444   return false;
13445 }
13446 
13447 struct DupKey {
13448   int64_t val;
13449   bool isTombstoneOrEmptyKey;
13450   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
13451     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
13452 };
13453 
13454 static DupKey GetDupKey(const llvm::APSInt& Val) {
13455   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
13456                 false);
13457 }
13458 
13459 struct DenseMapInfoDupKey {
13460   static DupKey getEmptyKey() { return DupKey(0, true); }
13461   static DupKey getTombstoneKey() { return DupKey(1, true); }
13462   static unsigned getHashValue(const DupKey Key) {
13463     return (unsigned)(Key.val * 37);
13464   }
13465   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
13466     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
13467            LHS.val == RHS.val;
13468   }
13469 };
13470 
13471 // Emits a warning when an element is implicitly set a value that
13472 // a previous element has already been set to.
13473 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
13474                                         EnumDecl *Enum,
13475                                         QualType EnumType) {
13476   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
13477     return;
13478   // Avoid anonymous enums
13479   if (!Enum->getIdentifier())
13480     return;
13481 
13482   // Only check for small enums.
13483   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
13484     return;
13485 
13486   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
13487   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
13488 
13489   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
13490   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
13491           ValueToVectorMap;
13492 
13493   DuplicatesVector DupVector;
13494   ValueToVectorMap EnumMap;
13495 
13496   // Populate the EnumMap with all values represented by enum constants without
13497   // an initialier.
13498   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13499     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
13500 
13501     // Null EnumConstantDecl means a previous diagnostic has been emitted for
13502     // this constant.  Skip this enum since it may be ill-formed.
13503     if (!ECD) {
13504       return;
13505     }
13506 
13507     if (ECD->getInitExpr())
13508       continue;
13509 
13510     DupKey Key = GetDupKey(ECD->getInitVal());
13511     DeclOrVector &Entry = EnumMap[Key];
13512 
13513     // First time encountering this value.
13514     if (Entry.isNull())
13515       Entry = ECD;
13516   }
13517 
13518   // Create vectors for any values that has duplicates.
13519   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13520     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
13521     if (!ValidDuplicateEnum(ECD, Enum))
13522       continue;
13523 
13524     DupKey Key = GetDupKey(ECD->getInitVal());
13525 
13526     DeclOrVector& Entry = EnumMap[Key];
13527     if (Entry.isNull())
13528       continue;
13529 
13530     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
13531       // Ensure constants are different.
13532       if (D == ECD)
13533         continue;
13534 
13535       // Create new vector and push values onto it.
13536       ECDVector *Vec = new ECDVector();
13537       Vec->push_back(D);
13538       Vec->push_back(ECD);
13539 
13540       // Update entry to point to the duplicates vector.
13541       Entry = Vec;
13542 
13543       // Store the vector somewhere we can consult later for quick emission of
13544       // diagnostics.
13545       DupVector.push_back(Vec);
13546       continue;
13547     }
13548 
13549     ECDVector *Vec = Entry.get<ECDVector*>();
13550     // Make sure constants are not added more than once.
13551     if (*Vec->begin() == ECD)
13552       continue;
13553 
13554     Vec->push_back(ECD);
13555   }
13556 
13557   // Emit diagnostics.
13558   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
13559                                   DupVectorEnd = DupVector.end();
13560        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
13561     ECDVector *Vec = *DupVectorIter;
13562     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
13563 
13564     // Emit warning for one enum constant.
13565     ECDVector::iterator I = Vec->begin();
13566     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
13567       << (*I)->getName() << (*I)->getInitVal().toString(10)
13568       << (*I)->getSourceRange();
13569     ++I;
13570 
13571     // Emit one note for each of the remaining enum constants with
13572     // the same value.
13573     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
13574       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
13575         << (*I)->getName() << (*I)->getInitVal().toString(10)
13576         << (*I)->getSourceRange();
13577     delete Vec;
13578   }
13579 }
13580 
13581 bool
13582 Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
13583                         bool AllowMask) const {
13584   FlagEnumAttr *FEAttr = ED->getAttr<FlagEnumAttr>();
13585   assert(FEAttr && "looking for value in non-flag enum");
13586 
13587   llvm::APInt FlagMask = ~FEAttr->getFlagBits();
13588   unsigned Width = FlagMask.getBitWidth();
13589 
13590   // We will try a zero-extended value for the regular check first.
13591   llvm::APInt ExtVal = Val.zextOrSelf(Width);
13592 
13593   // A value is in a flag enum if either its bits are a subset of the enum's
13594   // flag bits (the first condition) or we are allowing masks and the same is
13595   // true of its complement (the second condition). When masks are allowed, we
13596   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
13597   //
13598   // While it's true that any value could be used as a mask, the assumption is
13599   // that a mask will have all of the insignificant bits set. Anything else is
13600   // likely a logic error.
13601   if (!(FlagMask & ExtVal))
13602     return true;
13603 
13604   if (AllowMask) {
13605     // Try a one-extended value instead. This can happen if the enum is wider
13606     // than the constant used, in C with extensions to allow for wider enums.
13607     // The mask will still have the correct behaviour, so we give the user the
13608     // benefit of the doubt.
13609     //
13610     // FIXME: This heuristic can cause weird results if the enum was extended
13611     // to a larger type and is signed, because then bit-masks of smaller types
13612     // that get extended will fall out of range (e.g. ~0x1u). We currently don't
13613     // detect that case and will get a false positive for it. In most cases,
13614     // though, it can be fixed by making it a signed type (e.g. ~0x1), so it may
13615     // be fine just to accept this as a warning.
13616     ExtVal |= llvm::APInt::getHighBitsSet(Width, Width - Val.getBitWidth());
13617     if (!(FlagMask & ~ExtVal))
13618       return true;
13619   }
13620 
13621   return false;
13622 }
13623 
13624 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
13625                          SourceLocation RBraceLoc, Decl *EnumDeclX,
13626                          ArrayRef<Decl *> Elements,
13627                          Scope *S, AttributeList *Attr) {
13628   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
13629   QualType EnumType = Context.getTypeDeclType(Enum);
13630 
13631   if (Attr)
13632     ProcessDeclAttributeList(S, Enum, Attr);
13633 
13634   if (Enum->isDependentType()) {
13635     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13636       EnumConstantDecl *ECD =
13637         cast_or_null<EnumConstantDecl>(Elements[i]);
13638       if (!ECD) continue;
13639 
13640       ECD->setType(EnumType);
13641     }
13642 
13643     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
13644     return;
13645   }
13646 
13647   // TODO: If the result value doesn't fit in an int, it must be a long or long
13648   // long value.  ISO C does not support this, but GCC does as an extension,
13649   // emit a warning.
13650   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13651   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
13652   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
13653 
13654   // Verify that all the values are okay, compute the size of the values, and
13655   // reverse the list.
13656   unsigned NumNegativeBits = 0;
13657   unsigned NumPositiveBits = 0;
13658 
13659   // Keep track of whether all elements have type int.
13660   bool AllElementsInt = true;
13661 
13662   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13663     EnumConstantDecl *ECD =
13664       cast_or_null<EnumConstantDecl>(Elements[i]);
13665     if (!ECD) continue;  // Already issued a diagnostic.
13666 
13667     const llvm::APSInt &InitVal = ECD->getInitVal();
13668 
13669     // Keep track of the size of positive and negative values.
13670     if (InitVal.isUnsigned() || InitVal.isNonNegative())
13671       NumPositiveBits = std::max(NumPositiveBits,
13672                                  (unsigned)InitVal.getActiveBits());
13673     else
13674       NumNegativeBits = std::max(NumNegativeBits,
13675                                  (unsigned)InitVal.getMinSignedBits());
13676 
13677     // Keep track of whether every enum element has type int (very commmon).
13678     if (AllElementsInt)
13679       AllElementsInt = ECD->getType() == Context.IntTy;
13680   }
13681 
13682   // Figure out the type that should be used for this enum.
13683   QualType BestType;
13684   unsigned BestWidth;
13685 
13686   // C++0x N3000 [conv.prom]p3:
13687   //   An rvalue of an unscoped enumeration type whose underlying
13688   //   type is not fixed can be converted to an rvalue of the first
13689   //   of the following types that can represent all the values of
13690   //   the enumeration: int, unsigned int, long int, unsigned long
13691   //   int, long long int, or unsigned long long int.
13692   // C99 6.4.4.3p2:
13693   //   An identifier declared as an enumeration constant has type int.
13694   // The C99 rule is modified by a gcc extension
13695   QualType BestPromotionType;
13696 
13697   bool Packed = Enum->hasAttr<PackedAttr>();
13698   // -fshort-enums is the equivalent to specifying the packed attribute on all
13699   // enum definitions.
13700   if (LangOpts.ShortEnums)
13701     Packed = true;
13702 
13703   if (Enum->isFixed()) {
13704     BestType = Enum->getIntegerType();
13705     if (BestType->isPromotableIntegerType())
13706       BestPromotionType = Context.getPromotedIntegerType(BestType);
13707     else
13708       BestPromotionType = BestType;
13709 
13710     BestWidth = Context.getIntWidth(BestType);
13711   }
13712   else if (NumNegativeBits) {
13713     // If there is a negative value, figure out the smallest integer type (of
13714     // int/long/longlong) that fits.
13715     // If it's packed, check also if it fits a char or a short.
13716     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
13717       BestType = Context.SignedCharTy;
13718       BestWidth = CharWidth;
13719     } else if (Packed && NumNegativeBits <= ShortWidth &&
13720                NumPositiveBits < ShortWidth) {
13721       BestType = Context.ShortTy;
13722       BestWidth = ShortWidth;
13723     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
13724       BestType = Context.IntTy;
13725       BestWidth = IntWidth;
13726     } else {
13727       BestWidth = Context.getTargetInfo().getLongWidth();
13728 
13729       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
13730         BestType = Context.LongTy;
13731       } else {
13732         BestWidth = Context.getTargetInfo().getLongLongWidth();
13733 
13734         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
13735           Diag(Enum->getLocation(), diag::ext_enum_too_large);
13736         BestType = Context.LongLongTy;
13737       }
13738     }
13739     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
13740   } else {
13741     // If there is no negative value, figure out the smallest type that fits
13742     // all of the enumerator values.
13743     // If it's packed, check also if it fits a char or a short.
13744     if (Packed && NumPositiveBits <= CharWidth) {
13745       BestType = Context.UnsignedCharTy;
13746       BestPromotionType = Context.IntTy;
13747       BestWidth = CharWidth;
13748     } else if (Packed && NumPositiveBits <= ShortWidth) {
13749       BestType = Context.UnsignedShortTy;
13750       BestPromotionType = Context.IntTy;
13751       BestWidth = ShortWidth;
13752     } else if (NumPositiveBits <= IntWidth) {
13753       BestType = Context.UnsignedIntTy;
13754       BestWidth = IntWidth;
13755       BestPromotionType
13756         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13757                            ? Context.UnsignedIntTy : Context.IntTy;
13758     } else if (NumPositiveBits <=
13759                (BestWidth = Context.getTargetInfo().getLongWidth())) {
13760       BestType = Context.UnsignedLongTy;
13761       BestPromotionType
13762         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13763                            ? Context.UnsignedLongTy : Context.LongTy;
13764     } else {
13765       BestWidth = Context.getTargetInfo().getLongLongWidth();
13766       assert(NumPositiveBits <= BestWidth &&
13767              "How could an initializer get larger than ULL?");
13768       BestType = Context.UnsignedLongLongTy;
13769       BestPromotionType
13770         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
13771                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
13772     }
13773   }
13774 
13775   FlagEnumAttr *FEAttr = Enum->getAttr<FlagEnumAttr>();
13776   if (FEAttr)
13777     FEAttr->getFlagBits() = llvm::APInt(BestWidth, 0);
13778 
13779   // Loop over all of the enumerator constants, changing their types to match
13780   // the type of the enum if needed. If we have a flag type, we also prepare the
13781   // FlagBits cache.
13782   for (auto *D : Elements) {
13783     auto *ECD = cast_or_null<EnumConstantDecl>(D);
13784     if (!ECD) continue;  // Already issued a diagnostic.
13785 
13786     // Standard C says the enumerators have int type, but we allow, as an
13787     // extension, the enumerators to be larger than int size.  If each
13788     // enumerator value fits in an int, type it as an int, otherwise type it the
13789     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
13790     // that X has type 'int', not 'unsigned'.
13791 
13792     // Determine whether the value fits into an int.
13793     llvm::APSInt InitVal = ECD->getInitVal();
13794 
13795     // If it fits into an integer type, force it.  Otherwise force it to match
13796     // the enum decl type.
13797     QualType NewTy;
13798     unsigned NewWidth;
13799     bool NewSign;
13800     if (!getLangOpts().CPlusPlus &&
13801         !Enum->isFixed() &&
13802         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
13803       NewTy = Context.IntTy;
13804       NewWidth = IntWidth;
13805       NewSign = true;
13806     } else if (ECD->getType() == BestType) {
13807       // Already the right type!
13808       if (getLangOpts().CPlusPlus)
13809         // C++ [dcl.enum]p4: Following the closing brace of an
13810         // enum-specifier, each enumerator has the type of its
13811         // enumeration.
13812         ECD->setType(EnumType);
13813       goto flagbits;
13814     } else {
13815       NewTy = BestType;
13816       NewWidth = BestWidth;
13817       NewSign = BestType->isSignedIntegerOrEnumerationType();
13818     }
13819 
13820     // Adjust the APSInt value.
13821     InitVal = InitVal.extOrTrunc(NewWidth);
13822     InitVal.setIsSigned(NewSign);
13823     ECD->setInitVal(InitVal);
13824 
13825     // Adjust the Expr initializer and type.
13826     if (ECD->getInitExpr() &&
13827         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
13828       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
13829                                                 CK_IntegralCast,
13830                                                 ECD->getInitExpr(),
13831                                                 /*base paths*/ nullptr,
13832                                                 VK_RValue));
13833     if (getLangOpts().CPlusPlus)
13834       // C++ [dcl.enum]p4: Following the closing brace of an
13835       // enum-specifier, each enumerator has the type of its
13836       // enumeration.
13837       ECD->setType(EnumType);
13838     else
13839       ECD->setType(NewTy);
13840 
13841 flagbits:
13842     // Check to see if we have a constant with exactly one bit set. Note that x
13843     // & (x - 1) will be nonzero if and only if x has more than one bit set.
13844     if (FEAttr) {
13845       llvm::APInt ExtVal = InitVal.zextOrSelf(BestWidth);
13846       if (ExtVal != 0 && !(ExtVal & (ExtVal - 1))) {
13847         FEAttr->getFlagBits() |= ExtVal;
13848       }
13849     }
13850   }
13851 
13852   if (FEAttr) {
13853     for (Decl *D : Elements) {
13854       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
13855       if (!ECD) continue;  // Already issued a diagnostic.
13856 
13857       llvm::APSInt InitVal = ECD->getInitVal();
13858       if (InitVal != 0 && !IsValueInFlagEnum(Enum, InitVal, true))
13859         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
13860           << ECD << Enum;
13861     }
13862   }
13863 
13864 
13865 
13866   Enum->completeDefinition(BestType, BestPromotionType,
13867                            NumPositiveBits, NumNegativeBits);
13868 
13869   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
13870 
13871   // Now that the enum type is defined, ensure it's not been underaligned.
13872   if (Enum->hasAttrs())
13873     CheckAlignasUnderalignment(Enum);
13874 }
13875 
13876 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
13877                                   SourceLocation StartLoc,
13878                                   SourceLocation EndLoc) {
13879   StringLiteral *AsmString = cast<StringLiteral>(expr);
13880 
13881   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
13882                                                    AsmString, StartLoc,
13883                                                    EndLoc);
13884   CurContext->addDecl(New);
13885   return New;
13886 }
13887 
13888 static void checkModuleImportContext(Sema &S, Module *M,
13889                                      SourceLocation ImportLoc,
13890                                      DeclContext *DC) {
13891   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
13892     switch (LSD->getLanguage()) {
13893     case LinkageSpecDecl::lang_c:
13894       if (!M->IsExternC) {
13895         S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
13896           << M->getFullModuleName();
13897         S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
13898         return;
13899       }
13900       break;
13901     case LinkageSpecDecl::lang_cxx:
13902       break;
13903     }
13904     DC = LSD->getParent();
13905   }
13906 
13907   while (isa<LinkageSpecDecl>(DC))
13908     DC = DC->getParent();
13909   if (!isa<TranslationUnitDecl>(DC)) {
13910     S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
13911       << M->getFullModuleName() << DC;
13912     S.Diag(cast<Decl>(DC)->getLocStart(),
13913            diag::note_module_import_not_at_top_level)
13914       << DC;
13915   }
13916 }
13917 
13918 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
13919                                    SourceLocation ImportLoc,
13920                                    ModuleIdPath Path) {
13921   Module *Mod =
13922       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
13923                                    /*IsIncludeDirective=*/false);
13924   if (!Mod)
13925     return true;
13926 
13927   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13928 
13929   // FIXME: we should support importing a submodule within a different submodule
13930   // of the same top-level module. Until we do, make it an error rather than
13931   // silently ignoring the import.
13932   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
13933     Diag(ImportLoc, diag::err_module_self_import)
13934         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
13935   else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
13936     Diag(ImportLoc, diag::err_module_import_in_implementation)
13937         << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
13938 
13939   SmallVector<SourceLocation, 2> IdentifierLocs;
13940   Module *ModCheck = Mod;
13941   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13942     // If we've run out of module parents, just drop the remaining identifiers.
13943     // We need the length to be consistent.
13944     if (!ModCheck)
13945       break;
13946     ModCheck = ModCheck->Parent;
13947 
13948     IdentifierLocs.push_back(Path[I].second);
13949   }
13950 
13951   ImportDecl *Import = ImportDecl::Create(Context,
13952                                           Context.getTranslationUnitDecl(),
13953                                           AtLoc.isValid()? AtLoc : ImportLoc,
13954                                           Mod, IdentifierLocs);
13955   Context.getTranslationUnitDecl()->addDecl(Import);
13956   return Import;
13957 }
13958 
13959 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
13960   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13961 
13962   // FIXME: Should we synthesize an ImportDecl here?
13963   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13964                                       /*Complain=*/true);
13965 }
13966 
13967 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
13968                                                       Module *Mod) {
13969   // Bail if we're not allowed to implicitly import a module here.
13970   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
13971     return;
13972 
13973   // Create the implicit import declaration.
13974   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13975   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13976                                                    Loc, Mod, Loc);
13977   TU->addDecl(ImportD);
13978   Consumer.HandleImplicitImportDecl(ImportD);
13979 
13980   // Make the module visible.
13981   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13982                                       /*Complain=*/false);
13983 }
13984 
13985 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13986                                       IdentifierInfo* AliasName,
13987                                       SourceLocation PragmaLoc,
13988                                       SourceLocation NameLoc,
13989                                       SourceLocation AliasNameLoc) {
13990   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13991                                     LookupOrdinaryName);
13992   AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13993                                                     AliasName->getName(), 0);
13994 
13995   if (PrevDecl)
13996     PrevDecl->addAttr(Attr);
13997   else
13998     (void)ExtnameUndeclaredIdentifiers.insert(
13999       std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
14000 }
14001 
14002 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
14003                              SourceLocation PragmaLoc,
14004                              SourceLocation NameLoc) {
14005   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
14006 
14007   if (PrevDecl) {
14008     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
14009   } else {
14010     (void)WeakUndeclaredIdentifiers.insert(
14011       std::pair<IdentifierInfo*,WeakInfo>
14012         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
14013   }
14014 }
14015 
14016 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
14017                                 IdentifierInfo* AliasName,
14018                                 SourceLocation PragmaLoc,
14019                                 SourceLocation NameLoc,
14020                                 SourceLocation AliasNameLoc) {
14021   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
14022                                     LookupOrdinaryName);
14023   WeakInfo W = WeakInfo(Name, NameLoc);
14024 
14025   if (PrevDecl) {
14026     if (!PrevDecl->hasAttr<AliasAttr>())
14027       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
14028         DeclApplyPragmaWeak(TUScope, ND, W);
14029   } else {
14030     (void)WeakUndeclaredIdentifiers.insert(
14031       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
14032   }
14033 }
14034 
14035 Decl *Sema::getObjCDeclContext() const {
14036   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
14037 }
14038 
14039 AvailabilityResult Sema::getCurContextAvailability() const {
14040   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
14041   if (!D)
14042     return AR_Available;
14043 
14044   // If we are within an Objective-C method, we should consult
14045   // both the availability of the method as well as the
14046   // enclosing class.  If the class is (say) deprecated,
14047   // the entire method is considered deprecated from the
14048   // purpose of checking if the current context is deprecated.
14049   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
14050     AvailabilityResult R = MD->getAvailability();
14051     if (R != AR_Available)
14052       return R;
14053     D = MD->getClassInterface();
14054   }
14055   // If we are within an Objective-c @implementation, it
14056   // gets the same availability context as the @interface.
14057   else if (const ObjCImplementationDecl *ID =
14058             dyn_cast<ObjCImplementationDecl>(D)) {
14059     D = ID->getClassInterface();
14060   }
14061   // Recover from user error.
14062   return D ? D->getAvailability() : AR_Available;
14063 }
14064