1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68                        bool AllowTemplates=false)
69       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70         AllowClassTemplates(AllowTemplates) {
71     WantExpressionKeywords = false;
72     WantCXXNamedCasts = false;
73     WantRemainingKeywords = false;
74   }
75 
76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80       return (IsType || AllowedTemplate) &&
81              (AllowInvalidDecl || !ND->isInvalidDecl());
82     }
83     return !WantClassName && candidate.isKeyword();
84   }
85 
86  private:
87   bool AllowInvalidDecl;
88   bool WantClassName;
89   bool AllowClassTemplates;
90 };
91 
92 } // end anonymous namespace
93 
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96   switch (Kind) {
97   // FIXME: Take into account the current language when deciding whether a
98   // token kind is a valid type specifier
99   case tok::kw_short:
100   case tok::kw_long:
101   case tok::kw___int64:
102   case tok::kw___int128:
103   case tok::kw_signed:
104   case tok::kw_unsigned:
105   case tok::kw_void:
106   case tok::kw_char:
107   case tok::kw_int:
108   case tok::kw_half:
109   case tok::kw_float:
110   case tok::kw_double:
111   case tok::kw___float128:
112   case tok::kw_wchar_t:
113   case tok::kw_bool:
114   case tok::kw___underlying_type:
115   case tok::kw___auto_type:
116     return true;
117 
118   case tok::annot_typename:
119   case tok::kw_char16_t:
120   case tok::kw_char32_t:
121   case tok::kw_typeof:
122   case tok::annot_decltype:
123   case tok::kw_decltype:
124     return getLangOpts().CPlusPlus;
125 
126   default:
127     break;
128   }
129 
130   return false;
131 }
132 
133 namespace {
134 enum class UnqualifiedTypeNameLookupResult {
135   NotFound,
136   FoundNonType,
137   FoundType
138 };
139 } // end anonymous namespace
140 
141 /// \brief Tries to perform unqualified lookup of the type decls in bases for
142 /// dependent class.
143 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
144 /// type decl, \a FoundType if only type decls are found.
145 static UnqualifiedTypeNameLookupResult
146 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
147                                 SourceLocation NameLoc,
148                                 const CXXRecordDecl *RD) {
149   if (!RD->hasDefinition())
150     return UnqualifiedTypeNameLookupResult::NotFound;
151   // Look for type decls in base classes.
152   UnqualifiedTypeNameLookupResult FoundTypeDecl =
153       UnqualifiedTypeNameLookupResult::NotFound;
154   for (const auto &Base : RD->bases()) {
155     const CXXRecordDecl *BaseRD = nullptr;
156     if (auto *BaseTT = Base.getType()->getAs<TagType>())
157       BaseRD = BaseTT->getAsCXXRecordDecl();
158     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
159       // Look for type decls in dependent base classes that have known primary
160       // templates.
161       if (!TST || !TST->isDependentType())
162         continue;
163       auto *TD = TST->getTemplateName().getAsTemplateDecl();
164       if (!TD)
165         continue;
166       if (auto *BasePrimaryTemplate =
167           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
168         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
169           BaseRD = BasePrimaryTemplate;
170         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
171           if (const ClassTemplatePartialSpecializationDecl *PS =
172                   CTD->findPartialSpecialization(Base.getType()))
173             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
174               BaseRD = PS;
175         }
176       }
177     }
178     if (BaseRD) {
179       for (NamedDecl *ND : BaseRD->lookup(&II)) {
180         if (!isa<TypeDecl>(ND))
181           return UnqualifiedTypeNameLookupResult::FoundNonType;
182         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
183       }
184       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
185         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
186         case UnqualifiedTypeNameLookupResult::FoundNonType:
187           return UnqualifiedTypeNameLookupResult::FoundNonType;
188         case UnqualifiedTypeNameLookupResult::FoundType:
189           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
190           break;
191         case UnqualifiedTypeNameLookupResult::NotFound:
192           break;
193         }
194       }
195     }
196   }
197 
198   return FoundTypeDecl;
199 }
200 
201 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
202                                                       const IdentifierInfo &II,
203                                                       SourceLocation NameLoc) {
204   // Lookup in the parent class template context, if any.
205   const CXXRecordDecl *RD = nullptr;
206   UnqualifiedTypeNameLookupResult FoundTypeDecl =
207       UnqualifiedTypeNameLookupResult::NotFound;
208   for (DeclContext *DC = S.CurContext;
209        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
210        DC = DC->getParent()) {
211     // Look for type decls in dependent base classes that have known primary
212     // templates.
213     RD = dyn_cast<CXXRecordDecl>(DC);
214     if (RD && RD->getDescribedClassTemplate())
215       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
216   }
217   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
218     return nullptr;
219 
220   // We found some types in dependent base classes.  Recover as if the user
221   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
222   // lookup during template instantiation.
223   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
224 
225   ASTContext &Context = S.Context;
226   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
227                                           cast<Type>(Context.getRecordType(RD)));
228   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
229 
230   CXXScopeSpec SS;
231   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
232 
233   TypeLocBuilder Builder;
234   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
235   DepTL.setNameLoc(NameLoc);
236   DepTL.setElaboratedKeywordLoc(SourceLocation());
237   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
238   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
239 }
240 
241 /// \brief If the identifier refers to a type name within this scope,
242 /// return the declaration of that type.
243 ///
244 /// This routine performs ordinary name lookup of the identifier II
245 /// within the given scope, with optional C++ scope specifier SS, to
246 /// determine whether the name refers to a type. If so, returns an
247 /// opaque pointer (actually a QualType) corresponding to that
248 /// type. Otherwise, returns NULL.
249 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
250                              Scope *S, CXXScopeSpec *SS,
251                              bool isClassName, bool HasTrailingDot,
252                              ParsedType ObjectTypePtr,
253                              bool IsCtorOrDtorName,
254                              bool WantNontrivialTypeSourceInfo,
255                              IdentifierInfo **CorrectedII) {
256   // Determine where we will perform name lookup.
257   DeclContext *LookupCtx = nullptr;
258   if (ObjectTypePtr) {
259     QualType ObjectType = ObjectTypePtr.get();
260     if (ObjectType->isRecordType())
261       LookupCtx = computeDeclContext(ObjectType);
262   } else if (SS && SS->isNotEmpty()) {
263     LookupCtx = computeDeclContext(*SS, false);
264 
265     if (!LookupCtx) {
266       if (isDependentScopeSpecifier(*SS)) {
267         // C++ [temp.res]p3:
268         //   A qualified-id that refers to a type and in which the
269         //   nested-name-specifier depends on a template-parameter (14.6.2)
270         //   shall be prefixed by the keyword typename to indicate that the
271         //   qualified-id denotes a type, forming an
272         //   elaborated-type-specifier (7.1.5.3).
273         //
274         // We therefore do not perform any name lookup if the result would
275         // refer to a member of an unknown specialization.
276         if (!isClassName && !IsCtorOrDtorName)
277           return nullptr;
278 
279         // We know from the grammar that this name refers to a type,
280         // so build a dependent node to describe the type.
281         if (WantNontrivialTypeSourceInfo)
282           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
283 
284         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
285         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
286                                        II, NameLoc);
287         return ParsedType::make(T);
288       }
289 
290       return nullptr;
291     }
292 
293     if (!LookupCtx->isDependentContext() &&
294         RequireCompleteDeclContext(*SS, LookupCtx))
295       return nullptr;
296   }
297 
298   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
299   // lookup for class-names.
300   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
301                                       LookupOrdinaryName;
302   LookupResult Result(*this, &II, NameLoc, Kind);
303   if (LookupCtx) {
304     // Perform "qualified" name lookup into the declaration context we
305     // computed, which is either the type of the base of a member access
306     // expression or the declaration context associated with a prior
307     // nested-name-specifier.
308     LookupQualifiedName(Result, LookupCtx);
309 
310     if (ObjectTypePtr && Result.empty()) {
311       // C++ [basic.lookup.classref]p3:
312       //   If the unqualified-id is ~type-name, the type-name is looked up
313       //   in the context of the entire postfix-expression. If the type T of
314       //   the object expression is of a class type C, the type-name is also
315       //   looked up in the scope of class C. At least one of the lookups shall
316       //   find a name that refers to (possibly cv-qualified) T.
317       LookupName(Result, S);
318     }
319   } else {
320     // Perform unqualified name lookup.
321     LookupName(Result, S);
322 
323     // For unqualified lookup in a class template in MSVC mode, look into
324     // dependent base classes where the primary class template is known.
325     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
326       if (ParsedType TypeInBase =
327               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
328         return TypeInBase;
329     }
330   }
331 
332   NamedDecl *IIDecl = nullptr;
333   switch (Result.getResultKind()) {
334   case LookupResult::NotFound:
335   case LookupResult::NotFoundInCurrentInstantiation:
336     if (CorrectedII) {
337       TypoCorrection Correction = CorrectTypo(
338           Result.getLookupNameInfo(), Kind, S, SS,
339           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
340           CTK_ErrorRecovery);
341       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
342       TemplateTy Template;
343       bool MemberOfUnknownSpecialization;
344       UnqualifiedId TemplateName;
345       TemplateName.setIdentifier(NewII, NameLoc);
346       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
347       CXXScopeSpec NewSS, *NewSSPtr = SS;
348       if (SS && NNS) {
349         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
350         NewSSPtr = &NewSS;
351       }
352       if (Correction && (NNS || NewII != &II) &&
353           // Ignore a correction to a template type as the to-be-corrected
354           // identifier is not a template (typo correction for template names
355           // is handled elsewhere).
356           !(getLangOpts().CPlusPlus && NewSSPtr &&
357             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
358                            Template, MemberOfUnknownSpecialization))) {
359         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
360                                     isClassName, HasTrailingDot, ObjectTypePtr,
361                                     IsCtorOrDtorName,
362                                     WantNontrivialTypeSourceInfo);
363         if (Ty) {
364           diagnoseTypo(Correction,
365                        PDiag(diag::err_unknown_type_or_class_name_suggest)
366                          << Result.getLookupName() << isClassName);
367           if (SS && NNS)
368             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
369           *CorrectedII = NewII;
370           return Ty;
371         }
372       }
373     }
374     // If typo correction failed or was not performed, fall through
375   case LookupResult::FoundOverloaded:
376   case LookupResult::FoundUnresolvedValue:
377     Result.suppressDiagnostics();
378     return nullptr;
379 
380   case LookupResult::Ambiguous:
381     // Recover from type-hiding ambiguities by hiding the type.  We'll
382     // do the lookup again when looking for an object, and we can
383     // diagnose the error then.  If we don't do this, then the error
384     // about hiding the type will be immediately followed by an error
385     // that only makes sense if the identifier was treated like a type.
386     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
387       Result.suppressDiagnostics();
388       return nullptr;
389     }
390 
391     // Look to see if we have a type anywhere in the list of results.
392     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
393          Res != ResEnd; ++Res) {
394       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
395         if (!IIDecl ||
396             (*Res)->getLocation().getRawEncoding() <
397               IIDecl->getLocation().getRawEncoding())
398           IIDecl = *Res;
399       }
400     }
401 
402     if (!IIDecl) {
403       // None of the entities we found is a type, so there is no way
404       // to even assume that the result is a type. In this case, don't
405       // complain about the ambiguity. The parser will either try to
406       // perform this lookup again (e.g., as an object name), which
407       // will produce the ambiguity, or will complain that it expected
408       // a type name.
409       Result.suppressDiagnostics();
410       return nullptr;
411     }
412 
413     // We found a type within the ambiguous lookup; diagnose the
414     // ambiguity and then return that type. This might be the right
415     // answer, or it might not be, but it suppresses any attempt to
416     // perform the name lookup again.
417     break;
418 
419   case LookupResult::Found:
420     IIDecl = Result.getFoundDecl();
421     break;
422   }
423 
424   assert(IIDecl && "Didn't find decl");
425 
426   QualType T;
427   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
428     DiagnoseUseOfDecl(IIDecl, NameLoc);
429 
430     T = Context.getTypeDeclType(TD);
431     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
432 
433     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
434     // constructor or destructor name (in such a case, the scope specifier
435     // will be attached to the enclosing Expr or Decl node).
436     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
437       if (WantNontrivialTypeSourceInfo) {
438         // Construct a type with type-source information.
439         TypeLocBuilder Builder;
440         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
441 
442         T = getElaboratedType(ETK_None, *SS, T);
443         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
444         ElabTL.setElaboratedKeywordLoc(SourceLocation());
445         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
446         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
447       } else {
448         T = getElaboratedType(ETK_None, *SS, T);
449       }
450     }
451   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
452     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
453     if (!HasTrailingDot)
454       T = Context.getObjCInterfaceType(IDecl);
455   }
456 
457   if (T.isNull()) {
458     // If it's not plausibly a type, suppress diagnostics.
459     Result.suppressDiagnostics();
460     return nullptr;
461   }
462   return ParsedType::make(T);
463 }
464 
465 // Builds a fake NNS for the given decl context.
466 static NestedNameSpecifier *
467 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
468   for (;; DC = DC->getLookupParent()) {
469     DC = DC->getPrimaryContext();
470     auto *ND = dyn_cast<NamespaceDecl>(DC);
471     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
472       return NestedNameSpecifier::Create(Context, nullptr, ND);
473     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
474       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
475                                          RD->getTypeForDecl());
476     else if (isa<TranslationUnitDecl>(DC))
477       return NestedNameSpecifier::GlobalSpecifier(Context);
478   }
479   llvm_unreachable("something isn't in TU scope?");
480 }
481 
482 /// Find the parent class with dependent bases of the innermost enclosing method
483 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
484 /// up allowing unqualified dependent type names at class-level, which MSVC
485 /// correctly rejects.
486 static const CXXRecordDecl *
487 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
488   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
489     DC = DC->getPrimaryContext();
490     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
491       if (MD->getParent()->hasAnyDependentBases())
492         return MD->getParent();
493   }
494   return nullptr;
495 }
496 
497 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
498                                           SourceLocation NameLoc,
499                                           bool IsTemplateTypeArg) {
500   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
501 
502   NestedNameSpecifier *NNS = nullptr;
503   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
504     // If we weren't able to parse a default template argument, delay lookup
505     // until instantiation time by making a non-dependent DependentTypeName. We
506     // pretend we saw a NestedNameSpecifier referring to the current scope, and
507     // lookup is retried.
508     // FIXME: This hurts our diagnostic quality, since we get errors like "no
509     // type named 'Foo' in 'current_namespace'" when the user didn't write any
510     // name specifiers.
511     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
512     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
513   } else if (const CXXRecordDecl *RD =
514                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
515     // Build a DependentNameType that will perform lookup into RD at
516     // instantiation time.
517     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
518                                       RD->getTypeForDecl());
519 
520     // Diagnose that this identifier was undeclared, and retry the lookup during
521     // template instantiation.
522     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
523                                                                       << RD;
524   } else {
525     // This is not a situation that we should recover from.
526     return ParsedType();
527   }
528 
529   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
530 
531   // Build type location information.  We synthesized the qualifier, so we have
532   // to build a fake NestedNameSpecifierLoc.
533   NestedNameSpecifierLocBuilder NNSLocBuilder;
534   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
535   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
536 
537   TypeLocBuilder Builder;
538   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
539   DepTL.setNameLoc(NameLoc);
540   DepTL.setElaboratedKeywordLoc(SourceLocation());
541   DepTL.setQualifierLoc(QualifierLoc);
542   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
543 }
544 
545 /// isTagName() - This method is called *for error recovery purposes only*
546 /// to determine if the specified name is a valid tag name ("struct foo").  If
547 /// so, this returns the TST for the tag corresponding to it (TST_enum,
548 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
549 /// cases in C where the user forgot to specify the tag.
550 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
551   // Do a tag name lookup in this scope.
552   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
553   LookupName(R, S, false);
554   R.suppressDiagnostics();
555   if (R.getResultKind() == LookupResult::Found)
556     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
557       switch (TD->getTagKind()) {
558       case TTK_Struct: return DeclSpec::TST_struct;
559       case TTK_Interface: return DeclSpec::TST_interface;
560       case TTK_Union:  return DeclSpec::TST_union;
561       case TTK_Class:  return DeclSpec::TST_class;
562       case TTK_Enum:   return DeclSpec::TST_enum;
563       }
564     }
565 
566   return DeclSpec::TST_unspecified;
567 }
568 
569 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
570 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
571 /// then downgrade the missing typename error to a warning.
572 /// This is needed for MSVC compatibility; Example:
573 /// @code
574 /// template<class T> class A {
575 /// public:
576 ///   typedef int TYPE;
577 /// };
578 /// template<class T> class B : public A<T> {
579 /// public:
580 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
581 /// };
582 /// @endcode
583 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
584   if (CurContext->isRecord()) {
585     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
586       return true;
587 
588     const Type *Ty = SS->getScopeRep()->getAsType();
589 
590     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
591     for (const auto &Base : RD->bases())
592       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
593         return true;
594     return S->isFunctionPrototypeScope();
595   }
596   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
597 }
598 
599 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
600                                    SourceLocation IILoc,
601                                    Scope *S,
602                                    CXXScopeSpec *SS,
603                                    ParsedType &SuggestedType,
604                                    bool AllowClassTemplates) {
605   // We don't have anything to suggest (yet).
606   SuggestedType = nullptr;
607 
608   // There may have been a typo in the name of the type. Look up typo
609   // results, in case we have something that we can suggest.
610   if (TypoCorrection Corrected =
611           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
612                       llvm::make_unique<TypeNameValidatorCCC>(
613                           false, false, AllowClassTemplates),
614                       CTK_ErrorRecovery)) {
615     if (Corrected.isKeyword()) {
616       // We corrected to a keyword.
617       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
618       II = Corrected.getCorrectionAsIdentifierInfo();
619     } else {
620       // We found a similarly-named type or interface; suggest that.
621       if (!SS || !SS->isSet()) {
622         diagnoseTypo(Corrected,
623                      PDiag(diag::err_unknown_typename_suggest) << II);
624       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
625         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
626         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
627                                 II->getName().equals(CorrectedStr);
628         diagnoseTypo(Corrected,
629                      PDiag(diag::err_unknown_nested_typename_suggest)
630                        << II << DC << DroppedSpecifier << SS->getRange());
631       } else {
632         llvm_unreachable("could not have corrected a typo here");
633       }
634 
635       CXXScopeSpec tmpSS;
636       if (Corrected.getCorrectionSpecifier())
637         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
638                           SourceRange(IILoc));
639       SuggestedType =
640           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
641                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
642                       /*IsCtorOrDtorName=*/false,
643                       /*NonTrivialTypeSourceInfo=*/true);
644     }
645     return;
646   }
647 
648   if (getLangOpts().CPlusPlus) {
649     // See if II is a class template that the user forgot to pass arguments to.
650     UnqualifiedId Name;
651     Name.setIdentifier(II, IILoc);
652     CXXScopeSpec EmptySS;
653     TemplateTy TemplateResult;
654     bool MemberOfUnknownSpecialization;
655     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
656                        Name, nullptr, true, TemplateResult,
657                        MemberOfUnknownSpecialization) == TNK_Type_template) {
658       TemplateName TplName = TemplateResult.get();
659       Diag(IILoc, diag::err_template_missing_args) << TplName;
660       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
661         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
662           << TplDecl->getTemplateParameters()->getSourceRange();
663       }
664       return;
665     }
666   }
667 
668   // FIXME: Should we move the logic that tries to recover from a missing tag
669   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
670 
671   if (!SS || (!SS->isSet() && !SS->isInvalid()))
672     Diag(IILoc, diag::err_unknown_typename) << II;
673   else if (DeclContext *DC = computeDeclContext(*SS, false))
674     Diag(IILoc, diag::err_typename_nested_not_found)
675       << II << DC << SS->getRange();
676   else if (isDependentScopeSpecifier(*SS)) {
677     unsigned DiagID = diag::err_typename_missing;
678     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
679       DiagID = diag::ext_typename_missing;
680 
681     Diag(SS->getRange().getBegin(), DiagID)
682       << SS->getScopeRep() << II->getName()
683       << SourceRange(SS->getRange().getBegin(), IILoc)
684       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
685     SuggestedType = ActOnTypenameType(S, SourceLocation(),
686                                       *SS, *II, IILoc).get();
687   } else {
688     assert(SS && SS->isInvalid() &&
689            "Invalid scope specifier has already been diagnosed");
690   }
691 }
692 
693 /// \brief Determine whether the given result set contains either a type name
694 /// or
695 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
696   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
697                        NextToken.is(tok::less);
698 
699   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
700     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
701       return true;
702 
703     if (CheckTemplate && isa<TemplateDecl>(*I))
704       return true;
705   }
706 
707   return false;
708 }
709 
710 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
711                                     Scope *S, CXXScopeSpec &SS,
712                                     IdentifierInfo *&Name,
713                                     SourceLocation NameLoc) {
714   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
715   SemaRef.LookupParsedName(R, S, &SS);
716   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
717     StringRef FixItTagName;
718     switch (Tag->getTagKind()) {
719       case TTK_Class:
720         FixItTagName = "class ";
721         break;
722 
723       case TTK_Enum:
724         FixItTagName = "enum ";
725         break;
726 
727       case TTK_Struct:
728         FixItTagName = "struct ";
729         break;
730 
731       case TTK_Interface:
732         FixItTagName = "__interface ";
733         break;
734 
735       case TTK_Union:
736         FixItTagName = "union ";
737         break;
738     }
739 
740     StringRef TagName = FixItTagName.drop_back();
741     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
742       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
743       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
744 
745     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
746          I != IEnd; ++I)
747       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
748         << Name << TagName;
749 
750     // Replace lookup results with just the tag decl.
751     Result.clear(Sema::LookupTagName);
752     SemaRef.LookupParsedName(Result, S, &SS);
753     return true;
754   }
755 
756   return false;
757 }
758 
759 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
760 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
761                                   QualType T, SourceLocation NameLoc) {
762   ASTContext &Context = S.Context;
763 
764   TypeLocBuilder Builder;
765   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
766 
767   T = S.getElaboratedType(ETK_None, SS, T);
768   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
769   ElabTL.setElaboratedKeywordLoc(SourceLocation());
770   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
771   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
772 }
773 
774 Sema::NameClassification
775 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
776                    SourceLocation NameLoc, const Token &NextToken,
777                    bool IsAddressOfOperand,
778                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
779   DeclarationNameInfo NameInfo(Name, NameLoc);
780   ObjCMethodDecl *CurMethod = getCurMethodDecl();
781 
782   if (NextToken.is(tok::coloncolon)) {
783     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
784                                 QualType(), false, SS, nullptr, false);
785   }
786 
787   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
788   LookupParsedName(Result, S, &SS, !CurMethod);
789 
790   // For unqualified lookup in a class template in MSVC mode, look into
791   // dependent base classes where the primary class template is known.
792   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
793     if (ParsedType TypeInBase =
794             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
795       return TypeInBase;
796   }
797 
798   // Perform lookup for Objective-C instance variables (including automatically
799   // synthesized instance variables), if we're in an Objective-C method.
800   // FIXME: This lookup really, really needs to be folded in to the normal
801   // unqualified lookup mechanism.
802   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
803     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
804     if (E.get() || E.isInvalid())
805       return E;
806   }
807 
808   bool SecondTry = false;
809   bool IsFilteredTemplateName = false;
810 
811 Corrected:
812   switch (Result.getResultKind()) {
813   case LookupResult::NotFound:
814     // If an unqualified-id is followed by a '(', then we have a function
815     // call.
816     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
817       // In C++, this is an ADL-only call.
818       // FIXME: Reference?
819       if (getLangOpts().CPlusPlus)
820         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
821 
822       // C90 6.3.2.2:
823       //   If the expression that precedes the parenthesized argument list in a
824       //   function call consists solely of an identifier, and if no
825       //   declaration is visible for this identifier, the identifier is
826       //   implicitly declared exactly as if, in the innermost block containing
827       //   the function call, the declaration
828       //
829       //     extern int identifier ();
830       //
831       //   appeared.
832       //
833       // We also allow this in C99 as an extension.
834       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
835         Result.addDecl(D);
836         Result.resolveKind();
837         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
838       }
839     }
840 
841     // In C, we first see whether there is a tag type by the same name, in
842     // which case it's likely that the user just forgot to write "enum",
843     // "struct", or "union".
844     if (!getLangOpts().CPlusPlus && !SecondTry &&
845         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
846       break;
847     }
848 
849     // Perform typo correction to determine if there is another name that is
850     // close to this name.
851     if (!SecondTry && CCC) {
852       SecondTry = true;
853       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
854                                                  Result.getLookupKind(), S,
855                                                  &SS, std::move(CCC),
856                                                  CTK_ErrorRecovery)) {
857         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
858         unsigned QualifiedDiag = diag::err_no_member_suggest;
859 
860         NamedDecl *FirstDecl = Corrected.getFoundDecl();
861         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
862         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
863             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
864           UnqualifiedDiag = diag::err_no_template_suggest;
865           QualifiedDiag = diag::err_no_member_template_suggest;
866         } else if (UnderlyingFirstDecl &&
867                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
868                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
869                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
870           UnqualifiedDiag = diag::err_unknown_typename_suggest;
871           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
872         }
873 
874         if (SS.isEmpty()) {
875           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
876         } else {// FIXME: is this even reachable? Test it.
877           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
878           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
879                                   Name->getName().equals(CorrectedStr);
880           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
881                                     << Name << computeDeclContext(SS, false)
882                                     << DroppedSpecifier << SS.getRange());
883         }
884 
885         // Update the name, so that the caller has the new name.
886         Name = Corrected.getCorrectionAsIdentifierInfo();
887 
888         // Typo correction corrected to a keyword.
889         if (Corrected.isKeyword())
890           return Name;
891 
892         // Also update the LookupResult...
893         // FIXME: This should probably go away at some point
894         Result.clear();
895         Result.setLookupName(Corrected.getCorrection());
896         if (FirstDecl)
897           Result.addDecl(FirstDecl);
898 
899         // If we found an Objective-C instance variable, let
900         // LookupInObjCMethod build the appropriate expression to
901         // reference the ivar.
902         // FIXME: This is a gross hack.
903         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
904           Result.clear();
905           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
906           return E;
907         }
908 
909         goto Corrected;
910       }
911     }
912 
913     // We failed to correct; just fall through and let the parser deal with it.
914     Result.suppressDiagnostics();
915     return NameClassification::Unknown();
916 
917   case LookupResult::NotFoundInCurrentInstantiation: {
918     // We performed name lookup into the current instantiation, and there were
919     // dependent bases, so we treat this result the same way as any other
920     // dependent nested-name-specifier.
921 
922     // C++ [temp.res]p2:
923     //   A name used in a template declaration or definition and that is
924     //   dependent on a template-parameter is assumed not to name a type
925     //   unless the applicable name lookup finds a type name or the name is
926     //   qualified by the keyword typename.
927     //
928     // FIXME: If the next token is '<', we might want to ask the parser to
929     // perform some heroics to see if we actually have a
930     // template-argument-list, which would indicate a missing 'template'
931     // keyword here.
932     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
933                                       NameInfo, IsAddressOfOperand,
934                                       /*TemplateArgs=*/nullptr);
935   }
936 
937   case LookupResult::Found:
938   case LookupResult::FoundOverloaded:
939   case LookupResult::FoundUnresolvedValue:
940     break;
941 
942   case LookupResult::Ambiguous:
943     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
944         hasAnyAcceptableTemplateNames(Result)) {
945       // C++ [temp.local]p3:
946       //   A lookup that finds an injected-class-name (10.2) can result in an
947       //   ambiguity in certain cases (for example, if it is found in more than
948       //   one base class). If all of the injected-class-names that are found
949       //   refer to specializations of the same class template, and if the name
950       //   is followed by a template-argument-list, the reference refers to the
951       //   class template itself and not a specialization thereof, and is not
952       //   ambiguous.
953       //
954       // This filtering can make an ambiguous result into an unambiguous one,
955       // so try again after filtering out template names.
956       FilterAcceptableTemplateNames(Result);
957       if (!Result.isAmbiguous()) {
958         IsFilteredTemplateName = true;
959         break;
960       }
961     }
962 
963     // Diagnose the ambiguity and return an error.
964     return NameClassification::Error();
965   }
966 
967   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
968       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
969     // C++ [temp.names]p3:
970     //   After name lookup (3.4) finds that a name is a template-name or that
971     //   an operator-function-id or a literal- operator-id refers to a set of
972     //   overloaded functions any member of which is a function template if
973     //   this is followed by a <, the < is always taken as the delimiter of a
974     //   template-argument-list and never as the less-than operator.
975     if (!IsFilteredTemplateName)
976       FilterAcceptableTemplateNames(Result);
977 
978     if (!Result.empty()) {
979       bool IsFunctionTemplate;
980       bool IsVarTemplate;
981       TemplateName Template;
982       if (Result.end() - Result.begin() > 1) {
983         IsFunctionTemplate = true;
984         Template = Context.getOverloadedTemplateName(Result.begin(),
985                                                      Result.end());
986       } else {
987         TemplateDecl *TD
988           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
989         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
990         IsVarTemplate = isa<VarTemplateDecl>(TD);
991 
992         if (SS.isSet() && !SS.isInvalid())
993           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
994                                                     /*TemplateKeyword=*/false,
995                                                       TD);
996         else
997           Template = TemplateName(TD);
998       }
999 
1000       if (IsFunctionTemplate) {
1001         // Function templates always go through overload resolution, at which
1002         // point we'll perform the various checks (e.g., accessibility) we need
1003         // to based on which function we selected.
1004         Result.suppressDiagnostics();
1005 
1006         return NameClassification::FunctionTemplate(Template);
1007       }
1008 
1009       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1010                            : NameClassification::TypeTemplate(Template);
1011     }
1012   }
1013 
1014   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1015   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1016     DiagnoseUseOfDecl(Type, NameLoc);
1017     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1018     QualType T = Context.getTypeDeclType(Type);
1019     if (SS.isNotEmpty())
1020       return buildNestedType(*this, SS, T, NameLoc);
1021     return ParsedType::make(T);
1022   }
1023 
1024   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1025   if (!Class) {
1026     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1027     if (ObjCCompatibleAliasDecl *Alias =
1028             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1029       Class = Alias->getClassInterface();
1030   }
1031 
1032   if (Class) {
1033     DiagnoseUseOfDecl(Class, NameLoc);
1034 
1035     if (NextToken.is(tok::period)) {
1036       // Interface. <something> is parsed as a property reference expression.
1037       // Just return "unknown" as a fall-through for now.
1038       Result.suppressDiagnostics();
1039       return NameClassification::Unknown();
1040     }
1041 
1042     QualType T = Context.getObjCInterfaceType(Class);
1043     return ParsedType::make(T);
1044   }
1045 
1046   // We can have a type template here if we're classifying a template argument.
1047   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1048     return NameClassification::TypeTemplate(
1049         TemplateName(cast<TemplateDecl>(FirstDecl)));
1050 
1051   // Check for a tag type hidden by a non-type decl in a few cases where it
1052   // seems likely a type is wanted instead of the non-type that was found.
1053   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1054   if ((NextToken.is(tok::identifier) ||
1055        (NextIsOp &&
1056         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1057       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1058     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1059     DiagnoseUseOfDecl(Type, NameLoc);
1060     QualType T = Context.getTypeDeclType(Type);
1061     if (SS.isNotEmpty())
1062       return buildNestedType(*this, SS, T, NameLoc);
1063     return ParsedType::make(T);
1064   }
1065 
1066   if (FirstDecl->isCXXClassMember())
1067     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1068                                            nullptr, S);
1069 
1070   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1071   return BuildDeclarationNameExpr(SS, Result, ADL);
1072 }
1073 
1074 // Determines the context to return to after temporarily entering a
1075 // context.  This depends in an unnecessarily complicated way on the
1076 // exact ordering of callbacks from the parser.
1077 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1078 
1079   // Functions defined inline within classes aren't parsed until we've
1080   // finished parsing the top-level class, so the top-level class is
1081   // the context we'll need to return to.
1082   // A Lambda call operator whose parent is a class must not be treated
1083   // as an inline member function.  A Lambda can be used legally
1084   // either as an in-class member initializer or a default argument.  These
1085   // are parsed once the class has been marked complete and so the containing
1086   // context would be the nested class (when the lambda is defined in one);
1087   // If the class is not complete, then the lambda is being used in an
1088   // ill-formed fashion (such as to specify the width of a bit-field, or
1089   // in an array-bound) - in which case we still want to return the
1090   // lexically containing DC (which could be a nested class).
1091   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1092     DC = DC->getLexicalParent();
1093 
1094     // A function not defined within a class will always return to its
1095     // lexical context.
1096     if (!isa<CXXRecordDecl>(DC))
1097       return DC;
1098 
1099     // A C++ inline method/friend is parsed *after* the topmost class
1100     // it was declared in is fully parsed ("complete");  the topmost
1101     // class is the context we need to return to.
1102     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1103       DC = RD;
1104 
1105     // Return the declaration context of the topmost class the inline method is
1106     // declared in.
1107     return DC;
1108   }
1109 
1110   return DC->getLexicalParent();
1111 }
1112 
1113 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1114   assert(getContainingDC(DC) == CurContext &&
1115       "The next DeclContext should be lexically contained in the current one.");
1116   CurContext = DC;
1117   S->setEntity(DC);
1118 }
1119 
1120 void Sema::PopDeclContext() {
1121   assert(CurContext && "DeclContext imbalance!");
1122 
1123   CurContext = getContainingDC(CurContext);
1124   assert(CurContext && "Popped translation unit!");
1125 }
1126 
1127 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1128                                                                     Decl *D) {
1129   // Unlike PushDeclContext, the context to which we return is not necessarily
1130   // the containing DC of TD, because the new context will be some pre-existing
1131   // TagDecl definition instead of a fresh one.
1132   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1133   CurContext = cast<TagDecl>(D)->getDefinition();
1134   assert(CurContext && "skipping definition of undefined tag");
1135   // Start lookups from the parent of the current context; we don't want to look
1136   // into the pre-existing complete definition.
1137   S->setEntity(CurContext->getLookupParent());
1138   return Result;
1139 }
1140 
1141 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1142   CurContext = static_cast<decltype(CurContext)>(Context);
1143 }
1144 
1145 /// EnterDeclaratorContext - Used when we must lookup names in the context
1146 /// of a declarator's nested name specifier.
1147 ///
1148 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1149   // C++0x [basic.lookup.unqual]p13:
1150   //   A name used in the definition of a static data member of class
1151   //   X (after the qualified-id of the static member) is looked up as
1152   //   if the name was used in a member function of X.
1153   // C++0x [basic.lookup.unqual]p14:
1154   //   If a variable member of a namespace is defined outside of the
1155   //   scope of its namespace then any name used in the definition of
1156   //   the variable member (after the declarator-id) is looked up as
1157   //   if the definition of the variable member occurred in its
1158   //   namespace.
1159   // Both of these imply that we should push a scope whose context
1160   // is the semantic context of the declaration.  We can't use
1161   // PushDeclContext here because that context is not necessarily
1162   // lexically contained in the current context.  Fortunately,
1163   // the containing scope should have the appropriate information.
1164 
1165   assert(!S->getEntity() && "scope already has entity");
1166 
1167 #ifndef NDEBUG
1168   Scope *Ancestor = S->getParent();
1169   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1170   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1171 #endif
1172 
1173   CurContext = DC;
1174   S->setEntity(DC);
1175 }
1176 
1177 void Sema::ExitDeclaratorContext(Scope *S) {
1178   assert(S->getEntity() == CurContext && "Context imbalance!");
1179 
1180   // Switch back to the lexical context.  The safety of this is
1181   // enforced by an assert in EnterDeclaratorContext.
1182   Scope *Ancestor = S->getParent();
1183   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1184   CurContext = Ancestor->getEntity();
1185 
1186   // We don't need to do anything with the scope, which is going to
1187   // disappear.
1188 }
1189 
1190 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1191   // We assume that the caller has already called
1192   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1193   FunctionDecl *FD = D->getAsFunction();
1194   if (!FD)
1195     return;
1196 
1197   // Same implementation as PushDeclContext, but enters the context
1198   // from the lexical parent, rather than the top-level class.
1199   assert(CurContext == FD->getLexicalParent() &&
1200     "The next DeclContext should be lexically contained in the current one.");
1201   CurContext = FD;
1202   S->setEntity(CurContext);
1203 
1204   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1205     ParmVarDecl *Param = FD->getParamDecl(P);
1206     // If the parameter has an identifier, then add it to the scope
1207     if (Param->getIdentifier()) {
1208       S->AddDecl(Param);
1209       IdResolver.AddDecl(Param);
1210     }
1211   }
1212 }
1213 
1214 void Sema::ActOnExitFunctionContext() {
1215   // Same implementation as PopDeclContext, but returns to the lexical parent,
1216   // rather than the top-level class.
1217   assert(CurContext && "DeclContext imbalance!");
1218   CurContext = CurContext->getLexicalParent();
1219   assert(CurContext && "Popped translation unit!");
1220 }
1221 
1222 /// \brief Determine whether we allow overloading of the function
1223 /// PrevDecl with another declaration.
1224 ///
1225 /// This routine determines whether overloading is possible, not
1226 /// whether some new function is actually an overload. It will return
1227 /// true in C++ (where we can always provide overloads) or, as an
1228 /// extension, in C when the previous function is already an
1229 /// overloaded function declaration or has the "overloadable"
1230 /// attribute.
1231 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1232                                        ASTContext &Context) {
1233   if (Context.getLangOpts().CPlusPlus)
1234     return true;
1235 
1236   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1237     return true;
1238 
1239   return (Previous.getResultKind() == LookupResult::Found
1240           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1241 }
1242 
1243 /// Add this decl to the scope shadowed decl chains.
1244 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1245   // Move up the scope chain until we find the nearest enclosing
1246   // non-transparent context. The declaration will be introduced into this
1247   // scope.
1248   while (S->getEntity() && S->getEntity()->isTransparentContext())
1249     S = S->getParent();
1250 
1251   // Add scoped declarations into their context, so that they can be
1252   // found later. Declarations without a context won't be inserted
1253   // into any context.
1254   if (AddToContext)
1255     CurContext->addDecl(D);
1256 
1257   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1258   // are function-local declarations.
1259   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1260       !D->getDeclContext()->getRedeclContext()->Equals(
1261         D->getLexicalDeclContext()->getRedeclContext()) &&
1262       !D->getLexicalDeclContext()->isFunctionOrMethod())
1263     return;
1264 
1265   // Template instantiations should also not be pushed into scope.
1266   if (isa<FunctionDecl>(D) &&
1267       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1268     return;
1269 
1270   // If this replaces anything in the current scope,
1271   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1272                                IEnd = IdResolver.end();
1273   for (; I != IEnd; ++I) {
1274     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1275       S->RemoveDecl(*I);
1276       IdResolver.RemoveDecl(*I);
1277 
1278       // Should only need to replace one decl.
1279       break;
1280     }
1281   }
1282 
1283   S->AddDecl(D);
1284 
1285   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1286     // Implicitly-generated labels may end up getting generated in an order that
1287     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1288     // the label at the appropriate place in the identifier chain.
1289     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1290       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1291       if (IDC == CurContext) {
1292         if (!S->isDeclScope(*I))
1293           continue;
1294       } else if (IDC->Encloses(CurContext))
1295         break;
1296     }
1297 
1298     IdResolver.InsertDeclAfter(I, D);
1299   } else {
1300     IdResolver.AddDecl(D);
1301   }
1302 }
1303 
1304 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1305   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1306     TUScope->AddDecl(D);
1307 }
1308 
1309 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1310                          bool AllowInlineNamespace) {
1311   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1312 }
1313 
1314 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1315   DeclContext *TargetDC = DC->getPrimaryContext();
1316   do {
1317     if (DeclContext *ScopeDC = S->getEntity())
1318       if (ScopeDC->getPrimaryContext() == TargetDC)
1319         return S;
1320   } while ((S = S->getParent()));
1321 
1322   return nullptr;
1323 }
1324 
1325 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1326                                             DeclContext*,
1327                                             ASTContext&);
1328 
1329 /// Filters out lookup results that don't fall within the given scope
1330 /// as determined by isDeclInScope.
1331 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1332                                 bool ConsiderLinkage,
1333                                 bool AllowInlineNamespace) {
1334   LookupResult::Filter F = R.makeFilter();
1335   while (F.hasNext()) {
1336     NamedDecl *D = F.next();
1337 
1338     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1339       continue;
1340 
1341     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1342       continue;
1343 
1344     F.erase();
1345   }
1346 
1347   F.done();
1348 }
1349 
1350 static bool isUsingDecl(NamedDecl *D) {
1351   return isa<UsingShadowDecl>(D) ||
1352          isa<UnresolvedUsingTypenameDecl>(D) ||
1353          isa<UnresolvedUsingValueDecl>(D);
1354 }
1355 
1356 /// Removes using shadow declarations from the lookup results.
1357 static void RemoveUsingDecls(LookupResult &R) {
1358   LookupResult::Filter F = R.makeFilter();
1359   while (F.hasNext())
1360     if (isUsingDecl(F.next()))
1361       F.erase();
1362 
1363   F.done();
1364 }
1365 
1366 /// \brief Check for this common pattern:
1367 /// @code
1368 /// class S {
1369 ///   S(const S&); // DO NOT IMPLEMENT
1370 ///   void operator=(const S&); // DO NOT IMPLEMENT
1371 /// };
1372 /// @endcode
1373 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1374   // FIXME: Should check for private access too but access is set after we get
1375   // the decl here.
1376   if (D->doesThisDeclarationHaveABody())
1377     return false;
1378 
1379   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1380     return CD->isCopyConstructor();
1381   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1382     return Method->isCopyAssignmentOperator();
1383   return false;
1384 }
1385 
1386 // We need this to handle
1387 //
1388 // typedef struct {
1389 //   void *foo() { return 0; }
1390 // } A;
1391 //
1392 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1393 // for example. If 'A', foo will have external linkage. If we have '*A',
1394 // foo will have no linkage. Since we can't know until we get to the end
1395 // of the typedef, this function finds out if D might have non-external linkage.
1396 // Callers should verify at the end of the TU if it D has external linkage or
1397 // not.
1398 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1399   const DeclContext *DC = D->getDeclContext();
1400   while (!DC->isTranslationUnit()) {
1401     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1402       if (!RD->hasNameForLinkage())
1403         return true;
1404     }
1405     DC = DC->getParent();
1406   }
1407 
1408   return !D->isExternallyVisible();
1409 }
1410 
1411 // FIXME: This needs to be refactored; some other isInMainFile users want
1412 // these semantics.
1413 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1414   if (S.TUKind != TU_Complete)
1415     return false;
1416   return S.SourceMgr.isInMainFile(Loc);
1417 }
1418 
1419 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1420   assert(D);
1421 
1422   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1423     return false;
1424 
1425   // Ignore all entities declared within templates, and out-of-line definitions
1426   // of members of class templates.
1427   if (D->getDeclContext()->isDependentContext() ||
1428       D->getLexicalDeclContext()->isDependentContext())
1429     return false;
1430 
1431   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1432     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1433       return false;
1434 
1435     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1436       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1437         return false;
1438     } else {
1439       // 'static inline' functions are defined in headers; don't warn.
1440       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1441         return false;
1442     }
1443 
1444     if (FD->doesThisDeclarationHaveABody() &&
1445         Context.DeclMustBeEmitted(FD))
1446       return false;
1447   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1448     // Constants and utility variables are defined in headers with internal
1449     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1450     // like "inline".)
1451     if (!isMainFileLoc(*this, VD->getLocation()))
1452       return false;
1453 
1454     if (Context.DeclMustBeEmitted(VD))
1455       return false;
1456 
1457     if (VD->isStaticDataMember() &&
1458         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1459       return false;
1460   } else {
1461     return false;
1462   }
1463 
1464   // Only warn for unused decls internal to the translation unit.
1465   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1466   // for inline functions defined in the main source file, for instance.
1467   return mightHaveNonExternalLinkage(D);
1468 }
1469 
1470 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1471   if (!D)
1472     return;
1473 
1474   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1475     const FunctionDecl *First = FD->getFirstDecl();
1476     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1477       return; // First should already be in the vector.
1478   }
1479 
1480   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1481     const VarDecl *First = VD->getFirstDecl();
1482     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1483       return; // First should already be in the vector.
1484   }
1485 
1486   if (ShouldWarnIfUnusedFileScopedDecl(D))
1487     UnusedFileScopedDecls.push_back(D);
1488 }
1489 
1490 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1491   if (D->isInvalidDecl())
1492     return false;
1493 
1494   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1495       D->hasAttr<ObjCPreciseLifetimeAttr>())
1496     return false;
1497 
1498   if (isa<LabelDecl>(D))
1499     return true;
1500 
1501   // Except for labels, we only care about unused decls that are local to
1502   // functions.
1503   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1504   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1505     // For dependent types, the diagnostic is deferred.
1506     WithinFunction =
1507         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1508   if (!WithinFunction)
1509     return false;
1510 
1511   if (isa<TypedefNameDecl>(D))
1512     return true;
1513 
1514   // White-list anything that isn't a local variable.
1515   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1516     return false;
1517 
1518   // Types of valid local variables should be complete, so this should succeed.
1519   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1520 
1521     // White-list anything with an __attribute__((unused)) type.
1522     QualType Ty = VD->getType();
1523 
1524     // Only look at the outermost level of typedef.
1525     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1526       if (TT->getDecl()->hasAttr<UnusedAttr>())
1527         return false;
1528     }
1529 
1530     // If we failed to complete the type for some reason, or if the type is
1531     // dependent, don't diagnose the variable.
1532     if (Ty->isIncompleteType() || Ty->isDependentType())
1533       return false;
1534 
1535     if (const TagType *TT = Ty->getAs<TagType>()) {
1536       const TagDecl *Tag = TT->getDecl();
1537       if (Tag->hasAttr<UnusedAttr>())
1538         return false;
1539 
1540       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1541         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1542           return false;
1543 
1544         if (const Expr *Init = VD->getInit()) {
1545           if (const ExprWithCleanups *Cleanups =
1546                   dyn_cast<ExprWithCleanups>(Init))
1547             Init = Cleanups->getSubExpr();
1548           const CXXConstructExpr *Construct =
1549             dyn_cast<CXXConstructExpr>(Init);
1550           if (Construct && !Construct->isElidable()) {
1551             CXXConstructorDecl *CD = Construct->getConstructor();
1552             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1553               return false;
1554           }
1555         }
1556       }
1557     }
1558 
1559     // TODO: __attribute__((unused)) templates?
1560   }
1561 
1562   return true;
1563 }
1564 
1565 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1566                                      FixItHint &Hint) {
1567   if (isa<LabelDecl>(D)) {
1568     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1569                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1570     if (AfterColon.isInvalid())
1571       return;
1572     Hint = FixItHint::CreateRemoval(CharSourceRange::
1573                                     getCharRange(D->getLocStart(), AfterColon));
1574   }
1575 }
1576 
1577 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1578   if (D->getTypeForDecl()->isDependentType())
1579     return;
1580 
1581   for (auto *TmpD : D->decls()) {
1582     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1583       DiagnoseUnusedDecl(T);
1584     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1585       DiagnoseUnusedNestedTypedefs(R);
1586   }
1587 }
1588 
1589 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1590 /// unless they are marked attr(unused).
1591 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1592   if (!ShouldDiagnoseUnusedDecl(D))
1593     return;
1594 
1595   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1596     // typedefs can be referenced later on, so the diagnostics are emitted
1597     // at end-of-translation-unit.
1598     UnusedLocalTypedefNameCandidates.insert(TD);
1599     return;
1600   }
1601 
1602   FixItHint Hint;
1603   GenerateFixForUnusedDecl(D, Context, Hint);
1604 
1605   unsigned DiagID;
1606   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1607     DiagID = diag::warn_unused_exception_param;
1608   else if (isa<LabelDecl>(D))
1609     DiagID = diag::warn_unused_label;
1610   else
1611     DiagID = diag::warn_unused_variable;
1612 
1613   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1614 }
1615 
1616 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1617   // Verify that we have no forward references left.  If so, there was a goto
1618   // or address of a label taken, but no definition of it.  Label fwd
1619   // definitions are indicated with a null substmt which is also not a resolved
1620   // MS inline assembly label name.
1621   bool Diagnose = false;
1622   if (L->isMSAsmLabel())
1623     Diagnose = !L->isResolvedMSAsmLabel();
1624   else
1625     Diagnose = L->getStmt() == nullptr;
1626   if (Diagnose)
1627     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1628 }
1629 
1630 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1631   S->mergeNRVOIntoParent();
1632 
1633   if (S->decl_empty()) return;
1634   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1635          "Scope shouldn't contain decls!");
1636 
1637   for (auto *TmpD : S->decls()) {
1638     assert(TmpD && "This decl didn't get pushed??");
1639 
1640     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1641     NamedDecl *D = cast<NamedDecl>(TmpD);
1642 
1643     if (!D->getDeclName()) continue;
1644 
1645     // Diagnose unused variables in this scope.
1646     if (!S->hasUnrecoverableErrorOccurred()) {
1647       DiagnoseUnusedDecl(D);
1648       if (const auto *RD = dyn_cast<RecordDecl>(D))
1649         DiagnoseUnusedNestedTypedefs(RD);
1650     }
1651 
1652     // If this was a forward reference to a label, verify it was defined.
1653     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1654       CheckPoppedLabel(LD, *this);
1655 
1656     // Remove this name from our lexical scope, and warn on it if we haven't
1657     // already.
1658     IdResolver.RemoveDecl(D);
1659     auto ShadowI = ShadowingDecls.find(D);
1660     if (ShadowI != ShadowingDecls.end()) {
1661       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1662         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1663             << D << FD << FD->getParent();
1664         Diag(FD->getLocation(), diag::note_previous_declaration);
1665       }
1666       ShadowingDecls.erase(ShadowI);
1667     }
1668   }
1669 }
1670 
1671 /// \brief Look for an Objective-C class in the translation unit.
1672 ///
1673 /// \param Id The name of the Objective-C class we're looking for. If
1674 /// typo-correction fixes this name, the Id will be updated
1675 /// to the fixed name.
1676 ///
1677 /// \param IdLoc The location of the name in the translation unit.
1678 ///
1679 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1680 /// if there is no class with the given name.
1681 ///
1682 /// \returns The declaration of the named Objective-C class, or NULL if the
1683 /// class could not be found.
1684 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1685                                               SourceLocation IdLoc,
1686                                               bool DoTypoCorrection) {
1687   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1688   // creation from this context.
1689   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1690 
1691   if (!IDecl && DoTypoCorrection) {
1692     // Perform typo correction at the given location, but only if we
1693     // find an Objective-C class name.
1694     if (TypoCorrection C = CorrectTypo(
1695             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1696             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1697             CTK_ErrorRecovery)) {
1698       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1699       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1700       Id = IDecl->getIdentifier();
1701     }
1702   }
1703   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1704   // This routine must always return a class definition, if any.
1705   if (Def && Def->getDefinition())
1706       Def = Def->getDefinition();
1707   return Def;
1708 }
1709 
1710 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1711 /// from S, where a non-field would be declared. This routine copes
1712 /// with the difference between C and C++ scoping rules in structs and
1713 /// unions. For example, the following code is well-formed in C but
1714 /// ill-formed in C++:
1715 /// @code
1716 /// struct S6 {
1717 ///   enum { BAR } e;
1718 /// };
1719 ///
1720 /// void test_S6() {
1721 ///   struct S6 a;
1722 ///   a.e = BAR;
1723 /// }
1724 /// @endcode
1725 /// For the declaration of BAR, this routine will return a different
1726 /// scope. The scope S will be the scope of the unnamed enumeration
1727 /// within S6. In C++, this routine will return the scope associated
1728 /// with S6, because the enumeration's scope is a transparent
1729 /// context but structures can contain non-field names. In C, this
1730 /// routine will return the translation unit scope, since the
1731 /// enumeration's scope is a transparent context and structures cannot
1732 /// contain non-field names.
1733 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1734   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1735          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1736          (S->isClassScope() && !getLangOpts().CPlusPlus))
1737     S = S->getParent();
1738   return S;
1739 }
1740 
1741 /// \brief Looks up the declaration of "struct objc_super" and
1742 /// saves it for later use in building builtin declaration of
1743 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1744 /// pre-existing declaration exists no action takes place.
1745 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1746                                         IdentifierInfo *II) {
1747   if (!II->isStr("objc_msgSendSuper"))
1748     return;
1749   ASTContext &Context = ThisSema.Context;
1750 
1751   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1752                       SourceLocation(), Sema::LookupTagName);
1753   ThisSema.LookupName(Result, S);
1754   if (Result.getResultKind() == LookupResult::Found)
1755     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1756       Context.setObjCSuperType(Context.getTagDeclType(TD));
1757 }
1758 
1759 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1760   switch (Error) {
1761   case ASTContext::GE_None:
1762     return "";
1763   case ASTContext::GE_Missing_stdio:
1764     return "stdio.h";
1765   case ASTContext::GE_Missing_setjmp:
1766     return "setjmp.h";
1767   case ASTContext::GE_Missing_ucontext:
1768     return "ucontext.h";
1769   }
1770   llvm_unreachable("unhandled error kind");
1771 }
1772 
1773 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1774 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1775 /// if we're creating this built-in in anticipation of redeclaring the
1776 /// built-in.
1777 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1778                                      Scope *S, bool ForRedeclaration,
1779                                      SourceLocation Loc) {
1780   LookupPredefedObjCSuperType(*this, S, II);
1781 
1782   ASTContext::GetBuiltinTypeError Error;
1783   QualType R = Context.GetBuiltinType(ID, Error);
1784   if (Error) {
1785     if (ForRedeclaration)
1786       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1787           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1788     return nullptr;
1789   }
1790 
1791   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1792     Diag(Loc, diag::ext_implicit_lib_function_decl)
1793         << Context.BuiltinInfo.getName(ID) << R;
1794     if (Context.BuiltinInfo.getHeaderName(ID) &&
1795         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1796       Diag(Loc, diag::note_include_header_or_declare)
1797           << Context.BuiltinInfo.getHeaderName(ID)
1798           << Context.BuiltinInfo.getName(ID);
1799   }
1800 
1801   if (R.isNull())
1802     return nullptr;
1803 
1804   DeclContext *Parent = Context.getTranslationUnitDecl();
1805   if (getLangOpts().CPlusPlus) {
1806     LinkageSpecDecl *CLinkageDecl =
1807         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1808                                 LinkageSpecDecl::lang_c, false);
1809     CLinkageDecl->setImplicit();
1810     Parent->addDecl(CLinkageDecl);
1811     Parent = CLinkageDecl;
1812   }
1813 
1814   FunctionDecl *New = FunctionDecl::Create(Context,
1815                                            Parent,
1816                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1817                                            SC_Extern,
1818                                            false,
1819                                            R->isFunctionProtoType());
1820   New->setImplicit();
1821 
1822   // Create Decl objects for each parameter, adding them to the
1823   // FunctionDecl.
1824   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1825     SmallVector<ParmVarDecl*, 16> Params;
1826     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1827       ParmVarDecl *parm =
1828           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1829                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1830                               SC_None, nullptr);
1831       parm->setScopeInfo(0, i);
1832       Params.push_back(parm);
1833     }
1834     New->setParams(Params);
1835   }
1836 
1837   AddKnownFunctionAttributes(New);
1838   RegisterLocallyScopedExternCDecl(New, S);
1839 
1840   // TUScope is the translation-unit scope to insert this function into.
1841   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1842   // relate Scopes to DeclContexts, and probably eliminate CurContext
1843   // entirely, but we're not there yet.
1844   DeclContext *SavedContext = CurContext;
1845   CurContext = Parent;
1846   PushOnScopeChains(New, TUScope);
1847   CurContext = SavedContext;
1848   return New;
1849 }
1850 
1851 /// Typedef declarations don't have linkage, but they still denote the same
1852 /// entity if their types are the same.
1853 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1854 /// isSameEntity.
1855 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1856                                                      TypedefNameDecl *Decl,
1857                                                      LookupResult &Previous) {
1858   // This is only interesting when modules are enabled.
1859   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1860     return;
1861 
1862   // Empty sets are uninteresting.
1863   if (Previous.empty())
1864     return;
1865 
1866   LookupResult::Filter Filter = Previous.makeFilter();
1867   while (Filter.hasNext()) {
1868     NamedDecl *Old = Filter.next();
1869 
1870     // Non-hidden declarations are never ignored.
1871     if (S.isVisible(Old))
1872       continue;
1873 
1874     // Declarations of the same entity are not ignored, even if they have
1875     // different linkages.
1876     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1877       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1878                                 Decl->getUnderlyingType()))
1879         continue;
1880 
1881       // If both declarations give a tag declaration a typedef name for linkage
1882       // purposes, then they declare the same entity.
1883       if (S.getLangOpts().CPlusPlus &&
1884           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1885           Decl->getAnonDeclWithTypedefName())
1886         continue;
1887     }
1888 
1889     Filter.erase();
1890   }
1891 
1892   Filter.done();
1893 }
1894 
1895 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1896   QualType OldType;
1897   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1898     OldType = OldTypedef->getUnderlyingType();
1899   else
1900     OldType = Context.getTypeDeclType(Old);
1901   QualType NewType = New->getUnderlyingType();
1902 
1903   if (NewType->isVariablyModifiedType()) {
1904     // Must not redefine a typedef with a variably-modified type.
1905     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1906     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1907       << Kind << NewType;
1908     if (Old->getLocation().isValid())
1909       Diag(Old->getLocation(), diag::note_previous_definition);
1910     New->setInvalidDecl();
1911     return true;
1912   }
1913 
1914   if (OldType != NewType &&
1915       !OldType->isDependentType() &&
1916       !NewType->isDependentType() &&
1917       !Context.hasSameType(OldType, NewType)) {
1918     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1919     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1920       << Kind << NewType << OldType;
1921     if (Old->getLocation().isValid())
1922       Diag(Old->getLocation(), diag::note_previous_definition);
1923     New->setInvalidDecl();
1924     return true;
1925   }
1926   return false;
1927 }
1928 
1929 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1930 /// same name and scope as a previous declaration 'Old'.  Figure out
1931 /// how to resolve this situation, merging decls or emitting
1932 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1933 ///
1934 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1935                                 LookupResult &OldDecls) {
1936   // If the new decl is known invalid already, don't bother doing any
1937   // merging checks.
1938   if (New->isInvalidDecl()) return;
1939 
1940   // Allow multiple definitions for ObjC built-in typedefs.
1941   // FIXME: Verify the underlying types are equivalent!
1942   if (getLangOpts().ObjC1) {
1943     const IdentifierInfo *TypeID = New->getIdentifier();
1944     switch (TypeID->getLength()) {
1945     default: break;
1946     case 2:
1947       {
1948         if (!TypeID->isStr("id"))
1949           break;
1950         QualType T = New->getUnderlyingType();
1951         if (!T->isPointerType())
1952           break;
1953         if (!T->isVoidPointerType()) {
1954           QualType PT = T->getAs<PointerType>()->getPointeeType();
1955           if (!PT->isStructureType())
1956             break;
1957         }
1958         Context.setObjCIdRedefinitionType(T);
1959         // Install the built-in type for 'id', ignoring the current definition.
1960         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1961         return;
1962       }
1963     case 5:
1964       if (!TypeID->isStr("Class"))
1965         break;
1966       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1967       // Install the built-in type for 'Class', ignoring the current definition.
1968       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1969       return;
1970     case 3:
1971       if (!TypeID->isStr("SEL"))
1972         break;
1973       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1974       // Install the built-in type for 'SEL', ignoring the current definition.
1975       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1976       return;
1977     }
1978     // Fall through - the typedef name was not a builtin type.
1979   }
1980 
1981   // Verify the old decl was also a type.
1982   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1983   if (!Old) {
1984     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1985       << New->getDeclName();
1986 
1987     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1988     if (OldD->getLocation().isValid())
1989       Diag(OldD->getLocation(), diag::note_previous_definition);
1990 
1991     return New->setInvalidDecl();
1992   }
1993 
1994   // If the old declaration is invalid, just give up here.
1995   if (Old->isInvalidDecl())
1996     return New->setInvalidDecl();
1997 
1998   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1999     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2000     auto *NewTag = New->getAnonDeclWithTypedefName();
2001     NamedDecl *Hidden = nullptr;
2002     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2003         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2004         !hasVisibleDefinition(OldTag, &Hidden)) {
2005       // There is a definition of this tag, but it is not visible. Use it
2006       // instead of our tag.
2007       New->setTypeForDecl(OldTD->getTypeForDecl());
2008       if (OldTD->isModed())
2009         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2010                                     OldTD->getUnderlyingType());
2011       else
2012         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2013 
2014       // Make the old tag definition visible.
2015       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
2016 
2017       // If this was an unscoped enumeration, yank all of its enumerators
2018       // out of the scope.
2019       if (isa<EnumDecl>(NewTag)) {
2020         Scope *EnumScope = getNonFieldDeclScope(S);
2021         for (auto *D : NewTag->decls()) {
2022           auto *ED = cast<EnumConstantDecl>(D);
2023           assert(EnumScope->isDeclScope(ED));
2024           EnumScope->RemoveDecl(ED);
2025           IdResolver.RemoveDecl(ED);
2026           ED->getLexicalDeclContext()->removeDecl(ED);
2027         }
2028       }
2029     }
2030   }
2031 
2032   // If the typedef types are not identical, reject them in all languages and
2033   // with any extensions enabled.
2034   if (isIncompatibleTypedef(Old, New))
2035     return;
2036 
2037   // The types match.  Link up the redeclaration chain and merge attributes if
2038   // the old declaration was a typedef.
2039   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2040     New->setPreviousDecl(Typedef);
2041     mergeDeclAttributes(New, Old);
2042   }
2043 
2044   if (getLangOpts().MicrosoftExt)
2045     return;
2046 
2047   if (getLangOpts().CPlusPlus) {
2048     // C++ [dcl.typedef]p2:
2049     //   In a given non-class scope, a typedef specifier can be used to
2050     //   redefine the name of any type declared in that scope to refer
2051     //   to the type to which it already refers.
2052     if (!isa<CXXRecordDecl>(CurContext))
2053       return;
2054 
2055     // C++0x [dcl.typedef]p4:
2056     //   In a given class scope, a typedef specifier can be used to redefine
2057     //   any class-name declared in that scope that is not also a typedef-name
2058     //   to refer to the type to which it already refers.
2059     //
2060     // This wording came in via DR424, which was a correction to the
2061     // wording in DR56, which accidentally banned code like:
2062     //
2063     //   struct S {
2064     //     typedef struct A { } A;
2065     //   };
2066     //
2067     // in the C++03 standard. We implement the C++0x semantics, which
2068     // allow the above but disallow
2069     //
2070     //   struct S {
2071     //     typedef int I;
2072     //     typedef int I;
2073     //   };
2074     //
2075     // since that was the intent of DR56.
2076     if (!isa<TypedefNameDecl>(Old))
2077       return;
2078 
2079     Diag(New->getLocation(), diag::err_redefinition)
2080       << New->getDeclName();
2081     Diag(Old->getLocation(), diag::note_previous_definition);
2082     return New->setInvalidDecl();
2083   }
2084 
2085   // Modules always permit redefinition of typedefs, as does C11.
2086   if (getLangOpts().Modules || getLangOpts().C11)
2087     return;
2088 
2089   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2090   // is normally mapped to an error, but can be controlled with
2091   // -Wtypedef-redefinition.  If either the original or the redefinition is
2092   // in a system header, don't emit this for compatibility with GCC.
2093   if (getDiagnostics().getSuppressSystemWarnings() &&
2094       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2095        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2096     return;
2097 
2098   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2099     << New->getDeclName();
2100   Diag(Old->getLocation(), diag::note_previous_definition);
2101 }
2102 
2103 /// DeclhasAttr - returns true if decl Declaration already has the target
2104 /// attribute.
2105 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2106   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2107   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2108   for (const auto *i : D->attrs())
2109     if (i->getKind() == A->getKind()) {
2110       if (Ann) {
2111         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2112           return true;
2113         continue;
2114       }
2115       // FIXME: Don't hardcode this check
2116       if (OA && isa<OwnershipAttr>(i))
2117         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2118       return true;
2119     }
2120 
2121   return false;
2122 }
2123 
2124 static bool isAttributeTargetADefinition(Decl *D) {
2125   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2126     return VD->isThisDeclarationADefinition();
2127   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2128     return TD->isCompleteDefinition() || TD->isBeingDefined();
2129   return true;
2130 }
2131 
2132 /// Merge alignment attributes from \p Old to \p New, taking into account the
2133 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2134 ///
2135 /// \return \c true if any attributes were added to \p New.
2136 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2137   // Look for alignas attributes on Old, and pick out whichever attribute
2138   // specifies the strictest alignment requirement.
2139   AlignedAttr *OldAlignasAttr = nullptr;
2140   AlignedAttr *OldStrictestAlignAttr = nullptr;
2141   unsigned OldAlign = 0;
2142   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2143     // FIXME: We have no way of representing inherited dependent alignments
2144     // in a case like:
2145     //   template<int A, int B> struct alignas(A) X;
2146     //   template<int A, int B> struct alignas(B) X {};
2147     // For now, we just ignore any alignas attributes which are not on the
2148     // definition in such a case.
2149     if (I->isAlignmentDependent())
2150       return false;
2151 
2152     if (I->isAlignas())
2153       OldAlignasAttr = I;
2154 
2155     unsigned Align = I->getAlignment(S.Context);
2156     if (Align > OldAlign) {
2157       OldAlign = Align;
2158       OldStrictestAlignAttr = I;
2159     }
2160   }
2161 
2162   // Look for alignas attributes on New.
2163   AlignedAttr *NewAlignasAttr = nullptr;
2164   unsigned NewAlign = 0;
2165   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2166     if (I->isAlignmentDependent())
2167       return false;
2168 
2169     if (I->isAlignas())
2170       NewAlignasAttr = I;
2171 
2172     unsigned Align = I->getAlignment(S.Context);
2173     if (Align > NewAlign)
2174       NewAlign = Align;
2175   }
2176 
2177   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2178     // Both declarations have 'alignas' attributes. We require them to match.
2179     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2180     // fall short. (If two declarations both have alignas, they must both match
2181     // every definition, and so must match each other if there is a definition.)
2182 
2183     // If either declaration only contains 'alignas(0)' specifiers, then it
2184     // specifies the natural alignment for the type.
2185     if (OldAlign == 0 || NewAlign == 0) {
2186       QualType Ty;
2187       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2188         Ty = VD->getType();
2189       else
2190         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2191 
2192       if (OldAlign == 0)
2193         OldAlign = S.Context.getTypeAlign(Ty);
2194       if (NewAlign == 0)
2195         NewAlign = S.Context.getTypeAlign(Ty);
2196     }
2197 
2198     if (OldAlign != NewAlign) {
2199       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2200         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2201         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2202       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2203     }
2204   }
2205 
2206   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2207     // C++11 [dcl.align]p6:
2208     //   if any declaration of an entity has an alignment-specifier,
2209     //   every defining declaration of that entity shall specify an
2210     //   equivalent alignment.
2211     // C11 6.7.5/7:
2212     //   If the definition of an object does not have an alignment
2213     //   specifier, any other declaration of that object shall also
2214     //   have no alignment specifier.
2215     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2216       << OldAlignasAttr;
2217     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2218       << OldAlignasAttr;
2219   }
2220 
2221   bool AnyAdded = false;
2222 
2223   // Ensure we have an attribute representing the strictest alignment.
2224   if (OldAlign > NewAlign) {
2225     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2226     Clone->setInherited(true);
2227     New->addAttr(Clone);
2228     AnyAdded = true;
2229   }
2230 
2231   // Ensure we have an alignas attribute if the old declaration had one.
2232   if (OldAlignasAttr && !NewAlignasAttr &&
2233       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2234     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2235     Clone->setInherited(true);
2236     New->addAttr(Clone);
2237     AnyAdded = true;
2238   }
2239 
2240   return AnyAdded;
2241 }
2242 
2243 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2244                                const InheritableAttr *Attr,
2245                                Sema::AvailabilityMergeKind AMK) {
2246   InheritableAttr *NewAttr = nullptr;
2247   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2248   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2249     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2250                                       AA->isImplicit(), AA->getIntroduced(),
2251                                       AA->getDeprecated(),
2252                                       AA->getObsoleted(), AA->getUnavailable(),
2253                                       AA->getMessage(), AA->getStrict(),
2254                                       AA->getReplacement(), AMK,
2255                                       AttrSpellingListIndex);
2256   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2257     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2258                                     AttrSpellingListIndex);
2259   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2260     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2261                                         AttrSpellingListIndex);
2262   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2263     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2264                                    AttrSpellingListIndex);
2265   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2266     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2267                                    AttrSpellingListIndex);
2268   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2269     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2270                                 FA->getFormatIdx(), FA->getFirstArg(),
2271                                 AttrSpellingListIndex);
2272   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2273     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2274                                  AttrSpellingListIndex);
2275   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2276     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2277                                        AttrSpellingListIndex,
2278                                        IA->getSemanticSpelling());
2279   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2280     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2281                                       &S.Context.Idents.get(AA->getSpelling()),
2282                                       AttrSpellingListIndex);
2283   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2284     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2285   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2286     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2287   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2288     NewAttr = S.mergeInternalLinkageAttr(
2289         D, InternalLinkageA->getRange(),
2290         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2291         AttrSpellingListIndex);
2292   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2293     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2294                                 &S.Context.Idents.get(CommonA->getSpelling()),
2295                                 AttrSpellingListIndex);
2296   else if (isa<AlignedAttr>(Attr))
2297     // AlignedAttrs are handled separately, because we need to handle all
2298     // such attributes on a declaration at the same time.
2299     NewAttr = nullptr;
2300   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2301            (AMK == Sema::AMK_Override ||
2302             AMK == Sema::AMK_ProtocolImplementation))
2303     NewAttr = nullptr;
2304   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2305     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2306 
2307   if (NewAttr) {
2308     NewAttr->setInherited(true);
2309     D->addAttr(NewAttr);
2310     if (isa<MSInheritanceAttr>(NewAttr))
2311       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2312     return true;
2313   }
2314 
2315   return false;
2316 }
2317 
2318 static const Decl *getDefinition(const Decl *D) {
2319   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2320     return TD->getDefinition();
2321   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2322     const VarDecl *Def = VD->getDefinition();
2323     if (Def)
2324       return Def;
2325     return VD->getActingDefinition();
2326   }
2327   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2328     const FunctionDecl* Def;
2329     if (FD->isDefined(Def))
2330       return Def;
2331   }
2332   return nullptr;
2333 }
2334 
2335 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2336   for (const auto *Attribute : D->attrs())
2337     if (Attribute->getKind() == Kind)
2338       return true;
2339   return false;
2340 }
2341 
2342 /// checkNewAttributesAfterDef - If we already have a definition, check that
2343 /// there are no new attributes in this declaration.
2344 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2345   if (!New->hasAttrs())
2346     return;
2347 
2348   const Decl *Def = getDefinition(Old);
2349   if (!Def || Def == New)
2350     return;
2351 
2352   AttrVec &NewAttributes = New->getAttrs();
2353   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2354     const Attr *NewAttribute = NewAttributes[I];
2355 
2356     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2357       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2358         Sema::SkipBodyInfo SkipBody;
2359         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2360 
2361         // If we're skipping this definition, drop the "alias" attribute.
2362         if (SkipBody.ShouldSkip) {
2363           NewAttributes.erase(NewAttributes.begin() + I);
2364           --E;
2365           continue;
2366         }
2367       } else {
2368         VarDecl *VD = cast<VarDecl>(New);
2369         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2370                                 VarDecl::TentativeDefinition
2371                             ? diag::err_alias_after_tentative
2372                             : diag::err_redefinition;
2373         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2374         S.Diag(Def->getLocation(), diag::note_previous_definition);
2375         VD->setInvalidDecl();
2376       }
2377       ++I;
2378       continue;
2379     }
2380 
2381     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2382       // Tentative definitions are only interesting for the alias check above.
2383       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2384         ++I;
2385         continue;
2386       }
2387     }
2388 
2389     if (hasAttribute(Def, NewAttribute->getKind())) {
2390       ++I;
2391       continue; // regular attr merging will take care of validating this.
2392     }
2393 
2394     if (isa<C11NoReturnAttr>(NewAttribute)) {
2395       // C's _Noreturn is allowed to be added to a function after it is defined.
2396       ++I;
2397       continue;
2398     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2399       if (AA->isAlignas()) {
2400         // C++11 [dcl.align]p6:
2401         //   if any declaration of an entity has an alignment-specifier,
2402         //   every defining declaration of that entity shall specify an
2403         //   equivalent alignment.
2404         // C11 6.7.5/7:
2405         //   If the definition of an object does not have an alignment
2406         //   specifier, any other declaration of that object shall also
2407         //   have no alignment specifier.
2408         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2409           << AA;
2410         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2411           << AA;
2412         NewAttributes.erase(NewAttributes.begin() + I);
2413         --E;
2414         continue;
2415       }
2416     }
2417 
2418     S.Diag(NewAttribute->getLocation(),
2419            diag::warn_attribute_precede_definition);
2420     S.Diag(Def->getLocation(), diag::note_previous_definition);
2421     NewAttributes.erase(NewAttributes.begin() + I);
2422     --E;
2423   }
2424 }
2425 
2426 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2427 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2428                                AvailabilityMergeKind AMK) {
2429   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2430     UsedAttr *NewAttr = OldAttr->clone(Context);
2431     NewAttr->setInherited(true);
2432     New->addAttr(NewAttr);
2433   }
2434 
2435   if (!Old->hasAttrs() && !New->hasAttrs())
2436     return;
2437 
2438   // Attributes declared post-definition are currently ignored.
2439   checkNewAttributesAfterDef(*this, New, Old);
2440 
2441   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2442     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2443       if (OldA->getLabel() != NewA->getLabel()) {
2444         // This redeclaration changes __asm__ label.
2445         Diag(New->getLocation(), diag::err_different_asm_label);
2446         Diag(OldA->getLocation(), diag::note_previous_declaration);
2447       }
2448     } else if (Old->isUsed()) {
2449       // This redeclaration adds an __asm__ label to a declaration that has
2450       // already been ODR-used.
2451       Diag(New->getLocation(), diag::err_late_asm_label_name)
2452         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2453     }
2454   }
2455 
2456   // Re-declaration cannot add abi_tag's.
2457   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2458     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2459       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2460         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2461                       NewTag) == OldAbiTagAttr->tags_end()) {
2462           Diag(NewAbiTagAttr->getLocation(),
2463                diag::err_new_abi_tag_on_redeclaration)
2464               << NewTag;
2465           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2466         }
2467       }
2468     } else {
2469       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2470       Diag(Old->getLocation(), diag::note_previous_declaration);
2471     }
2472   }
2473 
2474   if (!Old->hasAttrs())
2475     return;
2476 
2477   bool foundAny = New->hasAttrs();
2478 
2479   // Ensure that any moving of objects within the allocated map is done before
2480   // we process them.
2481   if (!foundAny) New->setAttrs(AttrVec());
2482 
2483   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2484     // Ignore deprecated/unavailable/availability attributes if requested.
2485     AvailabilityMergeKind LocalAMK = AMK_None;
2486     if (isa<DeprecatedAttr>(I) ||
2487         isa<UnavailableAttr>(I) ||
2488         isa<AvailabilityAttr>(I)) {
2489       switch (AMK) {
2490       case AMK_None:
2491         continue;
2492 
2493       case AMK_Redeclaration:
2494       case AMK_Override:
2495       case AMK_ProtocolImplementation:
2496         LocalAMK = AMK;
2497         break;
2498       }
2499     }
2500 
2501     // Already handled.
2502     if (isa<UsedAttr>(I))
2503       continue;
2504 
2505     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2506       foundAny = true;
2507   }
2508 
2509   if (mergeAlignedAttrs(*this, New, Old))
2510     foundAny = true;
2511 
2512   if (!foundAny) New->dropAttrs();
2513 }
2514 
2515 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2516 /// to the new one.
2517 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2518                                      const ParmVarDecl *oldDecl,
2519                                      Sema &S) {
2520   // C++11 [dcl.attr.depend]p2:
2521   //   The first declaration of a function shall specify the
2522   //   carries_dependency attribute for its declarator-id if any declaration
2523   //   of the function specifies the carries_dependency attribute.
2524   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2525   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2526     S.Diag(CDA->getLocation(),
2527            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2528     // Find the first declaration of the parameter.
2529     // FIXME: Should we build redeclaration chains for function parameters?
2530     const FunctionDecl *FirstFD =
2531       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2532     const ParmVarDecl *FirstVD =
2533       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2534     S.Diag(FirstVD->getLocation(),
2535            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2536   }
2537 
2538   if (!oldDecl->hasAttrs())
2539     return;
2540 
2541   bool foundAny = newDecl->hasAttrs();
2542 
2543   // Ensure that any moving of objects within the allocated map is
2544   // done before we process them.
2545   if (!foundAny) newDecl->setAttrs(AttrVec());
2546 
2547   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2548     if (!DeclHasAttr(newDecl, I)) {
2549       InheritableAttr *newAttr =
2550         cast<InheritableParamAttr>(I->clone(S.Context));
2551       newAttr->setInherited(true);
2552       newDecl->addAttr(newAttr);
2553       foundAny = true;
2554     }
2555   }
2556 
2557   if (!foundAny) newDecl->dropAttrs();
2558 }
2559 
2560 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2561                                 const ParmVarDecl *OldParam,
2562                                 Sema &S) {
2563   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2564     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2565       if (*Oldnullability != *Newnullability) {
2566         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2567           << DiagNullabilityKind(
2568                *Newnullability,
2569                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2570                 != 0))
2571           << DiagNullabilityKind(
2572                *Oldnullability,
2573                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2574                 != 0));
2575         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2576       }
2577     } else {
2578       QualType NewT = NewParam->getType();
2579       NewT = S.Context.getAttributedType(
2580                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2581                          NewT, NewT);
2582       NewParam->setType(NewT);
2583     }
2584   }
2585 }
2586 
2587 namespace {
2588 
2589 /// Used in MergeFunctionDecl to keep track of function parameters in
2590 /// C.
2591 struct GNUCompatibleParamWarning {
2592   ParmVarDecl *OldParm;
2593   ParmVarDecl *NewParm;
2594   QualType PromotedType;
2595 };
2596 
2597 } // end anonymous namespace
2598 
2599 /// getSpecialMember - get the special member enum for a method.
2600 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2601   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2602     if (Ctor->isDefaultConstructor())
2603       return Sema::CXXDefaultConstructor;
2604 
2605     if (Ctor->isCopyConstructor())
2606       return Sema::CXXCopyConstructor;
2607 
2608     if (Ctor->isMoveConstructor())
2609       return Sema::CXXMoveConstructor;
2610   } else if (isa<CXXDestructorDecl>(MD)) {
2611     return Sema::CXXDestructor;
2612   } else if (MD->isCopyAssignmentOperator()) {
2613     return Sema::CXXCopyAssignment;
2614   } else if (MD->isMoveAssignmentOperator()) {
2615     return Sema::CXXMoveAssignment;
2616   }
2617 
2618   return Sema::CXXInvalid;
2619 }
2620 
2621 // Determine whether the previous declaration was a definition, implicit
2622 // declaration, or a declaration.
2623 template <typename T>
2624 static std::pair<diag::kind, SourceLocation>
2625 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2626   diag::kind PrevDiag;
2627   SourceLocation OldLocation = Old->getLocation();
2628   if (Old->isThisDeclarationADefinition())
2629     PrevDiag = diag::note_previous_definition;
2630   else if (Old->isImplicit()) {
2631     PrevDiag = diag::note_previous_implicit_declaration;
2632     if (OldLocation.isInvalid())
2633       OldLocation = New->getLocation();
2634   } else
2635     PrevDiag = diag::note_previous_declaration;
2636   return std::make_pair(PrevDiag, OldLocation);
2637 }
2638 
2639 /// canRedefineFunction - checks if a function can be redefined. Currently,
2640 /// only extern inline functions can be redefined, and even then only in
2641 /// GNU89 mode.
2642 static bool canRedefineFunction(const FunctionDecl *FD,
2643                                 const LangOptions& LangOpts) {
2644   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2645           !LangOpts.CPlusPlus &&
2646           FD->isInlineSpecified() &&
2647           FD->getStorageClass() == SC_Extern);
2648 }
2649 
2650 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2651   const AttributedType *AT = T->getAs<AttributedType>();
2652   while (AT && !AT->isCallingConv())
2653     AT = AT->getModifiedType()->getAs<AttributedType>();
2654   return AT;
2655 }
2656 
2657 template <typename T>
2658 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2659   const DeclContext *DC = Old->getDeclContext();
2660   if (DC->isRecord())
2661     return false;
2662 
2663   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2664   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2665     return true;
2666   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2667     return true;
2668   return false;
2669 }
2670 
2671 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2672 static bool isExternC(VarTemplateDecl *) { return false; }
2673 
2674 /// \brief Check whether a redeclaration of an entity introduced by a
2675 /// using-declaration is valid, given that we know it's not an overload
2676 /// (nor a hidden tag declaration).
2677 template<typename ExpectedDecl>
2678 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2679                                    ExpectedDecl *New) {
2680   // C++11 [basic.scope.declarative]p4:
2681   //   Given a set of declarations in a single declarative region, each of
2682   //   which specifies the same unqualified name,
2683   //   -- they shall all refer to the same entity, or all refer to functions
2684   //      and function templates; or
2685   //   -- exactly one declaration shall declare a class name or enumeration
2686   //      name that is not a typedef name and the other declarations shall all
2687   //      refer to the same variable or enumerator, or all refer to functions
2688   //      and function templates; in this case the class name or enumeration
2689   //      name is hidden (3.3.10).
2690 
2691   // C++11 [namespace.udecl]p14:
2692   //   If a function declaration in namespace scope or block scope has the
2693   //   same name and the same parameter-type-list as a function introduced
2694   //   by a using-declaration, and the declarations do not declare the same
2695   //   function, the program is ill-formed.
2696 
2697   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2698   if (Old &&
2699       !Old->getDeclContext()->getRedeclContext()->Equals(
2700           New->getDeclContext()->getRedeclContext()) &&
2701       !(isExternC(Old) && isExternC(New)))
2702     Old = nullptr;
2703 
2704   if (!Old) {
2705     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2706     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2707     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2708     return true;
2709   }
2710   return false;
2711 }
2712 
2713 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2714                                             const FunctionDecl *B) {
2715   assert(A->getNumParams() == B->getNumParams());
2716 
2717   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2718     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2719     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2720     if (AttrA == AttrB)
2721       return true;
2722     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2723   };
2724 
2725   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2726 }
2727 
2728 /// MergeFunctionDecl - We just parsed a function 'New' from
2729 /// declarator D which has the same name and scope as a previous
2730 /// declaration 'Old'.  Figure out how to resolve this situation,
2731 /// merging decls or emitting diagnostics as appropriate.
2732 ///
2733 /// In C++, New and Old must be declarations that are not
2734 /// overloaded. Use IsOverload to determine whether New and Old are
2735 /// overloaded, and to select the Old declaration that New should be
2736 /// merged with.
2737 ///
2738 /// Returns true if there was an error, false otherwise.
2739 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2740                              Scope *S, bool MergeTypeWithOld) {
2741   // Verify the old decl was also a function.
2742   FunctionDecl *Old = OldD->getAsFunction();
2743   if (!Old) {
2744     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2745       if (New->getFriendObjectKind()) {
2746         Diag(New->getLocation(), diag::err_using_decl_friend);
2747         Diag(Shadow->getTargetDecl()->getLocation(),
2748              diag::note_using_decl_target);
2749         Diag(Shadow->getUsingDecl()->getLocation(),
2750              diag::note_using_decl) << 0;
2751         return true;
2752       }
2753 
2754       // Check whether the two declarations might declare the same function.
2755       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2756         return true;
2757       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2758     } else {
2759       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2760         << New->getDeclName();
2761       Diag(OldD->getLocation(), diag::note_previous_definition);
2762       return true;
2763     }
2764   }
2765 
2766   // If the old declaration is invalid, just give up here.
2767   if (Old->isInvalidDecl())
2768     return true;
2769 
2770   diag::kind PrevDiag;
2771   SourceLocation OldLocation;
2772   std::tie(PrevDiag, OldLocation) =
2773       getNoteDiagForInvalidRedeclaration(Old, New);
2774 
2775   // Don't complain about this if we're in GNU89 mode and the old function
2776   // is an extern inline function.
2777   // Don't complain about specializations. They are not supposed to have
2778   // storage classes.
2779   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2780       New->getStorageClass() == SC_Static &&
2781       Old->hasExternalFormalLinkage() &&
2782       !New->getTemplateSpecializationInfo() &&
2783       !canRedefineFunction(Old, getLangOpts())) {
2784     if (getLangOpts().MicrosoftExt) {
2785       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2786       Diag(OldLocation, PrevDiag);
2787     } else {
2788       Diag(New->getLocation(), diag::err_static_non_static) << New;
2789       Diag(OldLocation, PrevDiag);
2790       return true;
2791     }
2792   }
2793 
2794   if (New->hasAttr<InternalLinkageAttr>() &&
2795       !Old->hasAttr<InternalLinkageAttr>()) {
2796     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2797         << New->getDeclName();
2798     Diag(Old->getLocation(), diag::note_previous_definition);
2799     New->dropAttr<InternalLinkageAttr>();
2800   }
2801 
2802   // If a function is first declared with a calling convention, but is later
2803   // declared or defined without one, all following decls assume the calling
2804   // convention of the first.
2805   //
2806   // It's OK if a function is first declared without a calling convention,
2807   // but is later declared or defined with the default calling convention.
2808   //
2809   // To test if either decl has an explicit calling convention, we look for
2810   // AttributedType sugar nodes on the type as written.  If they are missing or
2811   // were canonicalized away, we assume the calling convention was implicit.
2812   //
2813   // Note also that we DO NOT return at this point, because we still have
2814   // other tests to run.
2815   QualType OldQType = Context.getCanonicalType(Old->getType());
2816   QualType NewQType = Context.getCanonicalType(New->getType());
2817   const FunctionType *OldType = cast<FunctionType>(OldQType);
2818   const FunctionType *NewType = cast<FunctionType>(NewQType);
2819   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2820   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2821   bool RequiresAdjustment = false;
2822 
2823   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2824     FunctionDecl *First = Old->getFirstDecl();
2825     const FunctionType *FT =
2826         First->getType().getCanonicalType()->castAs<FunctionType>();
2827     FunctionType::ExtInfo FI = FT->getExtInfo();
2828     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2829     if (!NewCCExplicit) {
2830       // Inherit the CC from the previous declaration if it was specified
2831       // there but not here.
2832       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2833       RequiresAdjustment = true;
2834     } else {
2835       // Calling conventions aren't compatible, so complain.
2836       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2837       Diag(New->getLocation(), diag::err_cconv_change)
2838         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2839         << !FirstCCExplicit
2840         << (!FirstCCExplicit ? "" :
2841             FunctionType::getNameForCallConv(FI.getCC()));
2842 
2843       // Put the note on the first decl, since it is the one that matters.
2844       Diag(First->getLocation(), diag::note_previous_declaration);
2845       return true;
2846     }
2847   }
2848 
2849   // FIXME: diagnose the other way around?
2850   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2851     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2852     RequiresAdjustment = true;
2853   }
2854 
2855   // Merge regparm attribute.
2856   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2857       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2858     if (NewTypeInfo.getHasRegParm()) {
2859       Diag(New->getLocation(), diag::err_regparm_mismatch)
2860         << NewType->getRegParmType()
2861         << OldType->getRegParmType();
2862       Diag(OldLocation, diag::note_previous_declaration);
2863       return true;
2864     }
2865 
2866     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2867     RequiresAdjustment = true;
2868   }
2869 
2870   // Merge ns_returns_retained attribute.
2871   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2872     if (NewTypeInfo.getProducesResult()) {
2873       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2874       Diag(OldLocation, diag::note_previous_declaration);
2875       return true;
2876     }
2877 
2878     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2879     RequiresAdjustment = true;
2880   }
2881 
2882   if (RequiresAdjustment) {
2883     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2884     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2885     New->setType(QualType(AdjustedType, 0));
2886     NewQType = Context.getCanonicalType(New->getType());
2887     NewType = cast<FunctionType>(NewQType);
2888   }
2889 
2890   // If this redeclaration makes the function inline, we may need to add it to
2891   // UndefinedButUsed.
2892   if (!Old->isInlined() && New->isInlined() &&
2893       !New->hasAttr<GNUInlineAttr>() &&
2894       !getLangOpts().GNUInline &&
2895       Old->isUsed(false) &&
2896       !Old->isDefined() && !New->isThisDeclarationADefinition())
2897     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2898                                            SourceLocation()));
2899 
2900   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2901   // about it.
2902   if (New->hasAttr<GNUInlineAttr>() &&
2903       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2904     UndefinedButUsed.erase(Old->getCanonicalDecl());
2905   }
2906 
2907   // If pass_object_size params don't match up perfectly, this isn't a valid
2908   // redeclaration.
2909   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2910       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2911     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2912         << New->getDeclName();
2913     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2914     return true;
2915   }
2916 
2917   if (getLangOpts().CPlusPlus) {
2918     // (C++98 13.1p2):
2919     //   Certain function declarations cannot be overloaded:
2920     //     -- Function declarations that differ only in the return type
2921     //        cannot be overloaded.
2922 
2923     // Go back to the type source info to compare the declared return types,
2924     // per C++1y [dcl.type.auto]p13:
2925     //   Redeclarations or specializations of a function or function template
2926     //   with a declared return type that uses a placeholder type shall also
2927     //   use that placeholder, not a deduced type.
2928     QualType OldDeclaredReturnType =
2929         (Old->getTypeSourceInfo()
2930              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2931              : OldType)->getReturnType();
2932     QualType NewDeclaredReturnType =
2933         (New->getTypeSourceInfo()
2934              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2935              : NewType)->getReturnType();
2936     QualType ResQT;
2937     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2938         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2939           New->isLocalExternDecl())) {
2940       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2941           OldDeclaredReturnType->isObjCObjectPointerType())
2942         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2943       if (ResQT.isNull()) {
2944         if (New->isCXXClassMember() && New->isOutOfLine())
2945           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2946               << New << New->getReturnTypeSourceRange();
2947         else
2948           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2949               << New->getReturnTypeSourceRange();
2950         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2951                                     << Old->getReturnTypeSourceRange();
2952         return true;
2953       }
2954       else
2955         NewQType = ResQT;
2956     }
2957 
2958     QualType OldReturnType = OldType->getReturnType();
2959     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2960     if (OldReturnType != NewReturnType) {
2961       // If this function has a deduced return type and has already been
2962       // defined, copy the deduced value from the old declaration.
2963       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2964       if (OldAT && OldAT->isDeduced()) {
2965         New->setType(
2966             SubstAutoType(New->getType(),
2967                           OldAT->isDependentType() ? Context.DependentTy
2968                                                    : OldAT->getDeducedType()));
2969         NewQType = Context.getCanonicalType(
2970             SubstAutoType(NewQType,
2971                           OldAT->isDependentType() ? Context.DependentTy
2972                                                    : OldAT->getDeducedType()));
2973       }
2974     }
2975 
2976     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2977     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2978     if (OldMethod && NewMethod) {
2979       // Preserve triviality.
2980       NewMethod->setTrivial(OldMethod->isTrivial());
2981 
2982       // MSVC allows explicit template specialization at class scope:
2983       // 2 CXXMethodDecls referring to the same function will be injected.
2984       // We don't want a redeclaration error.
2985       bool IsClassScopeExplicitSpecialization =
2986                               OldMethod->isFunctionTemplateSpecialization() &&
2987                               NewMethod->isFunctionTemplateSpecialization();
2988       bool isFriend = NewMethod->getFriendObjectKind();
2989 
2990       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2991           !IsClassScopeExplicitSpecialization) {
2992         //    -- Member function declarations with the same name and the
2993         //       same parameter types cannot be overloaded if any of them
2994         //       is a static member function declaration.
2995         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2996           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2997           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2998           return true;
2999         }
3000 
3001         // C++ [class.mem]p1:
3002         //   [...] A member shall not be declared twice in the
3003         //   member-specification, except that a nested class or member
3004         //   class template can be declared and then later defined.
3005         if (ActiveTemplateInstantiations.empty()) {
3006           unsigned NewDiag;
3007           if (isa<CXXConstructorDecl>(OldMethod))
3008             NewDiag = diag::err_constructor_redeclared;
3009           else if (isa<CXXDestructorDecl>(NewMethod))
3010             NewDiag = diag::err_destructor_redeclared;
3011           else if (isa<CXXConversionDecl>(NewMethod))
3012             NewDiag = diag::err_conv_function_redeclared;
3013           else
3014             NewDiag = diag::err_member_redeclared;
3015 
3016           Diag(New->getLocation(), NewDiag);
3017         } else {
3018           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3019             << New << New->getType();
3020         }
3021         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3022         return true;
3023 
3024       // Complain if this is an explicit declaration of a special
3025       // member that was initially declared implicitly.
3026       //
3027       // As an exception, it's okay to befriend such methods in order
3028       // to permit the implicit constructor/destructor/operator calls.
3029       } else if (OldMethod->isImplicit()) {
3030         if (isFriend) {
3031           NewMethod->setImplicit();
3032         } else {
3033           Diag(NewMethod->getLocation(),
3034                diag::err_definition_of_implicitly_declared_member)
3035             << New << getSpecialMember(OldMethod);
3036           return true;
3037         }
3038       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3039         Diag(NewMethod->getLocation(),
3040              diag::err_definition_of_explicitly_defaulted_member)
3041           << getSpecialMember(OldMethod);
3042         return true;
3043       }
3044     }
3045 
3046     // C++11 [dcl.attr.noreturn]p1:
3047     //   The first declaration of a function shall specify the noreturn
3048     //   attribute if any declaration of that function specifies the noreturn
3049     //   attribute.
3050     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3051     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3052       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3053       Diag(Old->getFirstDecl()->getLocation(),
3054            diag::note_noreturn_missing_first_decl);
3055     }
3056 
3057     // C++11 [dcl.attr.depend]p2:
3058     //   The first declaration of a function shall specify the
3059     //   carries_dependency attribute for its declarator-id if any declaration
3060     //   of the function specifies the carries_dependency attribute.
3061     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3062     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3063       Diag(CDA->getLocation(),
3064            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3065       Diag(Old->getFirstDecl()->getLocation(),
3066            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3067     }
3068 
3069     // (C++98 8.3.5p3):
3070     //   All declarations for a function shall agree exactly in both the
3071     //   return type and the parameter-type-list.
3072     // We also want to respect all the extended bits except noreturn.
3073 
3074     // noreturn should now match unless the old type info didn't have it.
3075     QualType OldQTypeForComparison = OldQType;
3076     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3077       assert(OldQType == QualType(OldType, 0));
3078       const FunctionType *OldTypeForComparison
3079         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3080       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3081       assert(OldQTypeForComparison.isCanonical());
3082     }
3083 
3084     if (haveIncompatibleLanguageLinkages(Old, New)) {
3085       // As a special case, retain the language linkage from previous
3086       // declarations of a friend function as an extension.
3087       //
3088       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3089       // and is useful because there's otherwise no way to specify language
3090       // linkage within class scope.
3091       //
3092       // Check cautiously as the friend object kind isn't yet complete.
3093       if (New->getFriendObjectKind() != Decl::FOK_None) {
3094         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3095         Diag(OldLocation, PrevDiag);
3096       } else {
3097         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3098         Diag(OldLocation, PrevDiag);
3099         return true;
3100       }
3101     }
3102 
3103     if (OldQTypeForComparison == NewQType)
3104       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3105 
3106     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3107         New->isLocalExternDecl()) {
3108       // It's OK if we couldn't merge types for a local function declaraton
3109       // if either the old or new type is dependent. We'll merge the types
3110       // when we instantiate the function.
3111       return false;
3112     }
3113 
3114     // Fall through for conflicting redeclarations and redefinitions.
3115   }
3116 
3117   // C: Function types need to be compatible, not identical. This handles
3118   // duplicate function decls like "void f(int); void f(enum X);" properly.
3119   if (!getLangOpts().CPlusPlus &&
3120       Context.typesAreCompatible(OldQType, NewQType)) {
3121     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3122     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3123     const FunctionProtoType *OldProto = nullptr;
3124     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3125         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3126       // The old declaration provided a function prototype, but the
3127       // new declaration does not. Merge in the prototype.
3128       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3129       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3130       NewQType =
3131           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3132                                   OldProto->getExtProtoInfo());
3133       New->setType(NewQType);
3134       New->setHasInheritedPrototype();
3135 
3136       // Synthesize parameters with the same types.
3137       SmallVector<ParmVarDecl*, 16> Params;
3138       for (const auto &ParamType : OldProto->param_types()) {
3139         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3140                                                  SourceLocation(), nullptr,
3141                                                  ParamType, /*TInfo=*/nullptr,
3142                                                  SC_None, nullptr);
3143         Param->setScopeInfo(0, Params.size());
3144         Param->setImplicit();
3145         Params.push_back(Param);
3146       }
3147 
3148       New->setParams(Params);
3149     }
3150 
3151     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3152   }
3153 
3154   // GNU C permits a K&R definition to follow a prototype declaration
3155   // if the declared types of the parameters in the K&R definition
3156   // match the types in the prototype declaration, even when the
3157   // promoted types of the parameters from the K&R definition differ
3158   // from the types in the prototype. GCC then keeps the types from
3159   // the prototype.
3160   //
3161   // If a variadic prototype is followed by a non-variadic K&R definition,
3162   // the K&R definition becomes variadic.  This is sort of an edge case, but
3163   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3164   // C99 6.9.1p8.
3165   if (!getLangOpts().CPlusPlus &&
3166       Old->hasPrototype() && !New->hasPrototype() &&
3167       New->getType()->getAs<FunctionProtoType>() &&
3168       Old->getNumParams() == New->getNumParams()) {
3169     SmallVector<QualType, 16> ArgTypes;
3170     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3171     const FunctionProtoType *OldProto
3172       = Old->getType()->getAs<FunctionProtoType>();
3173     const FunctionProtoType *NewProto
3174       = New->getType()->getAs<FunctionProtoType>();
3175 
3176     // Determine whether this is the GNU C extension.
3177     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3178                                                NewProto->getReturnType());
3179     bool LooseCompatible = !MergedReturn.isNull();
3180     for (unsigned Idx = 0, End = Old->getNumParams();
3181          LooseCompatible && Idx != End; ++Idx) {
3182       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3183       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3184       if (Context.typesAreCompatible(OldParm->getType(),
3185                                      NewProto->getParamType(Idx))) {
3186         ArgTypes.push_back(NewParm->getType());
3187       } else if (Context.typesAreCompatible(OldParm->getType(),
3188                                             NewParm->getType(),
3189                                             /*CompareUnqualified=*/true)) {
3190         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3191                                            NewProto->getParamType(Idx) };
3192         Warnings.push_back(Warn);
3193         ArgTypes.push_back(NewParm->getType());
3194       } else
3195         LooseCompatible = false;
3196     }
3197 
3198     if (LooseCompatible) {
3199       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3200         Diag(Warnings[Warn].NewParm->getLocation(),
3201              diag::ext_param_promoted_not_compatible_with_prototype)
3202           << Warnings[Warn].PromotedType
3203           << Warnings[Warn].OldParm->getType();
3204         if (Warnings[Warn].OldParm->getLocation().isValid())
3205           Diag(Warnings[Warn].OldParm->getLocation(),
3206                diag::note_previous_declaration);
3207       }
3208 
3209       if (MergeTypeWithOld)
3210         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3211                                              OldProto->getExtProtoInfo()));
3212       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3213     }
3214 
3215     // Fall through to diagnose conflicting types.
3216   }
3217 
3218   // A function that has already been declared has been redeclared or
3219   // defined with a different type; show an appropriate diagnostic.
3220 
3221   // If the previous declaration was an implicitly-generated builtin
3222   // declaration, then at the very least we should use a specialized note.
3223   unsigned BuiltinID;
3224   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3225     // If it's actually a library-defined builtin function like 'malloc'
3226     // or 'printf', just warn about the incompatible redeclaration.
3227     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3228       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3229       Diag(OldLocation, diag::note_previous_builtin_declaration)
3230         << Old << Old->getType();
3231 
3232       // If this is a global redeclaration, just forget hereafter
3233       // about the "builtin-ness" of the function.
3234       //
3235       // Doing this for local extern declarations is problematic.  If
3236       // the builtin declaration remains visible, a second invalid
3237       // local declaration will produce a hard error; if it doesn't
3238       // remain visible, a single bogus local redeclaration (which is
3239       // actually only a warning) could break all the downstream code.
3240       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3241         New->getIdentifier()->revertBuiltin();
3242 
3243       return false;
3244     }
3245 
3246     PrevDiag = diag::note_previous_builtin_declaration;
3247   }
3248 
3249   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3250   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3251   return true;
3252 }
3253 
3254 /// \brief Completes the merge of two function declarations that are
3255 /// known to be compatible.
3256 ///
3257 /// This routine handles the merging of attributes and other
3258 /// properties of function declarations from the old declaration to
3259 /// the new declaration, once we know that New is in fact a
3260 /// redeclaration of Old.
3261 ///
3262 /// \returns false
3263 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3264                                         Scope *S, bool MergeTypeWithOld) {
3265   // Merge the attributes
3266   mergeDeclAttributes(New, Old);
3267 
3268   // Merge "pure" flag.
3269   if (Old->isPure())
3270     New->setPure();
3271 
3272   // Merge "used" flag.
3273   if (Old->getMostRecentDecl()->isUsed(false))
3274     New->setIsUsed();
3275 
3276   // Merge attributes from the parameters.  These can mismatch with K&R
3277   // declarations.
3278   if (New->getNumParams() == Old->getNumParams())
3279       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3280         ParmVarDecl *NewParam = New->getParamDecl(i);
3281         ParmVarDecl *OldParam = Old->getParamDecl(i);
3282         mergeParamDeclAttributes(NewParam, OldParam, *this);
3283         mergeParamDeclTypes(NewParam, OldParam, *this);
3284       }
3285 
3286   if (getLangOpts().CPlusPlus)
3287     return MergeCXXFunctionDecl(New, Old, S);
3288 
3289   // Merge the function types so the we get the composite types for the return
3290   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3291   // was visible.
3292   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3293   if (!Merged.isNull() && MergeTypeWithOld)
3294     New->setType(Merged);
3295 
3296   return false;
3297 }
3298 
3299 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3300                                 ObjCMethodDecl *oldMethod) {
3301   // Merge the attributes, including deprecated/unavailable
3302   AvailabilityMergeKind MergeKind =
3303     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3304       ? AMK_ProtocolImplementation
3305       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3306                                                        : AMK_Override;
3307 
3308   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3309 
3310   // Merge attributes from the parameters.
3311   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3312                                        oe = oldMethod->param_end();
3313   for (ObjCMethodDecl::param_iterator
3314          ni = newMethod->param_begin(), ne = newMethod->param_end();
3315        ni != ne && oi != oe; ++ni, ++oi)
3316     mergeParamDeclAttributes(*ni, *oi, *this);
3317 
3318   CheckObjCMethodOverride(newMethod, oldMethod);
3319 }
3320 
3321 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3322   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3323 
3324   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3325          ? diag::err_redefinition_different_type
3326          : diag::err_redeclaration_different_type)
3327     << New->getDeclName() << New->getType() << Old->getType();
3328 
3329   diag::kind PrevDiag;
3330   SourceLocation OldLocation;
3331   std::tie(PrevDiag, OldLocation)
3332     = getNoteDiagForInvalidRedeclaration(Old, New);
3333   S.Diag(OldLocation, PrevDiag);
3334   New->setInvalidDecl();
3335 }
3336 
3337 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3338 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3339 /// emitting diagnostics as appropriate.
3340 ///
3341 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3342 /// to here in AddInitializerToDecl. We can't check them before the initializer
3343 /// is attached.
3344 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3345                              bool MergeTypeWithOld) {
3346   if (New->isInvalidDecl() || Old->isInvalidDecl())
3347     return;
3348 
3349   QualType MergedT;
3350   if (getLangOpts().CPlusPlus) {
3351     if (New->getType()->isUndeducedType()) {
3352       // We don't know what the new type is until the initializer is attached.
3353       return;
3354     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3355       // These could still be something that needs exception specs checked.
3356       return MergeVarDeclExceptionSpecs(New, Old);
3357     }
3358     // C++ [basic.link]p10:
3359     //   [...] the types specified by all declarations referring to a given
3360     //   object or function shall be identical, except that declarations for an
3361     //   array object can specify array types that differ by the presence or
3362     //   absence of a major array bound (8.3.4).
3363     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3364       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3365       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3366 
3367       // We are merging a variable declaration New into Old. If it has an array
3368       // bound, and that bound differs from Old's bound, we should diagnose the
3369       // mismatch.
3370       if (!NewArray->isIncompleteArrayType()) {
3371         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3372              PrevVD = PrevVD->getPreviousDecl()) {
3373           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3374           if (PrevVDTy->isIncompleteArrayType())
3375             continue;
3376 
3377           if (!Context.hasSameType(NewArray, PrevVDTy))
3378             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3379         }
3380       }
3381 
3382       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3383         if (Context.hasSameType(OldArray->getElementType(),
3384                                 NewArray->getElementType()))
3385           MergedT = New->getType();
3386       }
3387       // FIXME: Check visibility. New is hidden but has a complete type. If New
3388       // has no array bound, it should not inherit one from Old, if Old is not
3389       // visible.
3390       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3391         if (Context.hasSameType(OldArray->getElementType(),
3392                                 NewArray->getElementType()))
3393           MergedT = Old->getType();
3394       }
3395     }
3396     else if (New->getType()->isObjCObjectPointerType() &&
3397                Old->getType()->isObjCObjectPointerType()) {
3398       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3399                                               Old->getType());
3400     }
3401   } else {
3402     // C 6.2.7p2:
3403     //   All declarations that refer to the same object or function shall have
3404     //   compatible type.
3405     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3406   }
3407   if (MergedT.isNull()) {
3408     // It's OK if we couldn't merge types if either type is dependent, for a
3409     // block-scope variable. In other cases (static data members of class
3410     // templates, variable templates, ...), we require the types to be
3411     // equivalent.
3412     // FIXME: The C++ standard doesn't say anything about this.
3413     if ((New->getType()->isDependentType() ||
3414          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3415       // If the old type was dependent, we can't merge with it, so the new type
3416       // becomes dependent for now. We'll reproduce the original type when we
3417       // instantiate the TypeSourceInfo for the variable.
3418       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3419         New->setType(Context.DependentTy);
3420       return;
3421     }
3422     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3423   }
3424 
3425   // Don't actually update the type on the new declaration if the old
3426   // declaration was an extern declaration in a different scope.
3427   if (MergeTypeWithOld)
3428     New->setType(MergedT);
3429 }
3430 
3431 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3432                                   LookupResult &Previous) {
3433   // C11 6.2.7p4:
3434   //   For an identifier with internal or external linkage declared
3435   //   in a scope in which a prior declaration of that identifier is
3436   //   visible, if the prior declaration specifies internal or
3437   //   external linkage, the type of the identifier at the later
3438   //   declaration becomes the composite type.
3439   //
3440   // If the variable isn't visible, we do not merge with its type.
3441   if (Previous.isShadowed())
3442     return false;
3443 
3444   if (S.getLangOpts().CPlusPlus) {
3445     // C++11 [dcl.array]p3:
3446     //   If there is a preceding declaration of the entity in the same
3447     //   scope in which the bound was specified, an omitted array bound
3448     //   is taken to be the same as in that earlier declaration.
3449     return NewVD->isPreviousDeclInSameBlockScope() ||
3450            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3451             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3452   } else {
3453     // If the old declaration was function-local, don't merge with its
3454     // type unless we're in the same function.
3455     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3456            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3457   }
3458 }
3459 
3460 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3461 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3462 /// situation, merging decls or emitting diagnostics as appropriate.
3463 ///
3464 /// Tentative definition rules (C99 6.9.2p2) are checked by
3465 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3466 /// definitions here, since the initializer hasn't been attached.
3467 ///
3468 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3469   // If the new decl is already invalid, don't do any other checking.
3470   if (New->isInvalidDecl())
3471     return;
3472 
3473   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3474     return;
3475 
3476   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3477 
3478   // Verify the old decl was also a variable or variable template.
3479   VarDecl *Old = nullptr;
3480   VarTemplateDecl *OldTemplate = nullptr;
3481   if (Previous.isSingleResult()) {
3482     if (NewTemplate) {
3483       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3484       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3485 
3486       if (auto *Shadow =
3487               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3488         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3489           return New->setInvalidDecl();
3490     } else {
3491       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3492 
3493       if (auto *Shadow =
3494               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3495         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3496           return New->setInvalidDecl();
3497     }
3498   }
3499   if (!Old) {
3500     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3501       << New->getDeclName();
3502     Diag(Previous.getRepresentativeDecl()->getLocation(),
3503          diag::note_previous_definition);
3504     return New->setInvalidDecl();
3505   }
3506 
3507   // Ensure the template parameters are compatible.
3508   if (NewTemplate &&
3509       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3510                                       OldTemplate->getTemplateParameters(),
3511                                       /*Complain=*/true, TPL_TemplateMatch))
3512     return New->setInvalidDecl();
3513 
3514   // C++ [class.mem]p1:
3515   //   A member shall not be declared twice in the member-specification [...]
3516   //
3517   // Here, we need only consider static data members.
3518   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3519     Diag(New->getLocation(), diag::err_duplicate_member)
3520       << New->getIdentifier();
3521     Diag(Old->getLocation(), diag::note_previous_declaration);
3522     New->setInvalidDecl();
3523   }
3524 
3525   mergeDeclAttributes(New, Old);
3526   // Warn if an already-declared variable is made a weak_import in a subsequent
3527   // declaration
3528   if (New->hasAttr<WeakImportAttr>() &&
3529       Old->getStorageClass() == SC_None &&
3530       !Old->hasAttr<WeakImportAttr>()) {
3531     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3532     Diag(Old->getLocation(), diag::note_previous_definition);
3533     // Remove weak_import attribute on new declaration.
3534     New->dropAttr<WeakImportAttr>();
3535   }
3536 
3537   if (New->hasAttr<InternalLinkageAttr>() &&
3538       !Old->hasAttr<InternalLinkageAttr>()) {
3539     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3540         << New->getDeclName();
3541     Diag(Old->getLocation(), diag::note_previous_definition);
3542     New->dropAttr<InternalLinkageAttr>();
3543   }
3544 
3545   // Merge the types.
3546   VarDecl *MostRecent = Old->getMostRecentDecl();
3547   if (MostRecent != Old) {
3548     MergeVarDeclTypes(New, MostRecent,
3549                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3550     if (New->isInvalidDecl())
3551       return;
3552   }
3553 
3554   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3555   if (New->isInvalidDecl())
3556     return;
3557 
3558   diag::kind PrevDiag;
3559   SourceLocation OldLocation;
3560   std::tie(PrevDiag, OldLocation) =
3561       getNoteDiagForInvalidRedeclaration(Old, New);
3562 
3563   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3564   if (New->getStorageClass() == SC_Static &&
3565       !New->isStaticDataMember() &&
3566       Old->hasExternalFormalLinkage()) {
3567     if (getLangOpts().MicrosoftExt) {
3568       Diag(New->getLocation(), diag::ext_static_non_static)
3569           << New->getDeclName();
3570       Diag(OldLocation, PrevDiag);
3571     } else {
3572       Diag(New->getLocation(), diag::err_static_non_static)
3573           << New->getDeclName();
3574       Diag(OldLocation, PrevDiag);
3575       return New->setInvalidDecl();
3576     }
3577   }
3578   // C99 6.2.2p4:
3579   //   For an identifier declared with the storage-class specifier
3580   //   extern in a scope in which a prior declaration of that
3581   //   identifier is visible,23) if the prior declaration specifies
3582   //   internal or external linkage, the linkage of the identifier at
3583   //   the later declaration is the same as the linkage specified at
3584   //   the prior declaration. If no prior declaration is visible, or
3585   //   if the prior declaration specifies no linkage, then the
3586   //   identifier has external linkage.
3587   if (New->hasExternalStorage() && Old->hasLinkage())
3588     /* Okay */;
3589   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3590            !New->isStaticDataMember() &&
3591            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3592     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3593     Diag(OldLocation, PrevDiag);
3594     return New->setInvalidDecl();
3595   }
3596 
3597   // Check if extern is followed by non-extern and vice-versa.
3598   if (New->hasExternalStorage() &&
3599       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3600     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3601     Diag(OldLocation, PrevDiag);
3602     return New->setInvalidDecl();
3603   }
3604   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3605       !New->hasExternalStorage()) {
3606     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3607     Diag(OldLocation, PrevDiag);
3608     return New->setInvalidDecl();
3609   }
3610 
3611   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3612 
3613   // FIXME: The test for external storage here seems wrong? We still
3614   // need to check for mismatches.
3615   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3616       // Don't complain about out-of-line definitions of static members.
3617       !(Old->getLexicalDeclContext()->isRecord() &&
3618         !New->getLexicalDeclContext()->isRecord())) {
3619     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3620     Diag(OldLocation, PrevDiag);
3621     return New->setInvalidDecl();
3622   }
3623 
3624   if (New->getTLSKind() != Old->getTLSKind()) {
3625     if (!Old->getTLSKind()) {
3626       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3627       Diag(OldLocation, PrevDiag);
3628     } else if (!New->getTLSKind()) {
3629       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3630       Diag(OldLocation, PrevDiag);
3631     } else {
3632       // Do not allow redeclaration to change the variable between requiring
3633       // static and dynamic initialization.
3634       // FIXME: GCC allows this, but uses the TLS keyword on the first
3635       // declaration to determine the kind. Do we need to be compatible here?
3636       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3637         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3638       Diag(OldLocation, PrevDiag);
3639     }
3640   }
3641 
3642   // C++ doesn't have tentative definitions, so go right ahead and check here.
3643   VarDecl *Def;
3644   if (getLangOpts().CPlusPlus &&
3645       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3646       (Def = Old->getDefinition())) {
3647     NamedDecl *Hidden = nullptr;
3648     if (!hasVisibleDefinition(Def, &Hidden) &&
3649         (New->getFormalLinkage() == InternalLinkage ||
3650          New->getDescribedVarTemplate() ||
3651          New->getNumTemplateParameterLists() ||
3652          New->getDeclContext()->isDependentContext())) {
3653       // The previous definition is hidden, and multiple definitions are
3654       // permitted (in separate TUs). Form another definition of it.
3655     } else {
3656       Diag(New->getLocation(), diag::err_redefinition) << New;
3657       Diag(Def->getLocation(), diag::note_previous_definition);
3658       New->setInvalidDecl();
3659       return;
3660     }
3661   }
3662 
3663   if (haveIncompatibleLanguageLinkages(Old, New)) {
3664     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3665     Diag(OldLocation, PrevDiag);
3666     New->setInvalidDecl();
3667     return;
3668   }
3669 
3670   // Merge "used" flag.
3671   if (Old->getMostRecentDecl()->isUsed(false))
3672     New->setIsUsed();
3673 
3674   // Keep a chain of previous declarations.
3675   New->setPreviousDecl(Old);
3676   if (NewTemplate)
3677     NewTemplate->setPreviousDecl(OldTemplate);
3678 
3679   // Inherit access appropriately.
3680   New->setAccess(Old->getAccess());
3681   if (NewTemplate)
3682     NewTemplate->setAccess(New->getAccess());
3683 }
3684 
3685 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3686 /// no declarator (e.g. "struct foo;") is parsed.
3687 Decl *
3688 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3689                                  RecordDecl *&AnonRecord) {
3690   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3691                                     AnonRecord);
3692 }
3693 
3694 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3695 // disambiguate entities defined in different scopes.
3696 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3697 // compatibility.
3698 // We will pick our mangling number depending on which version of MSVC is being
3699 // targeted.
3700 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3701   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3702              ? S->getMSCurManglingNumber()
3703              : S->getMSLastManglingNumber();
3704 }
3705 
3706 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3707   if (!Context.getLangOpts().CPlusPlus)
3708     return;
3709 
3710   if (isa<CXXRecordDecl>(Tag->getParent())) {
3711     // If this tag is the direct child of a class, number it if
3712     // it is anonymous.
3713     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3714       return;
3715     MangleNumberingContext &MCtx =
3716         Context.getManglingNumberContext(Tag->getParent());
3717     Context.setManglingNumber(
3718         Tag, MCtx.getManglingNumber(
3719                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3720     return;
3721   }
3722 
3723   // If this tag isn't a direct child of a class, number it if it is local.
3724   Decl *ManglingContextDecl;
3725   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3726           Tag->getDeclContext(), ManglingContextDecl)) {
3727     Context.setManglingNumber(
3728         Tag, MCtx->getManglingNumber(
3729                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3730   }
3731 }
3732 
3733 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3734                                         TypedefNameDecl *NewTD) {
3735   if (TagFromDeclSpec->isInvalidDecl())
3736     return;
3737 
3738   // Do nothing if the tag already has a name for linkage purposes.
3739   if (TagFromDeclSpec->hasNameForLinkage())
3740     return;
3741 
3742   // A well-formed anonymous tag must always be a TUK_Definition.
3743   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3744 
3745   // The type must match the tag exactly;  no qualifiers allowed.
3746   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3747                            Context.getTagDeclType(TagFromDeclSpec))) {
3748     if (getLangOpts().CPlusPlus)
3749       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3750     return;
3751   }
3752 
3753   // If we've already computed linkage for the anonymous tag, then
3754   // adding a typedef name for the anonymous decl can change that
3755   // linkage, which might be a serious problem.  Diagnose this as
3756   // unsupported and ignore the typedef name.  TODO: we should
3757   // pursue this as a language defect and establish a formal rule
3758   // for how to handle it.
3759   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3760     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3761 
3762     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3763     tagLoc = getLocForEndOfToken(tagLoc);
3764 
3765     llvm::SmallString<40> textToInsert;
3766     textToInsert += ' ';
3767     textToInsert += NewTD->getIdentifier()->getName();
3768     Diag(tagLoc, diag::note_typedef_changes_linkage)
3769         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3770     return;
3771   }
3772 
3773   // Otherwise, set this is the anon-decl typedef for the tag.
3774   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3775 }
3776 
3777 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3778   switch (T) {
3779   case DeclSpec::TST_class:
3780     return 0;
3781   case DeclSpec::TST_struct:
3782     return 1;
3783   case DeclSpec::TST_interface:
3784     return 2;
3785   case DeclSpec::TST_union:
3786     return 3;
3787   case DeclSpec::TST_enum:
3788     return 4;
3789   default:
3790     llvm_unreachable("unexpected type specifier");
3791   }
3792 }
3793 
3794 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3795 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3796 /// parameters to cope with template friend declarations.
3797 Decl *
3798 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3799                                  MultiTemplateParamsArg TemplateParams,
3800                                  bool IsExplicitInstantiation,
3801                                  RecordDecl *&AnonRecord) {
3802   Decl *TagD = nullptr;
3803   TagDecl *Tag = nullptr;
3804   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3805       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3806       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3807       DS.getTypeSpecType() == DeclSpec::TST_union ||
3808       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3809     TagD = DS.getRepAsDecl();
3810 
3811     if (!TagD) // We probably had an error
3812       return nullptr;
3813 
3814     // Note that the above type specs guarantee that the
3815     // type rep is a Decl, whereas in many of the others
3816     // it's a Type.
3817     if (isa<TagDecl>(TagD))
3818       Tag = cast<TagDecl>(TagD);
3819     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3820       Tag = CTD->getTemplatedDecl();
3821   }
3822 
3823   if (Tag) {
3824     handleTagNumbering(Tag, S);
3825     Tag->setFreeStanding();
3826     if (Tag->isInvalidDecl())
3827       return Tag;
3828   }
3829 
3830   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3831     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3832     // or incomplete types shall not be restrict-qualified."
3833     if (TypeQuals & DeclSpec::TQ_restrict)
3834       Diag(DS.getRestrictSpecLoc(),
3835            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3836            << DS.getSourceRange();
3837   }
3838 
3839   if (DS.isConstexprSpecified()) {
3840     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3841     // and definitions of functions and variables.
3842     if (Tag)
3843       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3844           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3845     else
3846       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3847     // Don't emit warnings after this error.
3848     return TagD;
3849   }
3850 
3851   if (DS.isConceptSpecified()) {
3852     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3853     // either a function concept and its definition or a variable concept and
3854     // its initializer.
3855     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3856     return TagD;
3857   }
3858 
3859   DiagnoseFunctionSpecifiers(DS);
3860 
3861   if (DS.isFriendSpecified()) {
3862     // If we're dealing with a decl but not a TagDecl, assume that
3863     // whatever routines created it handled the friendship aspect.
3864     if (TagD && !Tag)
3865       return nullptr;
3866     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3867   }
3868 
3869   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3870   bool IsExplicitSpecialization =
3871     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3872   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3873       !IsExplicitInstantiation && !IsExplicitSpecialization &&
3874       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3875     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3876     // nested-name-specifier unless it is an explicit instantiation
3877     // or an explicit specialization.
3878     //
3879     // FIXME: We allow class template partial specializations here too, per the
3880     // obvious intent of DR1819.
3881     //
3882     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3883     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3884         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3885     return nullptr;
3886   }
3887 
3888   // Track whether this decl-specifier declares anything.
3889   bool DeclaresAnything = true;
3890 
3891   // Handle anonymous struct definitions.
3892   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3893     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3894         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3895       if (getLangOpts().CPlusPlus ||
3896           Record->getDeclContext()->isRecord()) {
3897         // If CurContext is a DeclContext that can contain statements,
3898         // RecursiveASTVisitor won't visit the decls that
3899         // BuildAnonymousStructOrUnion() will put into CurContext.
3900         // Also store them here so that they can be part of the
3901         // DeclStmt that gets created in this case.
3902         // FIXME: Also return the IndirectFieldDecls created by
3903         // BuildAnonymousStructOr union, for the same reason?
3904         if (CurContext->isFunctionOrMethod())
3905           AnonRecord = Record;
3906         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3907                                            Context.getPrintingPolicy());
3908       }
3909 
3910       DeclaresAnything = false;
3911     }
3912   }
3913 
3914   // C11 6.7.2.1p2:
3915   //   A struct-declaration that does not declare an anonymous structure or
3916   //   anonymous union shall contain a struct-declarator-list.
3917   //
3918   // This rule also existed in C89 and C99; the grammar for struct-declaration
3919   // did not permit a struct-declaration without a struct-declarator-list.
3920   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3921       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3922     // Check for Microsoft C extension: anonymous struct/union member.
3923     // Handle 2 kinds of anonymous struct/union:
3924     //   struct STRUCT;
3925     //   union UNION;
3926     // and
3927     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3928     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3929     if ((Tag && Tag->getDeclName()) ||
3930         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3931       RecordDecl *Record = nullptr;
3932       if (Tag)
3933         Record = dyn_cast<RecordDecl>(Tag);
3934       else if (const RecordType *RT =
3935                    DS.getRepAsType().get()->getAsStructureType())
3936         Record = RT->getDecl();
3937       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3938         Record = UT->getDecl();
3939 
3940       if (Record && getLangOpts().MicrosoftExt) {
3941         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3942           << Record->isUnion() << DS.getSourceRange();
3943         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3944       }
3945 
3946       DeclaresAnything = false;
3947     }
3948   }
3949 
3950   // Skip all the checks below if we have a type error.
3951   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3952       (TagD && TagD->isInvalidDecl()))
3953     return TagD;
3954 
3955   if (getLangOpts().CPlusPlus &&
3956       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3957     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3958       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3959           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3960         DeclaresAnything = false;
3961 
3962   if (!DS.isMissingDeclaratorOk()) {
3963     // Customize diagnostic for a typedef missing a name.
3964     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3965       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3966         << DS.getSourceRange();
3967     else
3968       DeclaresAnything = false;
3969   }
3970 
3971   if (DS.isModulePrivateSpecified() &&
3972       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3973     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3974       << Tag->getTagKind()
3975       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3976 
3977   ActOnDocumentableDecl(TagD);
3978 
3979   // C 6.7/2:
3980   //   A declaration [...] shall declare at least a declarator [...], a tag,
3981   //   or the members of an enumeration.
3982   // C++ [dcl.dcl]p3:
3983   //   [If there are no declarators], and except for the declaration of an
3984   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3985   //   names into the program, or shall redeclare a name introduced by a
3986   //   previous declaration.
3987   if (!DeclaresAnything) {
3988     // In C, we allow this as a (popular) extension / bug. Don't bother
3989     // producing further diagnostics for redundant qualifiers after this.
3990     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3991     return TagD;
3992   }
3993 
3994   // C++ [dcl.stc]p1:
3995   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3996   //   init-declarator-list of the declaration shall not be empty.
3997   // C++ [dcl.fct.spec]p1:
3998   //   If a cv-qualifier appears in a decl-specifier-seq, the
3999   //   init-declarator-list of the declaration shall not be empty.
4000   //
4001   // Spurious qualifiers here appear to be valid in C.
4002   unsigned DiagID = diag::warn_standalone_specifier;
4003   if (getLangOpts().CPlusPlus)
4004     DiagID = diag::ext_standalone_specifier;
4005 
4006   // Note that a linkage-specification sets a storage class, but
4007   // 'extern "C" struct foo;' is actually valid and not theoretically
4008   // useless.
4009   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4010     if (SCS == DeclSpec::SCS_mutable)
4011       // Since mutable is not a viable storage class specifier in C, there is
4012       // no reason to treat it as an extension. Instead, diagnose as an error.
4013       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4014     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4015       Diag(DS.getStorageClassSpecLoc(), DiagID)
4016         << DeclSpec::getSpecifierName(SCS);
4017   }
4018 
4019   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4020     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4021       << DeclSpec::getSpecifierName(TSCS);
4022   if (DS.getTypeQualifiers()) {
4023     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4024       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4025     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4026       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4027     // Restrict is covered above.
4028     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4029       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4030     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4031       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4032   }
4033 
4034   // Warn about ignored type attributes, for example:
4035   // __attribute__((aligned)) struct A;
4036   // Attributes should be placed after tag to apply to type declaration.
4037   if (!DS.getAttributes().empty()) {
4038     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4039     if (TypeSpecType == DeclSpec::TST_class ||
4040         TypeSpecType == DeclSpec::TST_struct ||
4041         TypeSpecType == DeclSpec::TST_interface ||
4042         TypeSpecType == DeclSpec::TST_union ||
4043         TypeSpecType == DeclSpec::TST_enum) {
4044       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4045            attrs = attrs->getNext())
4046         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4047             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4048     }
4049   }
4050 
4051   return TagD;
4052 }
4053 
4054 /// We are trying to inject an anonymous member into the given scope;
4055 /// check if there's an existing declaration that can't be overloaded.
4056 ///
4057 /// \return true if this is a forbidden redeclaration
4058 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4059                                          Scope *S,
4060                                          DeclContext *Owner,
4061                                          DeclarationName Name,
4062                                          SourceLocation NameLoc,
4063                                          bool IsUnion) {
4064   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4065                  Sema::ForRedeclaration);
4066   if (!SemaRef.LookupName(R, S)) return false;
4067 
4068   // Pick a representative declaration.
4069   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4070   assert(PrevDecl && "Expected a non-null Decl");
4071 
4072   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4073     return false;
4074 
4075   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4076     << IsUnion << Name;
4077   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4078 
4079   return true;
4080 }
4081 
4082 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4083 /// anonymous struct or union AnonRecord into the owning context Owner
4084 /// and scope S. This routine will be invoked just after we realize
4085 /// that an unnamed union or struct is actually an anonymous union or
4086 /// struct, e.g.,
4087 ///
4088 /// @code
4089 /// union {
4090 ///   int i;
4091 ///   float f;
4092 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4093 ///    // f into the surrounding scope.x
4094 /// @endcode
4095 ///
4096 /// This routine is recursive, injecting the names of nested anonymous
4097 /// structs/unions into the owning context and scope as well.
4098 static bool
4099 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4100                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4101                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4102   bool Invalid = false;
4103 
4104   // Look every FieldDecl and IndirectFieldDecl with a name.
4105   for (auto *D : AnonRecord->decls()) {
4106     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4107         cast<NamedDecl>(D)->getDeclName()) {
4108       ValueDecl *VD = cast<ValueDecl>(D);
4109       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4110                                        VD->getLocation(),
4111                                        AnonRecord->isUnion())) {
4112         // C++ [class.union]p2:
4113         //   The names of the members of an anonymous union shall be
4114         //   distinct from the names of any other entity in the
4115         //   scope in which the anonymous union is declared.
4116         Invalid = true;
4117       } else {
4118         // C++ [class.union]p2:
4119         //   For the purpose of name lookup, after the anonymous union
4120         //   definition, the members of the anonymous union are
4121         //   considered to have been defined in the scope in which the
4122         //   anonymous union is declared.
4123         unsigned OldChainingSize = Chaining.size();
4124         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4125           Chaining.append(IF->chain_begin(), IF->chain_end());
4126         else
4127           Chaining.push_back(VD);
4128 
4129         assert(Chaining.size() >= 2);
4130         NamedDecl **NamedChain =
4131           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4132         for (unsigned i = 0; i < Chaining.size(); i++)
4133           NamedChain[i] = Chaining[i];
4134 
4135         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4136             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4137             VD->getType(), NamedChain, Chaining.size());
4138 
4139         for (const auto *Attr : VD->attrs())
4140           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4141 
4142         IndirectField->setAccess(AS);
4143         IndirectField->setImplicit();
4144         SemaRef.PushOnScopeChains(IndirectField, S);
4145 
4146         // That includes picking up the appropriate access specifier.
4147         if (AS != AS_none) IndirectField->setAccess(AS);
4148 
4149         Chaining.resize(OldChainingSize);
4150       }
4151     }
4152   }
4153 
4154   return Invalid;
4155 }
4156 
4157 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4158 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4159 /// illegal input values are mapped to SC_None.
4160 static StorageClass
4161 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4162   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4163   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4164          "Parser allowed 'typedef' as storage class VarDecl.");
4165   switch (StorageClassSpec) {
4166   case DeclSpec::SCS_unspecified:    return SC_None;
4167   case DeclSpec::SCS_extern:
4168     if (DS.isExternInLinkageSpec())
4169       return SC_None;
4170     return SC_Extern;
4171   case DeclSpec::SCS_static:         return SC_Static;
4172   case DeclSpec::SCS_auto:           return SC_Auto;
4173   case DeclSpec::SCS_register:       return SC_Register;
4174   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4175     // Illegal SCSs map to None: error reporting is up to the caller.
4176   case DeclSpec::SCS_mutable:        // Fall through.
4177   case DeclSpec::SCS_typedef:        return SC_None;
4178   }
4179   llvm_unreachable("unknown storage class specifier");
4180 }
4181 
4182 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4183   assert(Record->hasInClassInitializer());
4184 
4185   for (const auto *I : Record->decls()) {
4186     const auto *FD = dyn_cast<FieldDecl>(I);
4187     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4188       FD = IFD->getAnonField();
4189     if (FD && FD->hasInClassInitializer())
4190       return FD->getLocation();
4191   }
4192 
4193   llvm_unreachable("couldn't find in-class initializer");
4194 }
4195 
4196 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4197                                       SourceLocation DefaultInitLoc) {
4198   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4199     return;
4200 
4201   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4202   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4203 }
4204 
4205 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4206                                       CXXRecordDecl *AnonUnion) {
4207   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4208     return;
4209 
4210   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4211 }
4212 
4213 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4214 /// anonymous structure or union. Anonymous unions are a C++ feature
4215 /// (C++ [class.union]) and a C11 feature; anonymous structures
4216 /// are a C11 feature and GNU C++ extension.
4217 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4218                                         AccessSpecifier AS,
4219                                         RecordDecl *Record,
4220                                         const PrintingPolicy &Policy) {
4221   DeclContext *Owner = Record->getDeclContext();
4222 
4223   // Diagnose whether this anonymous struct/union is an extension.
4224   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4225     Diag(Record->getLocation(), diag::ext_anonymous_union);
4226   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4227     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4228   else if (!Record->isUnion() && !getLangOpts().C11)
4229     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4230 
4231   // C and C++ require different kinds of checks for anonymous
4232   // structs/unions.
4233   bool Invalid = false;
4234   if (getLangOpts().CPlusPlus) {
4235     const char *PrevSpec = nullptr;
4236     unsigned DiagID;
4237     if (Record->isUnion()) {
4238       // C++ [class.union]p6:
4239       //   Anonymous unions declared in a named namespace or in the
4240       //   global namespace shall be declared static.
4241       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4242           (isa<TranslationUnitDecl>(Owner) ||
4243            (isa<NamespaceDecl>(Owner) &&
4244             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4245         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4246           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4247 
4248         // Recover by adding 'static'.
4249         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4250                                PrevSpec, DiagID, Policy);
4251       }
4252       // C++ [class.union]p6:
4253       //   A storage class is not allowed in a declaration of an
4254       //   anonymous union in a class scope.
4255       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4256                isa<RecordDecl>(Owner)) {
4257         Diag(DS.getStorageClassSpecLoc(),
4258              diag::err_anonymous_union_with_storage_spec)
4259           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4260 
4261         // Recover by removing the storage specifier.
4262         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4263                                SourceLocation(),
4264                                PrevSpec, DiagID, Context.getPrintingPolicy());
4265       }
4266     }
4267 
4268     // Ignore const/volatile/restrict qualifiers.
4269     if (DS.getTypeQualifiers()) {
4270       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4271         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4272           << Record->isUnion() << "const"
4273           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4274       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4275         Diag(DS.getVolatileSpecLoc(),
4276              diag::ext_anonymous_struct_union_qualified)
4277           << Record->isUnion() << "volatile"
4278           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4279       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4280         Diag(DS.getRestrictSpecLoc(),
4281              diag::ext_anonymous_struct_union_qualified)
4282           << Record->isUnion() << "restrict"
4283           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4284       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4285         Diag(DS.getAtomicSpecLoc(),
4286              diag::ext_anonymous_struct_union_qualified)
4287           << Record->isUnion() << "_Atomic"
4288           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4289       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4290         Diag(DS.getUnalignedSpecLoc(),
4291              diag::ext_anonymous_struct_union_qualified)
4292           << Record->isUnion() << "__unaligned"
4293           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4294 
4295       DS.ClearTypeQualifiers();
4296     }
4297 
4298     // C++ [class.union]p2:
4299     //   The member-specification of an anonymous union shall only
4300     //   define non-static data members. [Note: nested types and
4301     //   functions cannot be declared within an anonymous union. ]
4302     for (auto *Mem : Record->decls()) {
4303       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4304         // C++ [class.union]p3:
4305         //   An anonymous union shall not have private or protected
4306         //   members (clause 11).
4307         assert(FD->getAccess() != AS_none);
4308         if (FD->getAccess() != AS_public) {
4309           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4310             << Record->isUnion() << (FD->getAccess() == AS_protected);
4311           Invalid = true;
4312         }
4313 
4314         // C++ [class.union]p1
4315         //   An object of a class with a non-trivial constructor, a non-trivial
4316         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4317         //   assignment operator cannot be a member of a union, nor can an
4318         //   array of such objects.
4319         if (CheckNontrivialField(FD))
4320           Invalid = true;
4321       } else if (Mem->isImplicit()) {
4322         // Any implicit members are fine.
4323       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4324         // This is a type that showed up in an
4325         // elaborated-type-specifier inside the anonymous struct or
4326         // union, but which actually declares a type outside of the
4327         // anonymous struct or union. It's okay.
4328       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4329         if (!MemRecord->isAnonymousStructOrUnion() &&
4330             MemRecord->getDeclName()) {
4331           // Visual C++ allows type definition in anonymous struct or union.
4332           if (getLangOpts().MicrosoftExt)
4333             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4334               << Record->isUnion();
4335           else {
4336             // This is a nested type declaration.
4337             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4338               << Record->isUnion();
4339             Invalid = true;
4340           }
4341         } else {
4342           // This is an anonymous type definition within another anonymous type.
4343           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4344           // not part of standard C++.
4345           Diag(MemRecord->getLocation(),
4346                diag::ext_anonymous_record_with_anonymous_type)
4347             << Record->isUnion();
4348         }
4349       } else if (isa<AccessSpecDecl>(Mem)) {
4350         // Any access specifier is fine.
4351       } else if (isa<StaticAssertDecl>(Mem)) {
4352         // In C++1z, static_assert declarations are also fine.
4353       } else {
4354         // We have something that isn't a non-static data
4355         // member. Complain about it.
4356         unsigned DK = diag::err_anonymous_record_bad_member;
4357         if (isa<TypeDecl>(Mem))
4358           DK = diag::err_anonymous_record_with_type;
4359         else if (isa<FunctionDecl>(Mem))
4360           DK = diag::err_anonymous_record_with_function;
4361         else if (isa<VarDecl>(Mem))
4362           DK = diag::err_anonymous_record_with_static;
4363 
4364         // Visual C++ allows type definition in anonymous struct or union.
4365         if (getLangOpts().MicrosoftExt &&
4366             DK == diag::err_anonymous_record_with_type)
4367           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4368             << Record->isUnion();
4369         else {
4370           Diag(Mem->getLocation(), DK) << Record->isUnion();
4371           Invalid = true;
4372         }
4373       }
4374     }
4375 
4376     // C++11 [class.union]p8 (DR1460):
4377     //   At most one variant member of a union may have a
4378     //   brace-or-equal-initializer.
4379     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4380         Owner->isRecord())
4381       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4382                                 cast<CXXRecordDecl>(Record));
4383   }
4384 
4385   if (!Record->isUnion() && !Owner->isRecord()) {
4386     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4387       << getLangOpts().CPlusPlus;
4388     Invalid = true;
4389   }
4390 
4391   // Mock up a declarator.
4392   Declarator Dc(DS, Declarator::MemberContext);
4393   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4394   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4395 
4396   // Create a declaration for this anonymous struct/union.
4397   NamedDecl *Anon = nullptr;
4398   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4399     Anon = FieldDecl::Create(Context, OwningClass,
4400                              DS.getLocStart(),
4401                              Record->getLocation(),
4402                              /*IdentifierInfo=*/nullptr,
4403                              Context.getTypeDeclType(Record),
4404                              TInfo,
4405                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4406                              /*InitStyle=*/ICIS_NoInit);
4407     Anon->setAccess(AS);
4408     if (getLangOpts().CPlusPlus)
4409       FieldCollector->Add(cast<FieldDecl>(Anon));
4410   } else {
4411     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4412     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4413     if (SCSpec == DeclSpec::SCS_mutable) {
4414       // mutable can only appear on non-static class members, so it's always
4415       // an error here
4416       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4417       Invalid = true;
4418       SC = SC_None;
4419     }
4420 
4421     Anon = VarDecl::Create(Context, Owner,
4422                            DS.getLocStart(),
4423                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4424                            Context.getTypeDeclType(Record),
4425                            TInfo, SC);
4426 
4427     // Default-initialize the implicit variable. This initialization will be
4428     // trivial in almost all cases, except if a union member has an in-class
4429     // initializer:
4430     //   union { int n = 0; };
4431     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4432   }
4433   Anon->setImplicit();
4434 
4435   // Mark this as an anonymous struct/union type.
4436   Record->setAnonymousStructOrUnion(true);
4437 
4438   // Add the anonymous struct/union object to the current
4439   // context. We'll be referencing this object when we refer to one of
4440   // its members.
4441   Owner->addDecl(Anon);
4442 
4443   // Inject the members of the anonymous struct/union into the owning
4444   // context and into the identifier resolver chain for name lookup
4445   // purposes.
4446   SmallVector<NamedDecl*, 2> Chain;
4447   Chain.push_back(Anon);
4448 
4449   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4450     Invalid = true;
4451 
4452   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4453     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4454       Decl *ManglingContextDecl;
4455       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4456               NewVD->getDeclContext(), ManglingContextDecl)) {
4457         Context.setManglingNumber(
4458             NewVD, MCtx->getManglingNumber(
4459                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4460         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4461       }
4462     }
4463   }
4464 
4465   if (Invalid)
4466     Anon->setInvalidDecl();
4467 
4468   return Anon;
4469 }
4470 
4471 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4472 /// Microsoft C anonymous structure.
4473 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4474 /// Example:
4475 ///
4476 /// struct A { int a; };
4477 /// struct B { struct A; int b; };
4478 ///
4479 /// void foo() {
4480 ///   B var;
4481 ///   var.a = 3;
4482 /// }
4483 ///
4484 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4485                                            RecordDecl *Record) {
4486   assert(Record && "expected a record!");
4487 
4488   // Mock up a declarator.
4489   Declarator Dc(DS, Declarator::TypeNameContext);
4490   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4491   assert(TInfo && "couldn't build declarator info for anonymous struct");
4492 
4493   auto *ParentDecl = cast<RecordDecl>(CurContext);
4494   QualType RecTy = Context.getTypeDeclType(Record);
4495 
4496   // Create a declaration for this anonymous struct.
4497   NamedDecl *Anon = FieldDecl::Create(Context,
4498                              ParentDecl,
4499                              DS.getLocStart(),
4500                              DS.getLocStart(),
4501                              /*IdentifierInfo=*/nullptr,
4502                              RecTy,
4503                              TInfo,
4504                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4505                              /*InitStyle=*/ICIS_NoInit);
4506   Anon->setImplicit();
4507 
4508   // Add the anonymous struct object to the current context.
4509   CurContext->addDecl(Anon);
4510 
4511   // Inject the members of the anonymous struct into the current
4512   // context and into the identifier resolver chain for name lookup
4513   // purposes.
4514   SmallVector<NamedDecl*, 2> Chain;
4515   Chain.push_back(Anon);
4516 
4517   RecordDecl *RecordDef = Record->getDefinition();
4518   if (RequireCompleteType(Anon->getLocation(), RecTy,
4519                           diag::err_field_incomplete) ||
4520       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4521                                           AS_none, Chain)) {
4522     Anon->setInvalidDecl();
4523     ParentDecl->setInvalidDecl();
4524   }
4525 
4526   return Anon;
4527 }
4528 
4529 /// GetNameForDeclarator - Determine the full declaration name for the
4530 /// given Declarator.
4531 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4532   return GetNameFromUnqualifiedId(D.getName());
4533 }
4534 
4535 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4536 DeclarationNameInfo
4537 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4538   DeclarationNameInfo NameInfo;
4539   NameInfo.setLoc(Name.StartLocation);
4540 
4541   switch (Name.getKind()) {
4542 
4543   case UnqualifiedId::IK_ImplicitSelfParam:
4544   case UnqualifiedId::IK_Identifier:
4545     NameInfo.setName(Name.Identifier);
4546     NameInfo.setLoc(Name.StartLocation);
4547     return NameInfo;
4548 
4549   case UnqualifiedId::IK_OperatorFunctionId:
4550     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4551                                            Name.OperatorFunctionId.Operator));
4552     NameInfo.setLoc(Name.StartLocation);
4553     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4554       = Name.OperatorFunctionId.SymbolLocations[0];
4555     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4556       = Name.EndLocation.getRawEncoding();
4557     return NameInfo;
4558 
4559   case UnqualifiedId::IK_LiteralOperatorId:
4560     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4561                                                            Name.Identifier));
4562     NameInfo.setLoc(Name.StartLocation);
4563     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4564     return NameInfo;
4565 
4566   case UnqualifiedId::IK_ConversionFunctionId: {
4567     TypeSourceInfo *TInfo;
4568     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4569     if (Ty.isNull())
4570       return DeclarationNameInfo();
4571     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4572                                                Context.getCanonicalType(Ty)));
4573     NameInfo.setLoc(Name.StartLocation);
4574     NameInfo.setNamedTypeInfo(TInfo);
4575     return NameInfo;
4576   }
4577 
4578   case UnqualifiedId::IK_ConstructorName: {
4579     TypeSourceInfo *TInfo;
4580     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4581     if (Ty.isNull())
4582       return DeclarationNameInfo();
4583     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4584                                               Context.getCanonicalType(Ty)));
4585     NameInfo.setLoc(Name.StartLocation);
4586     NameInfo.setNamedTypeInfo(TInfo);
4587     return NameInfo;
4588   }
4589 
4590   case UnqualifiedId::IK_ConstructorTemplateId: {
4591     // In well-formed code, we can only have a constructor
4592     // template-id that refers to the current context, so go there
4593     // to find the actual type being constructed.
4594     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4595     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4596       return DeclarationNameInfo();
4597 
4598     // Determine the type of the class being constructed.
4599     QualType CurClassType = Context.getTypeDeclType(CurClass);
4600 
4601     // FIXME: Check two things: that the template-id names the same type as
4602     // CurClassType, and that the template-id does not occur when the name
4603     // was qualified.
4604 
4605     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4606                                     Context.getCanonicalType(CurClassType)));
4607     NameInfo.setLoc(Name.StartLocation);
4608     // FIXME: should we retrieve TypeSourceInfo?
4609     NameInfo.setNamedTypeInfo(nullptr);
4610     return NameInfo;
4611   }
4612 
4613   case UnqualifiedId::IK_DestructorName: {
4614     TypeSourceInfo *TInfo;
4615     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4616     if (Ty.isNull())
4617       return DeclarationNameInfo();
4618     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4619                                               Context.getCanonicalType(Ty)));
4620     NameInfo.setLoc(Name.StartLocation);
4621     NameInfo.setNamedTypeInfo(TInfo);
4622     return NameInfo;
4623   }
4624 
4625   case UnqualifiedId::IK_TemplateId: {
4626     TemplateName TName = Name.TemplateId->Template.get();
4627     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4628     return Context.getNameForTemplate(TName, TNameLoc);
4629   }
4630 
4631   } // switch (Name.getKind())
4632 
4633   llvm_unreachable("Unknown name kind");
4634 }
4635 
4636 static QualType getCoreType(QualType Ty) {
4637   do {
4638     if (Ty->isPointerType() || Ty->isReferenceType())
4639       Ty = Ty->getPointeeType();
4640     else if (Ty->isArrayType())
4641       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4642     else
4643       return Ty.withoutLocalFastQualifiers();
4644   } while (true);
4645 }
4646 
4647 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4648 /// and Definition have "nearly" matching parameters. This heuristic is
4649 /// used to improve diagnostics in the case where an out-of-line function
4650 /// definition doesn't match any declaration within the class or namespace.
4651 /// Also sets Params to the list of indices to the parameters that differ
4652 /// between the declaration and the definition. If hasSimilarParameters
4653 /// returns true and Params is empty, then all of the parameters match.
4654 static bool hasSimilarParameters(ASTContext &Context,
4655                                      FunctionDecl *Declaration,
4656                                      FunctionDecl *Definition,
4657                                      SmallVectorImpl<unsigned> &Params) {
4658   Params.clear();
4659   if (Declaration->param_size() != Definition->param_size())
4660     return false;
4661   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4662     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4663     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4664 
4665     // The parameter types are identical
4666     if (Context.hasSameType(DefParamTy, DeclParamTy))
4667       continue;
4668 
4669     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4670     QualType DefParamBaseTy = getCoreType(DefParamTy);
4671     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4672     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4673 
4674     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4675         (DeclTyName && DeclTyName == DefTyName))
4676       Params.push_back(Idx);
4677     else  // The two parameters aren't even close
4678       return false;
4679   }
4680 
4681   return true;
4682 }
4683 
4684 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4685 /// declarator needs to be rebuilt in the current instantiation.
4686 /// Any bits of declarator which appear before the name are valid for
4687 /// consideration here.  That's specifically the type in the decl spec
4688 /// and the base type in any member-pointer chunks.
4689 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4690                                                     DeclarationName Name) {
4691   // The types we specifically need to rebuild are:
4692   //   - typenames, typeofs, and decltypes
4693   //   - types which will become injected class names
4694   // Of course, we also need to rebuild any type referencing such a
4695   // type.  It's safest to just say "dependent", but we call out a
4696   // few cases here.
4697 
4698   DeclSpec &DS = D.getMutableDeclSpec();
4699   switch (DS.getTypeSpecType()) {
4700   case DeclSpec::TST_typename:
4701   case DeclSpec::TST_typeofType:
4702   case DeclSpec::TST_underlyingType:
4703   case DeclSpec::TST_atomic: {
4704     // Grab the type from the parser.
4705     TypeSourceInfo *TSI = nullptr;
4706     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4707     if (T.isNull() || !T->isDependentType()) break;
4708 
4709     // Make sure there's a type source info.  This isn't really much
4710     // of a waste; most dependent types should have type source info
4711     // attached already.
4712     if (!TSI)
4713       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4714 
4715     // Rebuild the type in the current instantiation.
4716     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4717     if (!TSI) return true;
4718 
4719     // Store the new type back in the decl spec.
4720     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4721     DS.UpdateTypeRep(LocType);
4722     break;
4723   }
4724 
4725   case DeclSpec::TST_decltype:
4726   case DeclSpec::TST_typeofExpr: {
4727     Expr *E = DS.getRepAsExpr();
4728     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4729     if (Result.isInvalid()) return true;
4730     DS.UpdateExprRep(Result.get());
4731     break;
4732   }
4733 
4734   default:
4735     // Nothing to do for these decl specs.
4736     break;
4737   }
4738 
4739   // It doesn't matter what order we do this in.
4740   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4741     DeclaratorChunk &Chunk = D.getTypeObject(I);
4742 
4743     // The only type information in the declarator which can come
4744     // before the declaration name is the base type of a member
4745     // pointer.
4746     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4747       continue;
4748 
4749     // Rebuild the scope specifier in-place.
4750     CXXScopeSpec &SS = Chunk.Mem.Scope();
4751     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4752       return true;
4753   }
4754 
4755   return false;
4756 }
4757 
4758 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4759   D.setFunctionDefinitionKind(FDK_Declaration);
4760   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4761 
4762   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4763       Dcl && Dcl->getDeclContext()->isFileContext())
4764     Dcl->setTopLevelDeclInObjCContainer();
4765 
4766   return Dcl;
4767 }
4768 
4769 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4770 ///   If T is the name of a class, then each of the following shall have a
4771 ///   name different from T:
4772 ///     - every static data member of class T;
4773 ///     - every member function of class T
4774 ///     - every member of class T that is itself a type;
4775 /// \returns true if the declaration name violates these rules.
4776 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4777                                    DeclarationNameInfo NameInfo) {
4778   DeclarationName Name = NameInfo.getName();
4779 
4780   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4781   while (Record && Record->isAnonymousStructOrUnion())
4782     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4783   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4784     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4785     return true;
4786   }
4787 
4788   return false;
4789 }
4790 
4791 /// \brief Diagnose a declaration whose declarator-id has the given
4792 /// nested-name-specifier.
4793 ///
4794 /// \param SS The nested-name-specifier of the declarator-id.
4795 ///
4796 /// \param DC The declaration context to which the nested-name-specifier
4797 /// resolves.
4798 ///
4799 /// \param Name The name of the entity being declared.
4800 ///
4801 /// \param Loc The location of the name of the entity being declared.
4802 ///
4803 /// \returns true if we cannot safely recover from this error, false otherwise.
4804 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4805                                         DeclarationName Name,
4806                                         SourceLocation Loc) {
4807   DeclContext *Cur = CurContext;
4808   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4809     Cur = Cur->getParent();
4810 
4811   // If the user provided a superfluous scope specifier that refers back to the
4812   // class in which the entity is already declared, diagnose and ignore it.
4813   //
4814   // class X {
4815   //   void X::f();
4816   // };
4817   //
4818   // Note, it was once ill-formed to give redundant qualification in all
4819   // contexts, but that rule was removed by DR482.
4820   if (Cur->Equals(DC)) {
4821     if (Cur->isRecord()) {
4822       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4823                                       : diag::err_member_extra_qualification)
4824         << Name << FixItHint::CreateRemoval(SS.getRange());
4825       SS.clear();
4826     } else {
4827       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4828     }
4829     return false;
4830   }
4831 
4832   // Check whether the qualifying scope encloses the scope of the original
4833   // declaration.
4834   if (!Cur->Encloses(DC)) {
4835     if (Cur->isRecord())
4836       Diag(Loc, diag::err_member_qualification)
4837         << Name << SS.getRange();
4838     else if (isa<TranslationUnitDecl>(DC))
4839       Diag(Loc, diag::err_invalid_declarator_global_scope)
4840         << Name << SS.getRange();
4841     else if (isa<FunctionDecl>(Cur))
4842       Diag(Loc, diag::err_invalid_declarator_in_function)
4843         << Name << SS.getRange();
4844     else if (isa<BlockDecl>(Cur))
4845       Diag(Loc, diag::err_invalid_declarator_in_block)
4846         << Name << SS.getRange();
4847     else
4848       Diag(Loc, diag::err_invalid_declarator_scope)
4849       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4850 
4851     return true;
4852   }
4853 
4854   if (Cur->isRecord()) {
4855     // Cannot qualify members within a class.
4856     Diag(Loc, diag::err_member_qualification)
4857       << Name << SS.getRange();
4858     SS.clear();
4859 
4860     // C++ constructors and destructors with incorrect scopes can break
4861     // our AST invariants by having the wrong underlying types. If
4862     // that's the case, then drop this declaration entirely.
4863     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4864          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4865         !Context.hasSameType(Name.getCXXNameType(),
4866                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4867       return true;
4868 
4869     return false;
4870   }
4871 
4872   // C++11 [dcl.meaning]p1:
4873   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4874   //   not begin with a decltype-specifer"
4875   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4876   while (SpecLoc.getPrefix())
4877     SpecLoc = SpecLoc.getPrefix();
4878   if (dyn_cast_or_null<DecltypeType>(
4879         SpecLoc.getNestedNameSpecifier()->getAsType()))
4880     Diag(Loc, diag::err_decltype_in_declarator)
4881       << SpecLoc.getTypeLoc().getSourceRange();
4882 
4883   return false;
4884 }
4885 
4886 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4887                                   MultiTemplateParamsArg TemplateParamLists) {
4888   // TODO: consider using NameInfo for diagnostic.
4889   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4890   DeclarationName Name = NameInfo.getName();
4891 
4892   // All of these full declarators require an identifier.  If it doesn't have
4893   // one, the ParsedFreeStandingDeclSpec action should be used.
4894   if (!Name) {
4895     if (!D.isInvalidType())  // Reject this if we think it is valid.
4896       Diag(D.getDeclSpec().getLocStart(),
4897            diag::err_declarator_need_ident)
4898         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4899     return nullptr;
4900   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4901     return nullptr;
4902 
4903   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4904   // we find one that is.
4905   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4906          (S->getFlags() & Scope::TemplateParamScope) != 0)
4907     S = S->getParent();
4908 
4909   DeclContext *DC = CurContext;
4910   if (D.getCXXScopeSpec().isInvalid())
4911     D.setInvalidType();
4912   else if (D.getCXXScopeSpec().isSet()) {
4913     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4914                                         UPPC_DeclarationQualifier))
4915       return nullptr;
4916 
4917     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4918     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4919     if (!DC || isa<EnumDecl>(DC)) {
4920       // If we could not compute the declaration context, it's because the
4921       // declaration context is dependent but does not refer to a class,
4922       // class template, or class template partial specialization. Complain
4923       // and return early, to avoid the coming semantic disaster.
4924       Diag(D.getIdentifierLoc(),
4925            diag::err_template_qualified_declarator_no_match)
4926         << D.getCXXScopeSpec().getScopeRep()
4927         << D.getCXXScopeSpec().getRange();
4928       return nullptr;
4929     }
4930     bool IsDependentContext = DC->isDependentContext();
4931 
4932     if (!IsDependentContext &&
4933         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4934       return nullptr;
4935 
4936     // If a class is incomplete, do not parse entities inside it.
4937     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4938       Diag(D.getIdentifierLoc(),
4939            diag::err_member_def_undefined_record)
4940         << Name << DC << D.getCXXScopeSpec().getRange();
4941       return nullptr;
4942     }
4943     if (!D.getDeclSpec().isFriendSpecified()) {
4944       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4945                                       Name, D.getIdentifierLoc())) {
4946         if (DC->isRecord())
4947           return nullptr;
4948 
4949         D.setInvalidType();
4950       }
4951     }
4952 
4953     // Check whether we need to rebuild the type of the given
4954     // declaration in the current instantiation.
4955     if (EnteringContext && IsDependentContext &&
4956         TemplateParamLists.size() != 0) {
4957       ContextRAII SavedContext(*this, DC);
4958       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4959         D.setInvalidType();
4960     }
4961   }
4962 
4963   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4964   QualType R = TInfo->getType();
4965 
4966   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4967     // If this is a typedef, we'll end up spewing multiple diagnostics.
4968     // Just return early; it's safer. If this is a function, let the
4969     // "constructor cannot have a return type" diagnostic handle it.
4970     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4971       return nullptr;
4972 
4973   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4974                                       UPPC_DeclarationType))
4975     D.setInvalidType();
4976 
4977   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4978                         ForRedeclaration);
4979 
4980   // See if this is a redefinition of a variable in the same scope.
4981   if (!D.getCXXScopeSpec().isSet()) {
4982     bool IsLinkageLookup = false;
4983     bool CreateBuiltins = false;
4984 
4985     // If the declaration we're planning to build will be a function
4986     // or object with linkage, then look for another declaration with
4987     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4988     //
4989     // If the declaration we're planning to build will be declared with
4990     // external linkage in the translation unit, create any builtin with
4991     // the same name.
4992     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4993       /* Do nothing*/;
4994     else if (CurContext->isFunctionOrMethod() &&
4995              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4996               R->isFunctionType())) {
4997       IsLinkageLookup = true;
4998       CreateBuiltins =
4999           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5000     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5001                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5002       CreateBuiltins = true;
5003 
5004     if (IsLinkageLookup)
5005       Previous.clear(LookupRedeclarationWithLinkage);
5006 
5007     LookupName(Previous, S, CreateBuiltins);
5008   } else { // Something like "int foo::x;"
5009     LookupQualifiedName(Previous, DC);
5010 
5011     // C++ [dcl.meaning]p1:
5012     //   When the declarator-id is qualified, the declaration shall refer to a
5013     //  previously declared member of the class or namespace to which the
5014     //  qualifier refers (or, in the case of a namespace, of an element of the
5015     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5016     //  thereof; [...]
5017     //
5018     // Note that we already checked the context above, and that we do not have
5019     // enough information to make sure that Previous contains the declaration
5020     // we want to match. For example, given:
5021     //
5022     //   class X {
5023     //     void f();
5024     //     void f(float);
5025     //   };
5026     //
5027     //   void X::f(int) { } // ill-formed
5028     //
5029     // In this case, Previous will point to the overload set
5030     // containing the two f's declared in X, but neither of them
5031     // matches.
5032 
5033     // C++ [dcl.meaning]p1:
5034     //   [...] the member shall not merely have been introduced by a
5035     //   using-declaration in the scope of the class or namespace nominated by
5036     //   the nested-name-specifier of the declarator-id.
5037     RemoveUsingDecls(Previous);
5038   }
5039 
5040   if (Previous.isSingleResult() &&
5041       Previous.getFoundDecl()->isTemplateParameter()) {
5042     // Maybe we will complain about the shadowed template parameter.
5043     if (!D.isInvalidType())
5044       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5045                                       Previous.getFoundDecl());
5046 
5047     // Just pretend that we didn't see the previous declaration.
5048     Previous.clear();
5049   }
5050 
5051   // In C++, the previous declaration we find might be a tag type
5052   // (class or enum). In this case, the new declaration will hide the
5053   // tag type. Note that this does does not apply if we're declaring a
5054   // typedef (C++ [dcl.typedef]p4).
5055   if (Previous.isSingleTagDecl() &&
5056       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5057     Previous.clear();
5058 
5059   // Check that there are no default arguments other than in the parameters
5060   // of a function declaration (C++ only).
5061   if (getLangOpts().CPlusPlus)
5062     CheckExtraCXXDefaultArguments(D);
5063 
5064   if (D.getDeclSpec().isConceptSpecified()) {
5065     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5066     // applied only to the definition of a function template or variable
5067     // template, declared in namespace scope
5068     if (!TemplateParamLists.size()) {
5069       Diag(D.getDeclSpec().getConceptSpecLoc(),
5070            diag:: err_concept_wrong_decl_kind);
5071       return nullptr;
5072     }
5073 
5074     if (!DC->getRedeclContext()->isFileContext()) {
5075       Diag(D.getIdentifierLoc(),
5076            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5077       return nullptr;
5078     }
5079   }
5080 
5081   NamedDecl *New;
5082 
5083   bool AddToScope = true;
5084   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5085     if (TemplateParamLists.size()) {
5086       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5087       return nullptr;
5088     }
5089 
5090     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5091   } else if (R->isFunctionType()) {
5092     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5093                                   TemplateParamLists,
5094                                   AddToScope);
5095   } else {
5096     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5097                                   AddToScope);
5098   }
5099 
5100   if (!New)
5101     return nullptr;
5102 
5103   // If this has an identifier and is not a function template specialization,
5104   // add it to the scope stack.
5105   if (New->getDeclName() && AddToScope) {
5106     // Only make a locally-scoped extern declaration visible if it is the first
5107     // declaration of this entity. Qualified lookup for such an entity should
5108     // only find this declaration if there is no visible declaration of it.
5109     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5110     PushOnScopeChains(New, S, AddToContext);
5111     if (!AddToContext)
5112       CurContext->addHiddenDecl(New);
5113   }
5114 
5115   if (isInOpenMPDeclareTargetContext())
5116     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5117 
5118   return New;
5119 }
5120 
5121 /// Helper method to turn variable array types into constant array
5122 /// types in certain situations which would otherwise be errors (for
5123 /// GCC compatibility).
5124 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5125                                                     ASTContext &Context,
5126                                                     bool &SizeIsNegative,
5127                                                     llvm::APSInt &Oversized) {
5128   // This method tries to turn a variable array into a constant
5129   // array even when the size isn't an ICE.  This is necessary
5130   // for compatibility with code that depends on gcc's buggy
5131   // constant expression folding, like struct {char x[(int)(char*)2];}
5132   SizeIsNegative = false;
5133   Oversized = 0;
5134 
5135   if (T->isDependentType())
5136     return QualType();
5137 
5138   QualifierCollector Qs;
5139   const Type *Ty = Qs.strip(T);
5140 
5141   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5142     QualType Pointee = PTy->getPointeeType();
5143     QualType FixedType =
5144         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5145                                             Oversized);
5146     if (FixedType.isNull()) return FixedType;
5147     FixedType = Context.getPointerType(FixedType);
5148     return Qs.apply(Context, FixedType);
5149   }
5150   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5151     QualType Inner = PTy->getInnerType();
5152     QualType FixedType =
5153         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5154                                             Oversized);
5155     if (FixedType.isNull()) return FixedType;
5156     FixedType = Context.getParenType(FixedType);
5157     return Qs.apply(Context, FixedType);
5158   }
5159 
5160   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5161   if (!VLATy)
5162     return QualType();
5163   // FIXME: We should probably handle this case
5164   if (VLATy->getElementType()->isVariablyModifiedType())
5165     return QualType();
5166 
5167   llvm::APSInt Res;
5168   if (!VLATy->getSizeExpr() ||
5169       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5170     return QualType();
5171 
5172   // Check whether the array size is negative.
5173   if (Res.isSigned() && Res.isNegative()) {
5174     SizeIsNegative = true;
5175     return QualType();
5176   }
5177 
5178   // Check whether the array is too large to be addressed.
5179   unsigned ActiveSizeBits
5180     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5181                                               Res);
5182   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5183     Oversized = Res;
5184     return QualType();
5185   }
5186 
5187   return Context.getConstantArrayType(VLATy->getElementType(),
5188                                       Res, ArrayType::Normal, 0);
5189 }
5190 
5191 static void
5192 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5193   SrcTL = SrcTL.getUnqualifiedLoc();
5194   DstTL = DstTL.getUnqualifiedLoc();
5195   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5196     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5197     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5198                                       DstPTL.getPointeeLoc());
5199     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5200     return;
5201   }
5202   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5203     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5204     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5205                                       DstPTL.getInnerLoc());
5206     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5207     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5208     return;
5209   }
5210   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5211   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5212   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5213   TypeLoc DstElemTL = DstATL.getElementLoc();
5214   DstElemTL.initializeFullCopy(SrcElemTL);
5215   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5216   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5217   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5218 }
5219 
5220 /// Helper method to turn variable array types into constant array
5221 /// types in certain situations which would otherwise be errors (for
5222 /// GCC compatibility).
5223 static TypeSourceInfo*
5224 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5225                                               ASTContext &Context,
5226                                               bool &SizeIsNegative,
5227                                               llvm::APSInt &Oversized) {
5228   QualType FixedTy
5229     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5230                                           SizeIsNegative, Oversized);
5231   if (FixedTy.isNull())
5232     return nullptr;
5233   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5234   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5235                                     FixedTInfo->getTypeLoc());
5236   return FixedTInfo;
5237 }
5238 
5239 /// \brief Register the given locally-scoped extern "C" declaration so
5240 /// that it can be found later for redeclarations. We include any extern "C"
5241 /// declaration that is not visible in the translation unit here, not just
5242 /// function-scope declarations.
5243 void
5244 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5245   if (!getLangOpts().CPlusPlus &&
5246       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5247     // Don't need to track declarations in the TU in C.
5248     return;
5249 
5250   // Note that we have a locally-scoped external with this name.
5251   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5252 }
5253 
5254 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5255   // FIXME: We can have multiple results via __attribute__((overloadable)).
5256   auto Result = Context.getExternCContextDecl()->lookup(Name);
5257   return Result.empty() ? nullptr : *Result.begin();
5258 }
5259 
5260 /// \brief Diagnose function specifiers on a declaration of an identifier that
5261 /// does not identify a function.
5262 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5263   // FIXME: We should probably indicate the identifier in question to avoid
5264   // confusion for constructs like "inline int a(), b;"
5265   if (DS.isInlineSpecified())
5266     Diag(DS.getInlineSpecLoc(),
5267          diag::err_inline_non_function);
5268 
5269   if (DS.isVirtualSpecified())
5270     Diag(DS.getVirtualSpecLoc(),
5271          diag::err_virtual_non_function);
5272 
5273   if (DS.isExplicitSpecified())
5274     Diag(DS.getExplicitSpecLoc(),
5275          diag::err_explicit_non_function);
5276 
5277   if (DS.isNoreturnSpecified())
5278     Diag(DS.getNoreturnSpecLoc(),
5279          diag::err_noreturn_non_function);
5280 }
5281 
5282 NamedDecl*
5283 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5284                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5285   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5286   if (D.getCXXScopeSpec().isSet()) {
5287     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5288       << D.getCXXScopeSpec().getRange();
5289     D.setInvalidType();
5290     // Pretend we didn't see the scope specifier.
5291     DC = CurContext;
5292     Previous.clear();
5293   }
5294 
5295   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5296 
5297   if (D.getDeclSpec().isConstexprSpecified())
5298     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5299       << 1;
5300   if (D.getDeclSpec().isConceptSpecified())
5301     Diag(D.getDeclSpec().getConceptSpecLoc(),
5302          diag::err_concept_wrong_decl_kind);
5303 
5304   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5305     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5306       << D.getName().getSourceRange();
5307     return nullptr;
5308   }
5309 
5310   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5311   if (!NewTD) return nullptr;
5312 
5313   // Handle attributes prior to checking for duplicates in MergeVarDecl
5314   ProcessDeclAttributes(S, NewTD, D);
5315 
5316   CheckTypedefForVariablyModifiedType(S, NewTD);
5317 
5318   bool Redeclaration = D.isRedeclaration();
5319   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5320   D.setRedeclaration(Redeclaration);
5321   return ND;
5322 }
5323 
5324 void
5325 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5326   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5327   // then it shall have block scope.
5328   // Note that variably modified types must be fixed before merging the decl so
5329   // that redeclarations will match.
5330   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5331   QualType T = TInfo->getType();
5332   if (T->isVariablyModifiedType()) {
5333     getCurFunction()->setHasBranchProtectedScope();
5334 
5335     if (S->getFnParent() == nullptr) {
5336       bool SizeIsNegative;
5337       llvm::APSInt Oversized;
5338       TypeSourceInfo *FixedTInfo =
5339         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5340                                                       SizeIsNegative,
5341                                                       Oversized);
5342       if (FixedTInfo) {
5343         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5344         NewTD->setTypeSourceInfo(FixedTInfo);
5345       } else {
5346         if (SizeIsNegative)
5347           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5348         else if (T->isVariableArrayType())
5349           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5350         else if (Oversized.getBoolValue())
5351           Diag(NewTD->getLocation(), diag::err_array_too_large)
5352             << Oversized.toString(10);
5353         else
5354           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5355         NewTD->setInvalidDecl();
5356       }
5357     }
5358   }
5359 }
5360 
5361 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5362 /// declares a typedef-name, either using the 'typedef' type specifier or via
5363 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5364 NamedDecl*
5365 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5366                            LookupResult &Previous, bool &Redeclaration) {
5367   // Merge the decl with the existing one if appropriate. If the decl is
5368   // in an outer scope, it isn't the same thing.
5369   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5370                        /*AllowInlineNamespace*/false);
5371   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5372   if (!Previous.empty()) {
5373     Redeclaration = true;
5374     MergeTypedefNameDecl(S, NewTD, Previous);
5375   }
5376 
5377   // If this is the C FILE type, notify the AST context.
5378   if (IdentifierInfo *II = NewTD->getIdentifier())
5379     if (!NewTD->isInvalidDecl() &&
5380         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5381       if (II->isStr("FILE"))
5382         Context.setFILEDecl(NewTD);
5383       else if (II->isStr("jmp_buf"))
5384         Context.setjmp_bufDecl(NewTD);
5385       else if (II->isStr("sigjmp_buf"))
5386         Context.setsigjmp_bufDecl(NewTD);
5387       else if (II->isStr("ucontext_t"))
5388         Context.setucontext_tDecl(NewTD);
5389     }
5390 
5391   return NewTD;
5392 }
5393 
5394 /// \brief Determines whether the given declaration is an out-of-scope
5395 /// previous declaration.
5396 ///
5397 /// This routine should be invoked when name lookup has found a
5398 /// previous declaration (PrevDecl) that is not in the scope where a
5399 /// new declaration by the same name is being introduced. If the new
5400 /// declaration occurs in a local scope, previous declarations with
5401 /// linkage may still be considered previous declarations (C99
5402 /// 6.2.2p4-5, C++ [basic.link]p6).
5403 ///
5404 /// \param PrevDecl the previous declaration found by name
5405 /// lookup
5406 ///
5407 /// \param DC the context in which the new declaration is being
5408 /// declared.
5409 ///
5410 /// \returns true if PrevDecl is an out-of-scope previous declaration
5411 /// for a new delcaration with the same name.
5412 static bool
5413 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5414                                 ASTContext &Context) {
5415   if (!PrevDecl)
5416     return false;
5417 
5418   if (!PrevDecl->hasLinkage())
5419     return false;
5420 
5421   if (Context.getLangOpts().CPlusPlus) {
5422     // C++ [basic.link]p6:
5423     //   If there is a visible declaration of an entity with linkage
5424     //   having the same name and type, ignoring entities declared
5425     //   outside the innermost enclosing namespace scope, the block
5426     //   scope declaration declares that same entity and receives the
5427     //   linkage of the previous declaration.
5428     DeclContext *OuterContext = DC->getRedeclContext();
5429     if (!OuterContext->isFunctionOrMethod())
5430       // This rule only applies to block-scope declarations.
5431       return false;
5432 
5433     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5434     if (PrevOuterContext->isRecord())
5435       // We found a member function: ignore it.
5436       return false;
5437 
5438     // Find the innermost enclosing namespace for the new and
5439     // previous declarations.
5440     OuterContext = OuterContext->getEnclosingNamespaceContext();
5441     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5442 
5443     // The previous declaration is in a different namespace, so it
5444     // isn't the same function.
5445     if (!OuterContext->Equals(PrevOuterContext))
5446       return false;
5447   }
5448 
5449   return true;
5450 }
5451 
5452 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5453   CXXScopeSpec &SS = D.getCXXScopeSpec();
5454   if (!SS.isSet()) return;
5455   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5456 }
5457 
5458 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5459   QualType type = decl->getType();
5460   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5461   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5462     // Various kinds of declaration aren't allowed to be __autoreleasing.
5463     unsigned kind = -1U;
5464     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5465       if (var->hasAttr<BlocksAttr>())
5466         kind = 0; // __block
5467       else if (!var->hasLocalStorage())
5468         kind = 1; // global
5469     } else if (isa<ObjCIvarDecl>(decl)) {
5470       kind = 3; // ivar
5471     } else if (isa<FieldDecl>(decl)) {
5472       kind = 2; // field
5473     }
5474 
5475     if (kind != -1U) {
5476       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5477         << kind;
5478     }
5479   } else if (lifetime == Qualifiers::OCL_None) {
5480     // Try to infer lifetime.
5481     if (!type->isObjCLifetimeType())
5482       return false;
5483 
5484     lifetime = type->getObjCARCImplicitLifetime();
5485     type = Context.getLifetimeQualifiedType(type, lifetime);
5486     decl->setType(type);
5487   }
5488 
5489   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5490     // Thread-local variables cannot have lifetime.
5491     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5492         var->getTLSKind()) {
5493       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5494         << var->getType();
5495       return true;
5496     }
5497   }
5498 
5499   return false;
5500 }
5501 
5502 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5503   // Ensure that an auto decl is deduced otherwise the checks below might cache
5504   // the wrong linkage.
5505   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5506 
5507   // 'weak' only applies to declarations with external linkage.
5508   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5509     if (!ND.isExternallyVisible()) {
5510       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5511       ND.dropAttr<WeakAttr>();
5512     }
5513   }
5514   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5515     if (ND.isExternallyVisible()) {
5516       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5517       ND.dropAttr<WeakRefAttr>();
5518       ND.dropAttr<AliasAttr>();
5519     }
5520   }
5521 
5522   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5523     if (VD->hasInit()) {
5524       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5525         assert(VD->isThisDeclarationADefinition() &&
5526                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5527         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5528         VD->dropAttr<AliasAttr>();
5529       }
5530     }
5531   }
5532 
5533   // 'selectany' only applies to externally visible variable declarations.
5534   // It does not apply to functions.
5535   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5536     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5537       S.Diag(Attr->getLocation(),
5538              diag::err_attribute_selectany_non_extern_data);
5539       ND.dropAttr<SelectAnyAttr>();
5540     }
5541   }
5542 
5543   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5544     // dll attributes require external linkage. Static locals may have external
5545     // linkage but still cannot be explicitly imported or exported.
5546     auto *VD = dyn_cast<VarDecl>(&ND);
5547     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5548       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5549         << &ND << Attr;
5550       ND.setInvalidDecl();
5551     }
5552   }
5553 
5554   // Virtual functions cannot be marked as 'notail'.
5555   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5556     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5557       if (MD->isVirtual()) {
5558         S.Diag(ND.getLocation(),
5559                diag::err_invalid_attribute_on_virtual_function)
5560             << Attr;
5561         ND.dropAttr<NotTailCalledAttr>();
5562       }
5563 }
5564 
5565 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5566                                            NamedDecl *NewDecl,
5567                                            bool IsSpecialization,
5568                                            bool IsDefinition) {
5569   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5570     OldDecl = OldTD->getTemplatedDecl();
5571     if (!IsSpecialization)
5572       IsDefinition = false;
5573   }
5574   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5575     NewDecl = NewTD->getTemplatedDecl();
5576 
5577   if (!OldDecl || !NewDecl)
5578     return;
5579 
5580   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5581   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5582   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5583   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5584 
5585   // dllimport and dllexport are inheritable attributes so we have to exclude
5586   // inherited attribute instances.
5587   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5588                     (NewExportAttr && !NewExportAttr->isInherited());
5589 
5590   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5591   // the only exception being explicit specializations.
5592   // Implicitly generated declarations are also excluded for now because there
5593   // is no other way to switch these to use dllimport or dllexport.
5594   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5595 
5596   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5597     // Allow with a warning for free functions and global variables.
5598     bool JustWarn = false;
5599     if (!OldDecl->isCXXClassMember()) {
5600       auto *VD = dyn_cast<VarDecl>(OldDecl);
5601       if (VD && !VD->getDescribedVarTemplate())
5602         JustWarn = true;
5603       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5604       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5605         JustWarn = true;
5606     }
5607 
5608     // We cannot change a declaration that's been used because IR has already
5609     // been emitted. Dllimported functions will still work though (modulo
5610     // address equality) as they can use the thunk.
5611     if (OldDecl->isUsed())
5612       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5613         JustWarn = false;
5614 
5615     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5616                                : diag::err_attribute_dll_redeclaration;
5617     S.Diag(NewDecl->getLocation(), DiagID)
5618         << NewDecl
5619         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5620     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5621     if (!JustWarn) {
5622       NewDecl->setInvalidDecl();
5623       return;
5624     }
5625   }
5626 
5627   // A redeclaration is not allowed to drop a dllimport attribute, the only
5628   // exceptions being inline function definitions, local extern declarations,
5629   // qualified friend declarations or special MSVC extension: in the last case,
5630   // the declaration is treated as if it were marked dllexport.
5631   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5632   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5633   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5634     // Ignore static data because out-of-line definitions are diagnosed
5635     // separately.
5636     IsStaticDataMember = VD->isStaticDataMember();
5637     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5638                    VarDecl::DeclarationOnly;
5639   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5640     IsInline = FD->isInlined();
5641     IsQualifiedFriend = FD->getQualifier() &&
5642                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5643   }
5644 
5645   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5646       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5647     if (IsMicrosoft && IsDefinition) {
5648       S.Diag(NewDecl->getLocation(),
5649              diag::warn_redeclaration_without_import_attribute)
5650           << NewDecl;
5651       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5652       NewDecl->dropAttr<DLLImportAttr>();
5653       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5654           NewImportAttr->getRange(), S.Context,
5655           NewImportAttr->getSpellingListIndex()));
5656     } else {
5657       S.Diag(NewDecl->getLocation(),
5658              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5659           << NewDecl << OldImportAttr;
5660       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5661       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5662       OldDecl->dropAttr<DLLImportAttr>();
5663       NewDecl->dropAttr<DLLImportAttr>();
5664     }
5665   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5666     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5667     OldDecl->dropAttr<DLLImportAttr>();
5668     NewDecl->dropAttr<DLLImportAttr>();
5669     S.Diag(NewDecl->getLocation(),
5670            diag::warn_dllimport_dropped_from_inline_function)
5671         << NewDecl << OldImportAttr;
5672   }
5673 }
5674 
5675 /// Given that we are within the definition of the given function,
5676 /// will that definition behave like C99's 'inline', where the
5677 /// definition is discarded except for optimization purposes?
5678 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5679   // Try to avoid calling GetGVALinkageForFunction.
5680 
5681   // All cases of this require the 'inline' keyword.
5682   if (!FD->isInlined()) return false;
5683 
5684   // This is only possible in C++ with the gnu_inline attribute.
5685   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5686     return false;
5687 
5688   // Okay, go ahead and call the relatively-more-expensive function.
5689 
5690 #ifndef NDEBUG
5691   // AST quite reasonably asserts that it's working on a function
5692   // definition.  We don't really have a way to tell it that we're
5693   // currently defining the function, so just lie to it in +Asserts
5694   // builds.  This is an awful hack.
5695   FD->setLazyBody(1);
5696 #endif
5697 
5698   bool isC99Inline =
5699       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5700 
5701 #ifndef NDEBUG
5702   FD->setLazyBody(0);
5703 #endif
5704 
5705   return isC99Inline;
5706 }
5707 
5708 /// Determine whether a variable is extern "C" prior to attaching
5709 /// an initializer. We can't just call isExternC() here, because that
5710 /// will also compute and cache whether the declaration is externally
5711 /// visible, which might change when we attach the initializer.
5712 ///
5713 /// This can only be used if the declaration is known to not be a
5714 /// redeclaration of an internal linkage declaration.
5715 ///
5716 /// For instance:
5717 ///
5718 ///   auto x = []{};
5719 ///
5720 /// Attaching the initializer here makes this declaration not externally
5721 /// visible, because its type has internal linkage.
5722 ///
5723 /// FIXME: This is a hack.
5724 template<typename T>
5725 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5726   if (S.getLangOpts().CPlusPlus) {
5727     // In C++, the overloadable attribute negates the effects of extern "C".
5728     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5729       return false;
5730 
5731     // So do CUDA's host/device attributes.
5732     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5733                                  D->template hasAttr<CUDAHostAttr>()))
5734       return false;
5735   }
5736   return D->isExternC();
5737 }
5738 
5739 static bool shouldConsiderLinkage(const VarDecl *VD) {
5740   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5741   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5742     return VD->hasExternalStorage();
5743   if (DC->isFileContext())
5744     return true;
5745   if (DC->isRecord())
5746     return false;
5747   llvm_unreachable("Unexpected context");
5748 }
5749 
5750 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5751   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5752   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5753       isa<OMPDeclareReductionDecl>(DC))
5754     return true;
5755   if (DC->isRecord())
5756     return false;
5757   llvm_unreachable("Unexpected context");
5758 }
5759 
5760 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5761                           AttributeList::Kind Kind) {
5762   for (const AttributeList *L = AttrList; L; L = L->getNext())
5763     if (L->getKind() == Kind)
5764       return true;
5765   return false;
5766 }
5767 
5768 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5769                           AttributeList::Kind Kind) {
5770   // Check decl attributes on the DeclSpec.
5771   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5772     return true;
5773 
5774   // Walk the declarator structure, checking decl attributes that were in a type
5775   // position to the decl itself.
5776   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5777     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5778       return true;
5779   }
5780 
5781   // Finally, check attributes on the decl itself.
5782   return hasParsedAttr(S, PD.getAttributes(), Kind);
5783 }
5784 
5785 /// Adjust the \c DeclContext for a function or variable that might be a
5786 /// function-local external declaration.
5787 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5788   if (!DC->isFunctionOrMethod())
5789     return false;
5790 
5791   // If this is a local extern function or variable declared within a function
5792   // template, don't add it into the enclosing namespace scope until it is
5793   // instantiated; it might have a dependent type right now.
5794   if (DC->isDependentContext())
5795     return true;
5796 
5797   // C++11 [basic.link]p7:
5798   //   When a block scope declaration of an entity with linkage is not found to
5799   //   refer to some other declaration, then that entity is a member of the
5800   //   innermost enclosing namespace.
5801   //
5802   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5803   // semantically-enclosing namespace, not a lexically-enclosing one.
5804   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5805     DC = DC->getParent();
5806   return true;
5807 }
5808 
5809 /// \brief Returns true if given declaration has external C language linkage.
5810 static bool isDeclExternC(const Decl *D) {
5811   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5812     return FD->isExternC();
5813   if (const auto *VD = dyn_cast<VarDecl>(D))
5814     return VD->isExternC();
5815 
5816   llvm_unreachable("Unknown type of decl!");
5817 }
5818 
5819 NamedDecl *
5820 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5821                               TypeSourceInfo *TInfo, LookupResult &Previous,
5822                               MultiTemplateParamsArg TemplateParamLists,
5823                               bool &AddToScope) {
5824   QualType R = TInfo->getType();
5825   DeclarationName Name = GetNameForDeclarator(D).getName();
5826 
5827   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5828   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5829   // argument.
5830   if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) {
5831     Diag(D.getIdentifierLoc(),
5832          diag::err_opencl_type_can_only_be_used_as_function_parameter)
5833         << R;
5834     D.setInvalidType();
5835     return nullptr;
5836   }
5837 
5838   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5839   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5840 
5841   // dllimport globals without explicit storage class are treated as extern. We
5842   // have to change the storage class this early to get the right DeclContext.
5843   if (SC == SC_None && !DC->isRecord() &&
5844       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5845       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5846     SC = SC_Extern;
5847 
5848   DeclContext *OriginalDC = DC;
5849   bool IsLocalExternDecl = SC == SC_Extern &&
5850                            adjustContextForLocalExternDecl(DC);
5851 
5852   if (getLangOpts().OpenCL) {
5853     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5854     QualType NR = R;
5855     while (NR->isPointerType()) {
5856       if (NR->isFunctionPointerType()) {
5857         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5858         D.setInvalidType();
5859         break;
5860       }
5861       NR = NR->getPointeeType();
5862     }
5863 
5864     if (!getOpenCLOptions().cl_khr_fp16) {
5865       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5866       // half array type (unless the cl_khr_fp16 extension is enabled).
5867       if (Context.getBaseElementType(R)->isHalfType()) {
5868         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5869         D.setInvalidType();
5870       }
5871     }
5872   }
5873 
5874   if (SCSpec == DeclSpec::SCS_mutable) {
5875     // mutable can only appear on non-static class members, so it's always
5876     // an error here
5877     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5878     D.setInvalidType();
5879     SC = SC_None;
5880   }
5881 
5882   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5883       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5884                               D.getDeclSpec().getStorageClassSpecLoc())) {
5885     // In C++11, the 'register' storage class specifier is deprecated.
5886     // Suppress the warning in system macros, it's used in macros in some
5887     // popular C system headers, such as in glibc's htonl() macro.
5888     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5889          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5890                                    : diag::warn_deprecated_register)
5891       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5892   }
5893 
5894   IdentifierInfo *II = Name.getAsIdentifierInfo();
5895   if (!II) {
5896     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5897       << Name;
5898     return nullptr;
5899   }
5900 
5901   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5902 
5903   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5904     // C99 6.9p2: The storage-class specifiers auto and register shall not
5905     // appear in the declaration specifiers in an external declaration.
5906     // Global Register+Asm is a GNU extension we support.
5907     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5908       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5909       D.setInvalidType();
5910     }
5911   }
5912 
5913   if (getLangOpts().OpenCL) {
5914     // OpenCL v1.2 s6.9.b p4:
5915     // The sampler type cannot be used with the __local and __global address
5916     // space qualifiers.
5917     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5918       R.getAddressSpace() == LangAS::opencl_global)) {
5919       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5920     }
5921 
5922     // OpenCL 1.2 spec, p6.9 r:
5923     // The event type cannot be used to declare a program scope variable.
5924     // The event type cannot be used with the __local, __constant and __global
5925     // address space qualifiers.
5926     if (R->isEventT()) {
5927       if (S->getParent() == nullptr) {
5928         Diag(D.getLocStart(), diag::err_event_t_global_var);
5929         D.setInvalidType();
5930       }
5931 
5932       if (R.getAddressSpace()) {
5933         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5934         D.setInvalidType();
5935       }
5936     }
5937   }
5938 
5939   bool IsExplicitSpecialization = false;
5940   bool IsVariableTemplateSpecialization = false;
5941   bool IsPartialSpecialization = false;
5942   bool IsVariableTemplate = false;
5943   VarDecl *NewVD = nullptr;
5944   VarTemplateDecl *NewTemplate = nullptr;
5945   TemplateParameterList *TemplateParams = nullptr;
5946   if (!getLangOpts().CPlusPlus) {
5947     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5948                             D.getIdentifierLoc(), II,
5949                             R, TInfo, SC);
5950 
5951     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5952       ParsingInitForAutoVars.insert(NewVD);
5953 
5954     if (D.isInvalidType())
5955       NewVD->setInvalidDecl();
5956   } else {
5957     bool Invalid = false;
5958 
5959     if (DC->isRecord() && !CurContext->isRecord()) {
5960       // This is an out-of-line definition of a static data member.
5961       switch (SC) {
5962       case SC_None:
5963         break;
5964       case SC_Static:
5965         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5966              diag::err_static_out_of_line)
5967           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5968         break;
5969       case SC_Auto:
5970       case SC_Register:
5971       case SC_Extern:
5972         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5973         // to names of variables declared in a block or to function parameters.
5974         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5975         // of class members
5976 
5977         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5978              diag::err_storage_class_for_static_member)
5979           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5980         break;
5981       case SC_PrivateExtern:
5982         llvm_unreachable("C storage class in c++!");
5983       }
5984     }
5985 
5986     if (SC == SC_Static && CurContext->isRecord()) {
5987       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5988         if (RD->isLocalClass())
5989           Diag(D.getIdentifierLoc(),
5990                diag::err_static_data_member_not_allowed_in_local_class)
5991             << Name << RD->getDeclName();
5992 
5993         // C++98 [class.union]p1: If a union contains a static data member,
5994         // the program is ill-formed. C++11 drops this restriction.
5995         if (RD->isUnion())
5996           Diag(D.getIdentifierLoc(),
5997                getLangOpts().CPlusPlus11
5998                  ? diag::warn_cxx98_compat_static_data_member_in_union
5999                  : diag::ext_static_data_member_in_union) << Name;
6000         // We conservatively disallow static data members in anonymous structs.
6001         else if (!RD->getDeclName())
6002           Diag(D.getIdentifierLoc(),
6003                diag::err_static_data_member_not_allowed_in_anon_struct)
6004             << Name << RD->isUnion();
6005       }
6006     }
6007 
6008     // Match up the template parameter lists with the scope specifier, then
6009     // determine whether we have a template or a template specialization.
6010     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6011         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6012         D.getCXXScopeSpec(),
6013         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6014             ? D.getName().TemplateId
6015             : nullptr,
6016         TemplateParamLists,
6017         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
6018 
6019     if (TemplateParams) {
6020       if (!TemplateParams->size() &&
6021           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6022         // There is an extraneous 'template<>' for this variable. Complain
6023         // about it, but allow the declaration of the variable.
6024         Diag(TemplateParams->getTemplateLoc(),
6025              diag::err_template_variable_noparams)
6026           << II
6027           << SourceRange(TemplateParams->getTemplateLoc(),
6028                          TemplateParams->getRAngleLoc());
6029         TemplateParams = nullptr;
6030       } else {
6031         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6032           // This is an explicit specialization or a partial specialization.
6033           // FIXME: Check that we can declare a specialization here.
6034           IsVariableTemplateSpecialization = true;
6035           IsPartialSpecialization = TemplateParams->size() > 0;
6036         } else { // if (TemplateParams->size() > 0)
6037           // This is a template declaration.
6038           IsVariableTemplate = true;
6039 
6040           // Check that we can declare a template here.
6041           if (CheckTemplateDeclScope(S, TemplateParams))
6042             return nullptr;
6043 
6044           // Only C++1y supports variable templates (N3651).
6045           Diag(D.getIdentifierLoc(),
6046                getLangOpts().CPlusPlus14
6047                    ? diag::warn_cxx11_compat_variable_template
6048                    : diag::ext_variable_template);
6049         }
6050       }
6051     } else {
6052       assert(
6053           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6054           "should have a 'template<>' for this decl");
6055     }
6056 
6057     if (IsVariableTemplateSpecialization) {
6058       SourceLocation TemplateKWLoc =
6059           TemplateParamLists.size() > 0
6060               ? TemplateParamLists[0]->getTemplateLoc()
6061               : SourceLocation();
6062       DeclResult Res = ActOnVarTemplateSpecialization(
6063           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6064           IsPartialSpecialization);
6065       if (Res.isInvalid())
6066         return nullptr;
6067       NewVD = cast<VarDecl>(Res.get());
6068       AddToScope = false;
6069     } else
6070       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6071                               D.getIdentifierLoc(), II, R, TInfo, SC);
6072 
6073     // If this is supposed to be a variable template, create it as such.
6074     if (IsVariableTemplate) {
6075       NewTemplate =
6076           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6077                                   TemplateParams, NewVD);
6078       NewVD->setDescribedVarTemplate(NewTemplate);
6079     }
6080 
6081     // If this decl has an auto type in need of deduction, make a note of the
6082     // Decl so we can diagnose uses of it in its own initializer.
6083     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6084       ParsingInitForAutoVars.insert(NewVD);
6085 
6086     if (D.isInvalidType() || Invalid) {
6087       NewVD->setInvalidDecl();
6088       if (NewTemplate)
6089         NewTemplate->setInvalidDecl();
6090     }
6091 
6092     SetNestedNameSpecifier(NewVD, D);
6093 
6094     // If we have any template parameter lists that don't directly belong to
6095     // the variable (matching the scope specifier), store them.
6096     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6097     if (TemplateParamLists.size() > VDTemplateParamLists)
6098       NewVD->setTemplateParameterListsInfo(
6099           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6100 
6101     if (D.getDeclSpec().isConstexprSpecified())
6102       NewVD->setConstexpr(true);
6103 
6104     if (D.getDeclSpec().isConceptSpecified()) {
6105       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6106         VTD->setConcept();
6107 
6108       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6109       // be declared with the thread_local, inline, friend, or constexpr
6110       // specifiers, [...]
6111       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6112         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6113              diag::err_concept_decl_invalid_specifiers)
6114             << 0 << 0;
6115         NewVD->setInvalidDecl(true);
6116       }
6117 
6118       if (D.getDeclSpec().isConstexprSpecified()) {
6119         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6120              diag::err_concept_decl_invalid_specifiers)
6121             << 0 << 3;
6122         NewVD->setInvalidDecl(true);
6123       }
6124 
6125       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6126       // applied only to the definition of a function template or variable
6127       // template, declared in namespace scope.
6128       if (IsVariableTemplateSpecialization) {
6129         Diag(D.getDeclSpec().getConceptSpecLoc(),
6130              diag::err_concept_specified_specialization)
6131             << (IsPartialSpecialization ? 2 : 1);
6132       }
6133 
6134       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6135       // following restrictions:
6136       // - The declared type shall have the type bool.
6137       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6138           !NewVD->isInvalidDecl()) {
6139         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6140         NewVD->setInvalidDecl(true);
6141       }
6142     }
6143   }
6144 
6145   // Set the lexical context. If the declarator has a C++ scope specifier, the
6146   // lexical context will be different from the semantic context.
6147   NewVD->setLexicalDeclContext(CurContext);
6148   if (NewTemplate)
6149     NewTemplate->setLexicalDeclContext(CurContext);
6150 
6151   if (IsLocalExternDecl)
6152     NewVD->setLocalExternDecl();
6153 
6154   bool EmitTLSUnsupportedError = false;
6155   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6156     // C++11 [dcl.stc]p4:
6157     //   When thread_local is applied to a variable of block scope the
6158     //   storage-class-specifier static is implied if it does not appear
6159     //   explicitly.
6160     // Core issue: 'static' is not implied if the variable is declared
6161     //   'extern'.
6162     if (NewVD->hasLocalStorage() &&
6163         (SCSpec != DeclSpec::SCS_unspecified ||
6164          TSCS != DeclSpec::TSCS_thread_local ||
6165          !DC->isFunctionOrMethod()))
6166       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6167            diag::err_thread_non_global)
6168         << DeclSpec::getSpecifierName(TSCS);
6169     else if (!Context.getTargetInfo().isTLSSupported()) {
6170       if (getLangOpts().CUDA) {
6171         // Postpone error emission until we've collected attributes required to
6172         // figure out whether it's a host or device variable and whether the
6173         // error should be ignored.
6174         EmitTLSUnsupportedError = true;
6175         // We still need to mark the variable as TLS so it shows up in AST with
6176         // proper storage class for other tools to use even if we're not going
6177         // to emit any code for it.
6178         NewVD->setTSCSpec(TSCS);
6179       } else
6180         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6181              diag::err_thread_unsupported);
6182     } else
6183       NewVD->setTSCSpec(TSCS);
6184   }
6185 
6186   // C99 6.7.4p3
6187   //   An inline definition of a function with external linkage shall
6188   //   not contain a definition of a modifiable object with static or
6189   //   thread storage duration...
6190   // We only apply this when the function is required to be defined
6191   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6192   // that a local variable with thread storage duration still has to
6193   // be marked 'static'.  Also note that it's possible to get these
6194   // semantics in C++ using __attribute__((gnu_inline)).
6195   if (SC == SC_Static && S->getFnParent() != nullptr &&
6196       !NewVD->getType().isConstQualified()) {
6197     FunctionDecl *CurFD = getCurFunctionDecl();
6198     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6199       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6200            diag::warn_static_local_in_extern_inline);
6201       MaybeSuggestAddingStaticToDecl(CurFD);
6202     }
6203   }
6204 
6205   if (D.getDeclSpec().isModulePrivateSpecified()) {
6206     if (IsVariableTemplateSpecialization)
6207       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6208           << (IsPartialSpecialization ? 1 : 0)
6209           << FixItHint::CreateRemoval(
6210                  D.getDeclSpec().getModulePrivateSpecLoc());
6211     else if (IsExplicitSpecialization)
6212       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6213         << 2
6214         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6215     else if (NewVD->hasLocalStorage())
6216       Diag(NewVD->getLocation(), diag::err_module_private_local)
6217         << 0 << NewVD->getDeclName()
6218         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6219         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6220     else {
6221       NewVD->setModulePrivate();
6222       if (NewTemplate)
6223         NewTemplate->setModulePrivate();
6224     }
6225   }
6226 
6227   // Handle attributes prior to checking for duplicates in MergeVarDecl
6228   ProcessDeclAttributes(S, NewVD, D);
6229 
6230   if (getLangOpts().CUDA) {
6231     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6232       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6233            diag::err_thread_unsupported);
6234     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6235     // storage [duration]."
6236     if (SC == SC_None && S->getFnParent() != nullptr &&
6237         (NewVD->hasAttr<CUDASharedAttr>() ||
6238          NewVD->hasAttr<CUDAConstantAttr>())) {
6239       NewVD->setStorageClass(SC_Static);
6240     }
6241   }
6242 
6243   // Ensure that dllimport globals without explicit storage class are treated as
6244   // extern. The storage class is set above using parsed attributes. Now we can
6245   // check the VarDecl itself.
6246   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6247          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6248          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6249 
6250   // In auto-retain/release, infer strong retension for variables of
6251   // retainable type.
6252   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6253     NewVD->setInvalidDecl();
6254 
6255   // Handle GNU asm-label extension (encoded as an attribute).
6256   if (Expr *E = (Expr*)D.getAsmLabel()) {
6257     // The parser guarantees this is a string.
6258     StringLiteral *SE = cast<StringLiteral>(E);
6259     StringRef Label = SE->getString();
6260     if (S->getFnParent() != nullptr) {
6261       switch (SC) {
6262       case SC_None:
6263       case SC_Auto:
6264         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6265         break;
6266       case SC_Register:
6267         // Local Named register
6268         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6269             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6270           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6271         break;
6272       case SC_Static:
6273       case SC_Extern:
6274       case SC_PrivateExtern:
6275         break;
6276       }
6277     } else if (SC == SC_Register) {
6278       // Global Named register
6279       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6280         const auto &TI = Context.getTargetInfo();
6281         bool HasSizeMismatch;
6282 
6283         if (!TI.isValidGCCRegisterName(Label))
6284           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6285         else if (!TI.validateGlobalRegisterVariable(Label,
6286                                                     Context.getTypeSize(R),
6287                                                     HasSizeMismatch))
6288           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6289         else if (HasSizeMismatch)
6290           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6291       }
6292 
6293       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6294         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6295         NewVD->setInvalidDecl(true);
6296       }
6297     }
6298 
6299     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6300                                                 Context, Label, 0));
6301   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6302     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6303       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6304     if (I != ExtnameUndeclaredIdentifiers.end()) {
6305       if (isDeclExternC(NewVD)) {
6306         NewVD->addAttr(I->second);
6307         ExtnameUndeclaredIdentifiers.erase(I);
6308       } else
6309         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6310             << /*Variable*/1 << NewVD;
6311     }
6312   }
6313 
6314   // Diagnose shadowed variables before filtering for scope.
6315   if (D.getCXXScopeSpec().isEmpty())
6316     CheckShadow(S, NewVD, Previous);
6317 
6318   // Don't consider existing declarations that are in a different
6319   // scope and are out-of-semantic-context declarations (if the new
6320   // declaration has linkage).
6321   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6322                        D.getCXXScopeSpec().isNotEmpty() ||
6323                        IsExplicitSpecialization ||
6324                        IsVariableTemplateSpecialization);
6325 
6326   // Check whether the previous declaration is in the same block scope. This
6327   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6328   if (getLangOpts().CPlusPlus &&
6329       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6330     NewVD->setPreviousDeclInSameBlockScope(
6331         Previous.isSingleResult() && !Previous.isShadowed() &&
6332         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6333 
6334   if (!getLangOpts().CPlusPlus) {
6335     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6336   } else {
6337     // If this is an explicit specialization of a static data member, check it.
6338     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6339         CheckMemberSpecialization(NewVD, Previous))
6340       NewVD->setInvalidDecl();
6341 
6342     // Merge the decl with the existing one if appropriate.
6343     if (!Previous.empty()) {
6344       if (Previous.isSingleResult() &&
6345           isa<FieldDecl>(Previous.getFoundDecl()) &&
6346           D.getCXXScopeSpec().isSet()) {
6347         // The user tried to define a non-static data member
6348         // out-of-line (C++ [dcl.meaning]p1).
6349         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6350           << D.getCXXScopeSpec().getRange();
6351         Previous.clear();
6352         NewVD->setInvalidDecl();
6353       }
6354     } else if (D.getCXXScopeSpec().isSet()) {
6355       // No previous declaration in the qualifying scope.
6356       Diag(D.getIdentifierLoc(), diag::err_no_member)
6357         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6358         << D.getCXXScopeSpec().getRange();
6359       NewVD->setInvalidDecl();
6360     }
6361 
6362     if (!IsVariableTemplateSpecialization)
6363       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6364 
6365     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6366     // an explicit specialization (14.8.3) or a partial specialization of a
6367     // concept definition.
6368     if (IsVariableTemplateSpecialization &&
6369         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6370         Previous.isSingleResult()) {
6371       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6372       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6373         if (VarTmpl->isConcept()) {
6374           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6375               << 1                            /*variable*/
6376               << (IsPartialSpecialization ? 2 /*partially specialized*/
6377                                           : 1 /*explicitly specialized*/);
6378           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6379           NewVD->setInvalidDecl();
6380         }
6381       }
6382     }
6383 
6384     if (NewTemplate) {
6385       VarTemplateDecl *PrevVarTemplate =
6386           NewVD->getPreviousDecl()
6387               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6388               : nullptr;
6389 
6390       // Check the template parameter list of this declaration, possibly
6391       // merging in the template parameter list from the previous variable
6392       // template declaration.
6393       if (CheckTemplateParameterList(
6394               TemplateParams,
6395               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6396                               : nullptr,
6397               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6398                DC->isDependentContext())
6399                   ? TPC_ClassTemplateMember
6400                   : TPC_VarTemplate))
6401         NewVD->setInvalidDecl();
6402 
6403       // If we are providing an explicit specialization of a static variable
6404       // template, make a note of that.
6405       if (PrevVarTemplate &&
6406           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6407         PrevVarTemplate->setMemberSpecialization();
6408     }
6409   }
6410 
6411   ProcessPragmaWeak(S, NewVD);
6412 
6413   // If this is the first declaration of an extern C variable, update
6414   // the map of such variables.
6415   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6416       isIncompleteDeclExternC(*this, NewVD))
6417     RegisterLocallyScopedExternCDecl(NewVD, S);
6418 
6419   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6420     Decl *ManglingContextDecl;
6421     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6422             NewVD->getDeclContext(), ManglingContextDecl)) {
6423       Context.setManglingNumber(
6424           NewVD, MCtx->getManglingNumber(
6425                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6426       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6427     }
6428   }
6429 
6430   // Special handling of variable named 'main'.
6431   if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6432       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6433       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6434 
6435     // C++ [basic.start.main]p3
6436     // A program that declares a variable main at global scope is ill-formed.
6437     if (getLangOpts().CPlusPlus)
6438       Diag(D.getLocStart(), diag::err_main_global_variable);
6439 
6440     // In C, and external-linkage variable named main results in undefined
6441     // behavior.
6442     else if (NewVD->hasExternalFormalLinkage())
6443       Diag(D.getLocStart(), diag::warn_main_redefined);
6444   }
6445 
6446   if (D.isRedeclaration() && !Previous.empty()) {
6447     checkDLLAttributeRedeclaration(
6448         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6449         IsExplicitSpecialization, D.isFunctionDefinition());
6450   }
6451 
6452   if (NewTemplate) {
6453     if (NewVD->isInvalidDecl())
6454       NewTemplate->setInvalidDecl();
6455     ActOnDocumentableDecl(NewTemplate);
6456     return NewTemplate;
6457   }
6458 
6459   return NewVD;
6460 }
6461 
6462 /// Enum describing the %select options in diag::warn_decl_shadow.
6463 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
6464 
6465 /// Determine what kind of declaration we're shadowing.
6466 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6467                                                 const DeclContext *OldDC) {
6468   if (isa<RecordDecl>(OldDC))
6469     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6470   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6471 }
6472 
6473 /// \brief Diagnose variable or built-in function shadowing.  Implements
6474 /// -Wshadow.
6475 ///
6476 /// This method is called whenever a VarDecl is added to a "useful"
6477 /// scope.
6478 ///
6479 /// \param S the scope in which the shadowing name is being declared
6480 /// \param R the lookup of the name
6481 ///
6482 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6483   // Return if warning is ignored.
6484   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6485     return;
6486 
6487   // Don't diagnose declarations at file scope.
6488   if (D->hasGlobalStorage())
6489     return;
6490 
6491   DeclContext *NewDC = D->getDeclContext();
6492 
6493   // Only diagnose if we're shadowing an unambiguous field or variable.
6494   if (R.getResultKind() != LookupResult::Found)
6495     return;
6496 
6497   NamedDecl* ShadowedDecl = R.getFoundDecl();
6498   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6499     return;
6500 
6501   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6502     // Fields are not shadowed by variables in C++ static methods.
6503     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6504       if (MD->isStatic())
6505         return;
6506 
6507     // Fields shadowed by constructor parameters are a special case. Usually
6508     // the constructor initializes the field with the parameter.
6509     if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
6510       // Remember that this was shadowed so we can either warn about its
6511       // modification or its existence depending on warning settings.
6512       D = D->getCanonicalDecl();
6513       ShadowingDecls.insert({D, FD});
6514       return;
6515     }
6516   }
6517 
6518   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6519     if (shadowedVar->isExternC()) {
6520       // For shadowing external vars, make sure that we point to the global
6521       // declaration, not a locally scoped extern declaration.
6522       for (auto I : shadowedVar->redecls())
6523         if (I->isFileVarDecl()) {
6524           ShadowedDecl = I;
6525           break;
6526         }
6527     }
6528 
6529   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6530 
6531   // Only warn about certain kinds of shadowing for class members.
6532   if (NewDC && NewDC->isRecord()) {
6533     // In particular, don't warn about shadowing non-class members.
6534     if (!OldDC->isRecord())
6535       return;
6536 
6537     // TODO: should we warn about static data members shadowing
6538     // static data members from base classes?
6539 
6540     // TODO: don't diagnose for inaccessible shadowed members.
6541     // This is hard to do perfectly because we might friend the
6542     // shadowing context, but that's just a false negative.
6543   }
6544 
6545 
6546   DeclarationName Name = R.getLookupName();
6547 
6548   // Emit warning and note.
6549   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6550     return;
6551   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6552   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6553   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6554 }
6555 
6556 /// \brief Check -Wshadow without the advantage of a previous lookup.
6557 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6558   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6559     return;
6560 
6561   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6562                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6563   LookupName(R, S);
6564   CheckShadow(S, D, R);
6565 }
6566 
6567 /// Check if 'E', which is an expression that is about to be modified, refers
6568 /// to a constructor parameter that shadows a field.
6569 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6570   // Quickly ignore expressions that can't be shadowing ctor parameters.
6571   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6572     return;
6573   E = E->IgnoreParenImpCasts();
6574   auto *DRE = dyn_cast<DeclRefExpr>(E);
6575   if (!DRE)
6576     return;
6577   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6578   auto I = ShadowingDecls.find(D);
6579   if (I == ShadowingDecls.end())
6580     return;
6581   const NamedDecl *ShadowedDecl = I->second;
6582   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6583   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6584   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6585   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6586 
6587   // Avoid issuing multiple warnings about the same decl.
6588   ShadowingDecls.erase(I);
6589 }
6590 
6591 /// Check for conflict between this global or extern "C" declaration and
6592 /// previous global or extern "C" declarations. This is only used in C++.
6593 template<typename T>
6594 static bool checkGlobalOrExternCConflict(
6595     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6596   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6597   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6598 
6599   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6600     // The common case: this global doesn't conflict with any extern "C"
6601     // declaration.
6602     return false;
6603   }
6604 
6605   if (Prev) {
6606     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6607       // Both the old and new declarations have C language linkage. This is a
6608       // redeclaration.
6609       Previous.clear();
6610       Previous.addDecl(Prev);
6611       return true;
6612     }
6613 
6614     // This is a global, non-extern "C" declaration, and there is a previous
6615     // non-global extern "C" declaration. Diagnose if this is a variable
6616     // declaration.
6617     if (!isa<VarDecl>(ND))
6618       return false;
6619   } else {
6620     // The declaration is extern "C". Check for any declaration in the
6621     // translation unit which might conflict.
6622     if (IsGlobal) {
6623       // We have already performed the lookup into the translation unit.
6624       IsGlobal = false;
6625       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6626            I != E; ++I) {
6627         if (isa<VarDecl>(*I)) {
6628           Prev = *I;
6629           break;
6630         }
6631       }
6632     } else {
6633       DeclContext::lookup_result R =
6634           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6635       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6636            I != E; ++I) {
6637         if (isa<VarDecl>(*I)) {
6638           Prev = *I;
6639           break;
6640         }
6641         // FIXME: If we have any other entity with this name in global scope,
6642         // the declaration is ill-formed, but that is a defect: it breaks the
6643         // 'stat' hack, for instance. Only variables can have mangled name
6644         // clashes with extern "C" declarations, so only they deserve a
6645         // diagnostic.
6646       }
6647     }
6648 
6649     if (!Prev)
6650       return false;
6651   }
6652 
6653   // Use the first declaration's location to ensure we point at something which
6654   // is lexically inside an extern "C" linkage-spec.
6655   assert(Prev && "should have found a previous declaration to diagnose");
6656   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6657     Prev = FD->getFirstDecl();
6658   else
6659     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6660 
6661   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6662     << IsGlobal << ND;
6663   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6664     << IsGlobal;
6665   return false;
6666 }
6667 
6668 /// Apply special rules for handling extern "C" declarations. Returns \c true
6669 /// if we have found that this is a redeclaration of some prior entity.
6670 ///
6671 /// Per C++ [dcl.link]p6:
6672 ///   Two declarations [for a function or variable] with C language linkage
6673 ///   with the same name that appear in different scopes refer to the same
6674 ///   [entity]. An entity with C language linkage shall not be declared with
6675 ///   the same name as an entity in global scope.
6676 template<typename T>
6677 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6678                                                   LookupResult &Previous) {
6679   if (!S.getLangOpts().CPlusPlus) {
6680     // In C, when declaring a global variable, look for a corresponding 'extern'
6681     // variable declared in function scope. We don't need this in C++, because
6682     // we find local extern decls in the surrounding file-scope DeclContext.
6683     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6684       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6685         Previous.clear();
6686         Previous.addDecl(Prev);
6687         return true;
6688       }
6689     }
6690     return false;
6691   }
6692 
6693   // A declaration in the translation unit can conflict with an extern "C"
6694   // declaration.
6695   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6696     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6697 
6698   // An extern "C" declaration can conflict with a declaration in the
6699   // translation unit or can be a redeclaration of an extern "C" declaration
6700   // in another scope.
6701   if (isIncompleteDeclExternC(S,ND))
6702     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6703 
6704   // Neither global nor extern "C": nothing to do.
6705   return false;
6706 }
6707 
6708 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6709   // If the decl is already known invalid, don't check it.
6710   if (NewVD->isInvalidDecl())
6711     return;
6712 
6713   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6714   QualType T = TInfo->getType();
6715 
6716   // Defer checking an 'auto' type until its initializer is attached.
6717   if (T->isUndeducedType())
6718     return;
6719 
6720   if (NewVD->hasAttrs())
6721     CheckAlignasUnderalignment(NewVD);
6722 
6723   if (T->isObjCObjectType()) {
6724     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6725       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6726     T = Context.getObjCObjectPointerType(T);
6727     NewVD->setType(T);
6728   }
6729 
6730   // Emit an error if an address space was applied to decl with local storage.
6731   // This includes arrays of objects with address space qualifiers, but not
6732   // automatic variables that point to other address spaces.
6733   // ISO/IEC TR 18037 S5.1.2
6734   if (!getLangOpts().OpenCL
6735       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6736     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6737     NewVD->setInvalidDecl();
6738     return;
6739   }
6740 
6741   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
6742   // scope.
6743   if (getLangOpts().OpenCLVersion == 120 &&
6744       !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6745       NewVD->isStaticLocal()) {
6746     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6747     NewVD->setInvalidDecl();
6748     return;
6749   }
6750 
6751   if (getLangOpts().OpenCL) {
6752     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
6753     if (NewVD->hasAttr<BlocksAttr>()) {
6754       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
6755       return;
6756     }
6757 
6758     if (T->isBlockPointerType()) {
6759       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
6760       // can't use 'extern' storage class.
6761       if (!T.isConstQualified()) {
6762         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
6763             << 0 /*const*/;
6764         NewVD->setInvalidDecl();
6765         return;
6766       }
6767       if (NewVD->hasExternalStorage()) {
6768         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
6769         NewVD->setInvalidDecl();
6770         return;
6771       }
6772       // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported.
6773       // TODO: this check is not enough as it doesn't diagnose the typedef
6774       const BlockPointerType *BlkTy = T->getAs<BlockPointerType>();
6775       const FunctionProtoType *FTy =
6776           BlkTy->getPointeeType()->getAs<FunctionProtoType>();
6777       if (FTy && FTy->isVariadic()) {
6778         Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic)
6779             << T << NewVD->getSourceRange();
6780         NewVD->setInvalidDecl();
6781         return;
6782       }
6783     }
6784     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6785     // __constant address space.
6786     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6787     // variables inside a function can also be declared in the global
6788     // address space.
6789     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
6790         NewVD->hasExternalStorage()) {
6791       if (!T->isSamplerT() &&
6792           !(T.getAddressSpace() == LangAS::opencl_constant ||
6793             (T.getAddressSpace() == LangAS::opencl_global &&
6794              getLangOpts().OpenCLVersion == 200))) {
6795         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
6796         if (getLangOpts().OpenCLVersion == 200)
6797           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6798               << Scope << "global or constant";
6799         else
6800           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6801               << Scope << "constant";
6802         NewVD->setInvalidDecl();
6803         return;
6804       }
6805     } else {
6806       if (T.getAddressSpace() == LangAS::opencl_global) {
6807         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6808             << 1 /*is any function*/ << "global";
6809         NewVD->setInvalidDecl();
6810         return;
6811       }
6812       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6813       // in functions.
6814       if (T.getAddressSpace() == LangAS::opencl_constant ||
6815           T.getAddressSpace() == LangAS::opencl_local) {
6816         FunctionDecl *FD = getCurFunctionDecl();
6817         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6818           if (T.getAddressSpace() == LangAS::opencl_constant)
6819             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6820                 << 0 /*non-kernel only*/ << "constant";
6821           else
6822             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6823                 << 0 /*non-kernel only*/ << "local";
6824           NewVD->setInvalidDecl();
6825           return;
6826         }
6827       }
6828     }
6829   }
6830 
6831   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6832       && !NewVD->hasAttr<BlocksAttr>()) {
6833     if (getLangOpts().getGC() != LangOptions::NonGC)
6834       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6835     else {
6836       assert(!getLangOpts().ObjCAutoRefCount);
6837       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6838     }
6839   }
6840 
6841   bool isVM = T->isVariablyModifiedType();
6842   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6843       NewVD->hasAttr<BlocksAttr>())
6844     getCurFunction()->setHasBranchProtectedScope();
6845 
6846   if ((isVM && NewVD->hasLinkage()) ||
6847       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6848     bool SizeIsNegative;
6849     llvm::APSInt Oversized;
6850     TypeSourceInfo *FixedTInfo =
6851       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6852                                                     SizeIsNegative, Oversized);
6853     if (!FixedTInfo && T->isVariableArrayType()) {
6854       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6855       // FIXME: This won't give the correct result for
6856       // int a[10][n];
6857       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6858 
6859       if (NewVD->isFileVarDecl())
6860         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6861         << SizeRange;
6862       else if (NewVD->isStaticLocal())
6863         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6864         << SizeRange;
6865       else
6866         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6867         << SizeRange;
6868       NewVD->setInvalidDecl();
6869       return;
6870     }
6871 
6872     if (!FixedTInfo) {
6873       if (NewVD->isFileVarDecl())
6874         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6875       else
6876         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6877       NewVD->setInvalidDecl();
6878       return;
6879     }
6880 
6881     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6882     NewVD->setType(FixedTInfo->getType());
6883     NewVD->setTypeSourceInfo(FixedTInfo);
6884   }
6885 
6886   if (T->isVoidType()) {
6887     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6888     //                    of objects and functions.
6889     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6890       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6891         << T;
6892       NewVD->setInvalidDecl();
6893       return;
6894     }
6895   }
6896 
6897   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6898     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6899     NewVD->setInvalidDecl();
6900     return;
6901   }
6902 
6903   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6904     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6905     NewVD->setInvalidDecl();
6906     return;
6907   }
6908 
6909   if (NewVD->isConstexpr() && !T->isDependentType() &&
6910       RequireLiteralType(NewVD->getLocation(), T,
6911                          diag::err_constexpr_var_non_literal)) {
6912     NewVD->setInvalidDecl();
6913     return;
6914   }
6915 }
6916 
6917 /// \brief Perform semantic checking on a newly-created variable
6918 /// declaration.
6919 ///
6920 /// This routine performs all of the type-checking required for a
6921 /// variable declaration once it has been built. It is used both to
6922 /// check variables after they have been parsed and their declarators
6923 /// have been translated into a declaration, and to check variables
6924 /// that have been instantiated from a template.
6925 ///
6926 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6927 ///
6928 /// Returns true if the variable declaration is a redeclaration.
6929 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6930   CheckVariableDeclarationType(NewVD);
6931 
6932   // If the decl is already known invalid, don't check it.
6933   if (NewVD->isInvalidDecl())
6934     return false;
6935 
6936   // If we did not find anything by this name, look for a non-visible
6937   // extern "C" declaration with the same name.
6938   if (Previous.empty() &&
6939       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6940     Previous.setShadowed();
6941 
6942   if (!Previous.empty()) {
6943     MergeVarDecl(NewVD, Previous);
6944     return true;
6945   }
6946   return false;
6947 }
6948 
6949 namespace {
6950 struct FindOverriddenMethod {
6951   Sema *S;
6952   CXXMethodDecl *Method;
6953 
6954   /// Member lookup function that determines whether a given C++
6955   /// method overrides a method in a base class, to be used with
6956   /// CXXRecordDecl::lookupInBases().
6957   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6958     RecordDecl *BaseRecord =
6959         Specifier->getType()->getAs<RecordType>()->getDecl();
6960 
6961     DeclarationName Name = Method->getDeclName();
6962 
6963     // FIXME: Do we care about other names here too?
6964     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6965       // We really want to find the base class destructor here.
6966       QualType T = S->Context.getTypeDeclType(BaseRecord);
6967       CanQualType CT = S->Context.getCanonicalType(T);
6968 
6969       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
6970     }
6971 
6972     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6973          Path.Decls = Path.Decls.slice(1)) {
6974       NamedDecl *D = Path.Decls.front();
6975       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6976         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
6977           return true;
6978       }
6979     }
6980 
6981     return false;
6982   }
6983 };
6984 
6985 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6986 } // end anonymous namespace
6987 
6988 /// \brief Report an error regarding overriding, along with any relevant
6989 /// overriden methods.
6990 ///
6991 /// \param DiagID the primary error to report.
6992 /// \param MD the overriding method.
6993 /// \param OEK which overrides to include as notes.
6994 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6995                             OverrideErrorKind OEK = OEK_All) {
6996   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6997   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6998                                       E = MD->end_overridden_methods();
6999        I != E; ++I) {
7000     // This check (& the OEK parameter) could be replaced by a predicate, but
7001     // without lambdas that would be overkill. This is still nicer than writing
7002     // out the diag loop 3 times.
7003     if ((OEK == OEK_All) ||
7004         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7005         (OEK == OEK_Deleted && (*I)->isDeleted()))
7006       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7007   }
7008 }
7009 
7010 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7011 /// and if so, check that it's a valid override and remember it.
7012 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7013   // Look for methods in base classes that this method might override.
7014   CXXBasePaths Paths;
7015   FindOverriddenMethod FOM;
7016   FOM.Method = MD;
7017   FOM.S = this;
7018   bool hasDeletedOverridenMethods = false;
7019   bool hasNonDeletedOverridenMethods = false;
7020   bool AddedAny = false;
7021   if (DC->lookupInBases(FOM, Paths)) {
7022     for (auto *I : Paths.found_decls()) {
7023       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7024         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7025         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7026             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7027             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7028             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7029           hasDeletedOverridenMethods |= OldMD->isDeleted();
7030           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7031           AddedAny = true;
7032         }
7033       }
7034     }
7035   }
7036 
7037   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7038     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7039   }
7040   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7041     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7042   }
7043 
7044   return AddedAny;
7045 }
7046 
7047 namespace {
7048   // Struct for holding all of the extra arguments needed by
7049   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7050   struct ActOnFDArgs {
7051     Scope *S;
7052     Declarator &D;
7053     MultiTemplateParamsArg TemplateParamLists;
7054     bool AddToScope;
7055   };
7056 } // end anonymous namespace
7057 
7058 namespace {
7059 
7060 // Callback to only accept typo corrections that have a non-zero edit distance.
7061 // Also only accept corrections that have the same parent decl.
7062 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7063  public:
7064   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7065                             CXXRecordDecl *Parent)
7066       : Context(Context), OriginalFD(TypoFD),
7067         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7068 
7069   bool ValidateCandidate(const TypoCorrection &candidate) override {
7070     if (candidate.getEditDistance() == 0)
7071       return false;
7072 
7073     SmallVector<unsigned, 1> MismatchedParams;
7074     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7075                                           CDeclEnd = candidate.end();
7076          CDecl != CDeclEnd; ++CDecl) {
7077       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7078 
7079       if (FD && !FD->hasBody() &&
7080           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7081         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7082           CXXRecordDecl *Parent = MD->getParent();
7083           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7084             return true;
7085         } else if (!ExpectedParent) {
7086           return true;
7087         }
7088       }
7089     }
7090 
7091     return false;
7092   }
7093 
7094  private:
7095   ASTContext &Context;
7096   FunctionDecl *OriginalFD;
7097   CXXRecordDecl *ExpectedParent;
7098 };
7099 
7100 } // end anonymous namespace
7101 
7102 /// \brief Generate diagnostics for an invalid function redeclaration.
7103 ///
7104 /// This routine handles generating the diagnostic messages for an invalid
7105 /// function redeclaration, including finding possible similar declarations
7106 /// or performing typo correction if there are no previous declarations with
7107 /// the same name.
7108 ///
7109 /// Returns a NamedDecl iff typo correction was performed and substituting in
7110 /// the new declaration name does not cause new errors.
7111 static NamedDecl *DiagnoseInvalidRedeclaration(
7112     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7113     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7114   DeclarationName Name = NewFD->getDeclName();
7115   DeclContext *NewDC = NewFD->getDeclContext();
7116   SmallVector<unsigned, 1> MismatchedParams;
7117   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7118   TypoCorrection Correction;
7119   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7120   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7121                                    : diag::err_member_decl_does_not_match;
7122   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7123                     IsLocalFriend ? Sema::LookupLocalFriendName
7124                                   : Sema::LookupOrdinaryName,
7125                     Sema::ForRedeclaration);
7126 
7127   NewFD->setInvalidDecl();
7128   if (IsLocalFriend)
7129     SemaRef.LookupName(Prev, S);
7130   else
7131     SemaRef.LookupQualifiedName(Prev, NewDC);
7132   assert(!Prev.isAmbiguous() &&
7133          "Cannot have an ambiguity in previous-declaration lookup");
7134   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7135   if (!Prev.empty()) {
7136     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7137          Func != FuncEnd; ++Func) {
7138       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7139       if (FD &&
7140           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7141         // Add 1 to the index so that 0 can mean the mismatch didn't
7142         // involve a parameter
7143         unsigned ParamNum =
7144             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7145         NearMatches.push_back(std::make_pair(FD, ParamNum));
7146       }
7147     }
7148   // If the qualified name lookup yielded nothing, try typo correction
7149   } else if ((Correction = SemaRef.CorrectTypo(
7150                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7151                   &ExtraArgs.D.getCXXScopeSpec(),
7152                   llvm::make_unique<DifferentNameValidatorCCC>(
7153                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7154                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7155     // Set up everything for the call to ActOnFunctionDeclarator
7156     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7157                               ExtraArgs.D.getIdentifierLoc());
7158     Previous.clear();
7159     Previous.setLookupName(Correction.getCorrection());
7160     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7161                                     CDeclEnd = Correction.end();
7162          CDecl != CDeclEnd; ++CDecl) {
7163       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7164       if (FD && !FD->hasBody() &&
7165           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7166         Previous.addDecl(FD);
7167       }
7168     }
7169     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7170 
7171     NamedDecl *Result;
7172     // Retry building the function declaration with the new previous
7173     // declarations, and with errors suppressed.
7174     {
7175       // Trap errors.
7176       Sema::SFINAETrap Trap(SemaRef);
7177 
7178       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7179       // pieces need to verify the typo-corrected C++ declaration and hopefully
7180       // eliminate the need for the parameter pack ExtraArgs.
7181       Result = SemaRef.ActOnFunctionDeclarator(
7182           ExtraArgs.S, ExtraArgs.D,
7183           Correction.getCorrectionDecl()->getDeclContext(),
7184           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7185           ExtraArgs.AddToScope);
7186 
7187       if (Trap.hasErrorOccurred())
7188         Result = nullptr;
7189     }
7190 
7191     if (Result) {
7192       // Determine which correction we picked.
7193       Decl *Canonical = Result->getCanonicalDecl();
7194       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7195            I != E; ++I)
7196         if ((*I)->getCanonicalDecl() == Canonical)
7197           Correction.setCorrectionDecl(*I);
7198 
7199       SemaRef.diagnoseTypo(
7200           Correction,
7201           SemaRef.PDiag(IsLocalFriend
7202                           ? diag::err_no_matching_local_friend_suggest
7203                           : diag::err_member_decl_does_not_match_suggest)
7204             << Name << NewDC << IsDefinition);
7205       return Result;
7206     }
7207 
7208     // Pretend the typo correction never occurred
7209     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7210                               ExtraArgs.D.getIdentifierLoc());
7211     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7212     Previous.clear();
7213     Previous.setLookupName(Name);
7214   }
7215 
7216   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7217       << Name << NewDC << IsDefinition << NewFD->getLocation();
7218 
7219   bool NewFDisConst = false;
7220   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7221     NewFDisConst = NewMD->isConst();
7222 
7223   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7224        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7225        NearMatch != NearMatchEnd; ++NearMatch) {
7226     FunctionDecl *FD = NearMatch->first;
7227     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7228     bool FDisConst = MD && MD->isConst();
7229     bool IsMember = MD || !IsLocalFriend;
7230 
7231     // FIXME: These notes are poorly worded for the local friend case.
7232     if (unsigned Idx = NearMatch->second) {
7233       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7234       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7235       if (Loc.isInvalid()) Loc = FD->getLocation();
7236       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7237                                  : diag::note_local_decl_close_param_match)
7238         << Idx << FDParam->getType()
7239         << NewFD->getParamDecl(Idx - 1)->getType();
7240     } else if (FDisConst != NewFDisConst) {
7241       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7242           << NewFDisConst << FD->getSourceRange().getEnd();
7243     } else
7244       SemaRef.Diag(FD->getLocation(),
7245                    IsMember ? diag::note_member_def_close_match
7246                             : diag::note_local_decl_close_match);
7247   }
7248   return nullptr;
7249 }
7250 
7251 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7252   switch (D.getDeclSpec().getStorageClassSpec()) {
7253   default: llvm_unreachable("Unknown storage class!");
7254   case DeclSpec::SCS_auto:
7255   case DeclSpec::SCS_register:
7256   case DeclSpec::SCS_mutable:
7257     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7258                  diag::err_typecheck_sclass_func);
7259     D.setInvalidType();
7260     break;
7261   case DeclSpec::SCS_unspecified: break;
7262   case DeclSpec::SCS_extern:
7263     if (D.getDeclSpec().isExternInLinkageSpec())
7264       return SC_None;
7265     return SC_Extern;
7266   case DeclSpec::SCS_static: {
7267     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7268       // C99 6.7.1p5:
7269       //   The declaration of an identifier for a function that has
7270       //   block scope shall have no explicit storage-class specifier
7271       //   other than extern
7272       // See also (C++ [dcl.stc]p4).
7273       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7274                    diag::err_static_block_func);
7275       break;
7276     } else
7277       return SC_Static;
7278   }
7279   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7280   }
7281 
7282   // No explicit storage class has already been returned
7283   return SC_None;
7284 }
7285 
7286 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7287                                            DeclContext *DC, QualType &R,
7288                                            TypeSourceInfo *TInfo,
7289                                            StorageClass SC,
7290                                            bool &IsVirtualOkay) {
7291   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7292   DeclarationName Name = NameInfo.getName();
7293 
7294   FunctionDecl *NewFD = nullptr;
7295   bool isInline = D.getDeclSpec().isInlineSpecified();
7296 
7297   if (!SemaRef.getLangOpts().CPlusPlus) {
7298     // Determine whether the function was written with a
7299     // prototype. This true when:
7300     //   - there is a prototype in the declarator, or
7301     //   - the type R of the function is some kind of typedef or other reference
7302     //     to a type name (which eventually refers to a function type).
7303     bool HasPrototype =
7304       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7305       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7306 
7307     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7308                                  D.getLocStart(), NameInfo, R,
7309                                  TInfo, SC, isInline,
7310                                  HasPrototype, false);
7311     if (D.isInvalidType())
7312       NewFD->setInvalidDecl();
7313 
7314     return NewFD;
7315   }
7316 
7317   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7318   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7319 
7320   // Check that the return type is not an abstract class type.
7321   // For record types, this is done by the AbstractClassUsageDiagnoser once
7322   // the class has been completely parsed.
7323   if (!DC->isRecord() &&
7324       SemaRef.RequireNonAbstractType(
7325           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7326           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7327     D.setInvalidType();
7328 
7329   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7330     // This is a C++ constructor declaration.
7331     assert(DC->isRecord() &&
7332            "Constructors can only be declared in a member context");
7333 
7334     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7335     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7336                                       D.getLocStart(), NameInfo,
7337                                       R, TInfo, isExplicit, isInline,
7338                                       /*isImplicitlyDeclared=*/false,
7339                                       isConstexpr);
7340 
7341   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7342     // This is a C++ destructor declaration.
7343     if (DC->isRecord()) {
7344       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7345       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7346       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7347                                         SemaRef.Context, Record,
7348                                         D.getLocStart(),
7349                                         NameInfo, R, TInfo, isInline,
7350                                         /*isImplicitlyDeclared=*/false);
7351 
7352       // If the class is complete, then we now create the implicit exception
7353       // specification. If the class is incomplete or dependent, we can't do
7354       // it yet.
7355       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7356           Record->getDefinition() && !Record->isBeingDefined() &&
7357           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7358         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7359       }
7360 
7361       IsVirtualOkay = true;
7362       return NewDD;
7363 
7364     } else {
7365       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7366       D.setInvalidType();
7367 
7368       // Create a FunctionDecl to satisfy the function definition parsing
7369       // code path.
7370       return FunctionDecl::Create(SemaRef.Context, DC,
7371                                   D.getLocStart(),
7372                                   D.getIdentifierLoc(), Name, R, TInfo,
7373                                   SC, isInline,
7374                                   /*hasPrototype=*/true, isConstexpr);
7375     }
7376 
7377   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7378     if (!DC->isRecord()) {
7379       SemaRef.Diag(D.getIdentifierLoc(),
7380            diag::err_conv_function_not_member);
7381       return nullptr;
7382     }
7383 
7384     SemaRef.CheckConversionDeclarator(D, R, SC);
7385     IsVirtualOkay = true;
7386     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7387                                      D.getLocStart(), NameInfo,
7388                                      R, TInfo, isInline, isExplicit,
7389                                      isConstexpr, SourceLocation());
7390 
7391   } else if (DC->isRecord()) {
7392     // If the name of the function is the same as the name of the record,
7393     // then this must be an invalid constructor that has a return type.
7394     // (The parser checks for a return type and makes the declarator a
7395     // constructor if it has no return type).
7396     if (Name.getAsIdentifierInfo() &&
7397         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7398       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7399         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7400         << SourceRange(D.getIdentifierLoc());
7401       return nullptr;
7402     }
7403 
7404     // This is a C++ method declaration.
7405     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7406                                                cast<CXXRecordDecl>(DC),
7407                                                D.getLocStart(), NameInfo, R,
7408                                                TInfo, SC, isInline,
7409                                                isConstexpr, SourceLocation());
7410     IsVirtualOkay = !Ret->isStatic();
7411     return Ret;
7412   } else {
7413     bool isFriend =
7414         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7415     if (!isFriend && SemaRef.CurContext->isRecord())
7416       return nullptr;
7417 
7418     // Determine whether the function was written with a
7419     // prototype. This true when:
7420     //   - we're in C++ (where every function has a prototype),
7421     return FunctionDecl::Create(SemaRef.Context, DC,
7422                                 D.getLocStart(),
7423                                 NameInfo, R, TInfo, SC, isInline,
7424                                 true/*HasPrototype*/, isConstexpr);
7425   }
7426 }
7427 
7428 enum OpenCLParamType {
7429   ValidKernelParam,
7430   PtrPtrKernelParam,
7431   PtrKernelParam,
7432   PrivatePtrKernelParam,
7433   InvalidKernelParam,
7434   RecordKernelParam
7435 };
7436 
7437 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7438   if (PT->isPointerType()) {
7439     QualType PointeeType = PT->getPointeeType();
7440     if (PointeeType->isPointerType())
7441       return PtrPtrKernelParam;
7442     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7443                                               : PtrKernelParam;
7444   }
7445 
7446   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7447   // be used as builtin types.
7448 
7449   if (PT->isImageType())
7450     return PtrKernelParam;
7451 
7452   if (PT->isBooleanType())
7453     return InvalidKernelParam;
7454 
7455   if (PT->isEventT())
7456     return InvalidKernelParam;
7457 
7458   if (PT->isHalfType())
7459     return InvalidKernelParam;
7460 
7461   if (PT->isRecordType())
7462     return RecordKernelParam;
7463 
7464   return ValidKernelParam;
7465 }
7466 
7467 static void checkIsValidOpenCLKernelParameter(
7468   Sema &S,
7469   Declarator &D,
7470   ParmVarDecl *Param,
7471   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7472   QualType PT = Param->getType();
7473 
7474   // Cache the valid types we encounter to avoid rechecking structs that are
7475   // used again
7476   if (ValidTypes.count(PT.getTypePtr()))
7477     return;
7478 
7479   switch (getOpenCLKernelParameterType(PT)) {
7480   case PtrPtrKernelParam:
7481     // OpenCL v1.2 s6.9.a:
7482     // A kernel function argument cannot be declared as a
7483     // pointer to a pointer type.
7484     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7485     D.setInvalidType();
7486     return;
7487 
7488   case PrivatePtrKernelParam:
7489     // OpenCL v1.2 s6.9.a:
7490     // A kernel function argument cannot be declared as a
7491     // pointer to the private address space.
7492     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7493     D.setInvalidType();
7494     return;
7495 
7496     // OpenCL v1.2 s6.9.k:
7497     // Arguments to kernel functions in a program cannot be declared with the
7498     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7499     // uintptr_t or a struct and/or union that contain fields declared to be
7500     // one of these built-in scalar types.
7501 
7502   case InvalidKernelParam:
7503     // OpenCL v1.2 s6.8 n:
7504     // A kernel function argument cannot be declared
7505     // of event_t type.
7506     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7507     D.setInvalidType();
7508     return;
7509 
7510   case PtrKernelParam:
7511   case ValidKernelParam:
7512     ValidTypes.insert(PT.getTypePtr());
7513     return;
7514 
7515   case RecordKernelParam:
7516     break;
7517   }
7518 
7519   // Track nested structs we will inspect
7520   SmallVector<const Decl *, 4> VisitStack;
7521 
7522   // Track where we are in the nested structs. Items will migrate from
7523   // VisitStack to HistoryStack as we do the DFS for bad field.
7524   SmallVector<const FieldDecl *, 4> HistoryStack;
7525   HistoryStack.push_back(nullptr);
7526 
7527   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7528   VisitStack.push_back(PD);
7529 
7530   assert(VisitStack.back() && "First decl null?");
7531 
7532   do {
7533     const Decl *Next = VisitStack.pop_back_val();
7534     if (!Next) {
7535       assert(!HistoryStack.empty());
7536       // Found a marker, we have gone up a level
7537       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7538         ValidTypes.insert(Hist->getType().getTypePtr());
7539 
7540       continue;
7541     }
7542 
7543     // Adds everything except the original parameter declaration (which is not a
7544     // field itself) to the history stack.
7545     const RecordDecl *RD;
7546     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7547       HistoryStack.push_back(Field);
7548       RD = Field->getType()->castAs<RecordType>()->getDecl();
7549     } else {
7550       RD = cast<RecordDecl>(Next);
7551     }
7552 
7553     // Add a null marker so we know when we've gone back up a level
7554     VisitStack.push_back(nullptr);
7555 
7556     for (const auto *FD : RD->fields()) {
7557       QualType QT = FD->getType();
7558 
7559       if (ValidTypes.count(QT.getTypePtr()))
7560         continue;
7561 
7562       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7563       if (ParamType == ValidKernelParam)
7564         continue;
7565 
7566       if (ParamType == RecordKernelParam) {
7567         VisitStack.push_back(FD);
7568         continue;
7569       }
7570 
7571       // OpenCL v1.2 s6.9.p:
7572       // Arguments to kernel functions that are declared to be a struct or union
7573       // do not allow OpenCL objects to be passed as elements of the struct or
7574       // union.
7575       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7576           ParamType == PrivatePtrKernelParam) {
7577         S.Diag(Param->getLocation(),
7578                diag::err_record_with_pointers_kernel_param)
7579           << PT->isUnionType()
7580           << PT;
7581       } else {
7582         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7583       }
7584 
7585       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7586         << PD->getDeclName();
7587 
7588       // We have an error, now let's go back up through history and show where
7589       // the offending field came from
7590       for (ArrayRef<const FieldDecl *>::const_iterator
7591                I = HistoryStack.begin() + 1,
7592                E = HistoryStack.end();
7593            I != E; ++I) {
7594         const FieldDecl *OuterField = *I;
7595         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7596           << OuterField->getType();
7597       }
7598 
7599       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7600         << QT->isPointerType()
7601         << QT;
7602       D.setInvalidType();
7603       return;
7604     }
7605   } while (!VisitStack.empty());
7606 }
7607 
7608 NamedDecl*
7609 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7610                               TypeSourceInfo *TInfo, LookupResult &Previous,
7611                               MultiTemplateParamsArg TemplateParamLists,
7612                               bool &AddToScope) {
7613   QualType R = TInfo->getType();
7614 
7615   assert(R.getTypePtr()->isFunctionType());
7616 
7617   // TODO: consider using NameInfo for diagnostic.
7618   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7619   DeclarationName Name = NameInfo.getName();
7620   StorageClass SC = getFunctionStorageClass(*this, D);
7621 
7622   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7623     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7624          diag::err_invalid_thread)
7625       << DeclSpec::getSpecifierName(TSCS);
7626 
7627   if (D.isFirstDeclarationOfMember())
7628     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7629                            D.getIdentifierLoc());
7630 
7631   bool isFriend = false;
7632   FunctionTemplateDecl *FunctionTemplate = nullptr;
7633   bool isExplicitSpecialization = false;
7634   bool isFunctionTemplateSpecialization = false;
7635 
7636   bool isDependentClassScopeExplicitSpecialization = false;
7637   bool HasExplicitTemplateArgs = false;
7638   TemplateArgumentListInfo TemplateArgs;
7639 
7640   bool isVirtualOkay = false;
7641 
7642   DeclContext *OriginalDC = DC;
7643   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7644 
7645   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7646                                               isVirtualOkay);
7647   if (!NewFD) return nullptr;
7648 
7649   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7650     NewFD->setTopLevelDeclInObjCContainer();
7651 
7652   // Set the lexical context. If this is a function-scope declaration, or has a
7653   // C++ scope specifier, or is the object of a friend declaration, the lexical
7654   // context will be different from the semantic context.
7655   NewFD->setLexicalDeclContext(CurContext);
7656 
7657   if (IsLocalExternDecl)
7658     NewFD->setLocalExternDecl();
7659 
7660   if (getLangOpts().CPlusPlus) {
7661     bool isInline = D.getDeclSpec().isInlineSpecified();
7662     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7663     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7664     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7665     bool isConcept = D.getDeclSpec().isConceptSpecified();
7666     isFriend = D.getDeclSpec().isFriendSpecified();
7667     if (isFriend && !isInline && D.isFunctionDefinition()) {
7668       // C++ [class.friend]p5
7669       //   A function can be defined in a friend declaration of a
7670       //   class . . . . Such a function is implicitly inline.
7671       NewFD->setImplicitlyInline();
7672     }
7673 
7674     // If this is a method defined in an __interface, and is not a constructor
7675     // or an overloaded operator, then set the pure flag (isVirtual will already
7676     // return true).
7677     if (const CXXRecordDecl *Parent =
7678           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7679       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7680         NewFD->setPure(true);
7681 
7682       // C++ [class.union]p2
7683       //   A union can have member functions, but not virtual functions.
7684       if (isVirtual && Parent->isUnion())
7685         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7686     }
7687 
7688     SetNestedNameSpecifier(NewFD, D);
7689     isExplicitSpecialization = false;
7690     isFunctionTemplateSpecialization = false;
7691     if (D.isInvalidType())
7692       NewFD->setInvalidDecl();
7693 
7694     // Match up the template parameter lists with the scope specifier, then
7695     // determine whether we have a template or a template specialization.
7696     bool Invalid = false;
7697     if (TemplateParameterList *TemplateParams =
7698             MatchTemplateParametersToScopeSpecifier(
7699                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7700                 D.getCXXScopeSpec(),
7701                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7702                     ? D.getName().TemplateId
7703                     : nullptr,
7704                 TemplateParamLists, isFriend, isExplicitSpecialization,
7705                 Invalid)) {
7706       if (TemplateParams->size() > 0) {
7707         // This is a function template
7708 
7709         // Check that we can declare a template here.
7710         if (CheckTemplateDeclScope(S, TemplateParams))
7711           NewFD->setInvalidDecl();
7712 
7713         // A destructor cannot be a template.
7714         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7715           Diag(NewFD->getLocation(), diag::err_destructor_template);
7716           NewFD->setInvalidDecl();
7717         }
7718 
7719         // If we're adding a template to a dependent context, we may need to
7720         // rebuilding some of the types used within the template parameter list,
7721         // now that we know what the current instantiation is.
7722         if (DC->isDependentContext()) {
7723           ContextRAII SavedContext(*this, DC);
7724           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7725             Invalid = true;
7726         }
7727 
7728         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7729                                                         NewFD->getLocation(),
7730                                                         Name, TemplateParams,
7731                                                         NewFD);
7732         FunctionTemplate->setLexicalDeclContext(CurContext);
7733         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7734 
7735         // For source fidelity, store the other template param lists.
7736         if (TemplateParamLists.size() > 1) {
7737           NewFD->setTemplateParameterListsInfo(Context,
7738                                                TemplateParamLists.drop_back(1));
7739         }
7740       } else {
7741         // This is a function template specialization.
7742         isFunctionTemplateSpecialization = true;
7743         // For source fidelity, store all the template param lists.
7744         if (TemplateParamLists.size() > 0)
7745           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7746 
7747         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7748         if (isFriend) {
7749           // We want to remove the "template<>", found here.
7750           SourceRange RemoveRange = TemplateParams->getSourceRange();
7751 
7752           // If we remove the template<> and the name is not a
7753           // template-id, we're actually silently creating a problem:
7754           // the friend declaration will refer to an untemplated decl,
7755           // and clearly the user wants a template specialization.  So
7756           // we need to insert '<>' after the name.
7757           SourceLocation InsertLoc;
7758           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7759             InsertLoc = D.getName().getSourceRange().getEnd();
7760             InsertLoc = getLocForEndOfToken(InsertLoc);
7761           }
7762 
7763           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7764             << Name << RemoveRange
7765             << FixItHint::CreateRemoval(RemoveRange)
7766             << FixItHint::CreateInsertion(InsertLoc, "<>");
7767         }
7768       }
7769     }
7770     else {
7771       // All template param lists were matched against the scope specifier:
7772       // this is NOT (an explicit specialization of) a template.
7773       if (TemplateParamLists.size() > 0)
7774         // For source fidelity, store all the template param lists.
7775         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7776     }
7777 
7778     if (Invalid) {
7779       NewFD->setInvalidDecl();
7780       if (FunctionTemplate)
7781         FunctionTemplate->setInvalidDecl();
7782     }
7783 
7784     // C++ [dcl.fct.spec]p5:
7785     //   The virtual specifier shall only be used in declarations of
7786     //   nonstatic class member functions that appear within a
7787     //   member-specification of a class declaration; see 10.3.
7788     //
7789     if (isVirtual && !NewFD->isInvalidDecl()) {
7790       if (!isVirtualOkay) {
7791         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7792              diag::err_virtual_non_function);
7793       } else if (!CurContext->isRecord()) {
7794         // 'virtual' was specified outside of the class.
7795         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7796              diag::err_virtual_out_of_class)
7797           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7798       } else if (NewFD->getDescribedFunctionTemplate()) {
7799         // C++ [temp.mem]p3:
7800         //  A member function template shall not be virtual.
7801         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7802              diag::err_virtual_member_function_template)
7803           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7804       } else {
7805         // Okay: Add virtual to the method.
7806         NewFD->setVirtualAsWritten(true);
7807       }
7808 
7809       if (getLangOpts().CPlusPlus14 &&
7810           NewFD->getReturnType()->isUndeducedType())
7811         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7812     }
7813 
7814     if (getLangOpts().CPlusPlus14 &&
7815         (NewFD->isDependentContext() ||
7816          (isFriend && CurContext->isDependentContext())) &&
7817         NewFD->getReturnType()->isUndeducedType()) {
7818       // If the function template is referenced directly (for instance, as a
7819       // member of the current instantiation), pretend it has a dependent type.
7820       // This is not really justified by the standard, but is the only sane
7821       // thing to do.
7822       // FIXME: For a friend function, we have not marked the function as being
7823       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7824       const FunctionProtoType *FPT =
7825           NewFD->getType()->castAs<FunctionProtoType>();
7826       QualType Result =
7827           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7828       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7829                                              FPT->getExtProtoInfo()));
7830     }
7831 
7832     // C++ [dcl.fct.spec]p3:
7833     //  The inline specifier shall not appear on a block scope function
7834     //  declaration.
7835     if (isInline && !NewFD->isInvalidDecl()) {
7836       if (CurContext->isFunctionOrMethod()) {
7837         // 'inline' is not allowed on block scope function declaration.
7838         Diag(D.getDeclSpec().getInlineSpecLoc(),
7839              diag::err_inline_declaration_block_scope) << Name
7840           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7841       }
7842     }
7843 
7844     // C++ [dcl.fct.spec]p6:
7845     //  The explicit specifier shall be used only in the declaration of a
7846     //  constructor or conversion function within its class definition;
7847     //  see 12.3.1 and 12.3.2.
7848     if (isExplicit && !NewFD->isInvalidDecl()) {
7849       if (!CurContext->isRecord()) {
7850         // 'explicit' was specified outside of the class.
7851         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7852              diag::err_explicit_out_of_class)
7853           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7854       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7855                  !isa<CXXConversionDecl>(NewFD)) {
7856         // 'explicit' was specified on a function that wasn't a constructor
7857         // or conversion function.
7858         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7859              diag::err_explicit_non_ctor_or_conv_function)
7860           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7861       }
7862     }
7863 
7864     if (isConstexpr) {
7865       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7866       // are implicitly inline.
7867       NewFD->setImplicitlyInline();
7868 
7869       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7870       // be either constructors or to return a literal type. Therefore,
7871       // destructors cannot be declared constexpr.
7872       if (isa<CXXDestructorDecl>(NewFD))
7873         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7874     }
7875 
7876     if (isConcept) {
7877       // This is a function concept.
7878       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
7879         FTD->setConcept();
7880 
7881       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7882       // applied only to the definition of a function template [...]
7883       if (!D.isFunctionDefinition()) {
7884         Diag(D.getDeclSpec().getConceptSpecLoc(),
7885              diag::err_function_concept_not_defined);
7886         NewFD->setInvalidDecl();
7887       }
7888 
7889       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7890       // have no exception-specification and is treated as if it were specified
7891       // with noexcept(true) (15.4). [...]
7892       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7893         if (FPT->hasExceptionSpec()) {
7894           SourceRange Range;
7895           if (D.isFunctionDeclarator())
7896             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7897           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7898               << FixItHint::CreateRemoval(Range);
7899           NewFD->setInvalidDecl();
7900         } else {
7901           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7902         }
7903 
7904         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7905         // following restrictions:
7906         // - The declared return type shall have the type bool.
7907         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
7908           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
7909           NewFD->setInvalidDecl();
7910         }
7911 
7912         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7913         // following restrictions:
7914         // - The declaration's parameter list shall be equivalent to an empty
7915         //   parameter list.
7916         if (FPT->getNumParams() > 0 || FPT->isVariadic())
7917           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7918       }
7919 
7920       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7921       // implicity defined to be a constexpr declaration (implicitly inline)
7922       NewFD->setImplicitlyInline();
7923 
7924       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7925       // be declared with the thread_local, inline, friend, or constexpr
7926       // specifiers, [...]
7927       if (isInline) {
7928         Diag(D.getDeclSpec().getInlineSpecLoc(),
7929              diag::err_concept_decl_invalid_specifiers)
7930             << 1 << 1;
7931         NewFD->setInvalidDecl(true);
7932       }
7933 
7934       if (isFriend) {
7935         Diag(D.getDeclSpec().getFriendSpecLoc(),
7936              diag::err_concept_decl_invalid_specifiers)
7937             << 1 << 2;
7938         NewFD->setInvalidDecl(true);
7939       }
7940 
7941       if (isConstexpr) {
7942         Diag(D.getDeclSpec().getConstexprSpecLoc(),
7943              diag::err_concept_decl_invalid_specifiers)
7944             << 1 << 3;
7945         NewFD->setInvalidDecl(true);
7946       }
7947 
7948       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7949       // applied only to the definition of a function template or variable
7950       // template, declared in namespace scope.
7951       if (isFunctionTemplateSpecialization) {
7952         Diag(D.getDeclSpec().getConceptSpecLoc(),
7953              diag::err_concept_specified_specialization) << 1;
7954         NewFD->setInvalidDecl(true);
7955         return NewFD;
7956       }
7957     }
7958 
7959     // If __module_private__ was specified, mark the function accordingly.
7960     if (D.getDeclSpec().isModulePrivateSpecified()) {
7961       if (isFunctionTemplateSpecialization) {
7962         SourceLocation ModulePrivateLoc
7963           = D.getDeclSpec().getModulePrivateSpecLoc();
7964         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7965           << 0
7966           << FixItHint::CreateRemoval(ModulePrivateLoc);
7967       } else {
7968         NewFD->setModulePrivate();
7969         if (FunctionTemplate)
7970           FunctionTemplate->setModulePrivate();
7971       }
7972     }
7973 
7974     if (isFriend) {
7975       if (FunctionTemplate) {
7976         FunctionTemplate->setObjectOfFriendDecl();
7977         FunctionTemplate->setAccess(AS_public);
7978       }
7979       NewFD->setObjectOfFriendDecl();
7980       NewFD->setAccess(AS_public);
7981     }
7982 
7983     // If a function is defined as defaulted or deleted, mark it as such now.
7984     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7985     // definition kind to FDK_Definition.
7986     switch (D.getFunctionDefinitionKind()) {
7987       case FDK_Declaration:
7988       case FDK_Definition:
7989         break;
7990 
7991       case FDK_Defaulted:
7992         NewFD->setDefaulted();
7993         break;
7994 
7995       case FDK_Deleted:
7996         NewFD->setDeletedAsWritten();
7997         break;
7998     }
7999 
8000     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8001         D.isFunctionDefinition()) {
8002       // C++ [class.mfct]p2:
8003       //   A member function may be defined (8.4) in its class definition, in
8004       //   which case it is an inline member function (7.1.2)
8005       NewFD->setImplicitlyInline();
8006     }
8007 
8008     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8009         !CurContext->isRecord()) {
8010       // C++ [class.static]p1:
8011       //   A data or function member of a class may be declared static
8012       //   in a class definition, in which case it is a static member of
8013       //   the class.
8014 
8015       // Complain about the 'static' specifier if it's on an out-of-line
8016       // member function definition.
8017       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8018            diag::err_static_out_of_line)
8019         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8020     }
8021 
8022     // C++11 [except.spec]p15:
8023     //   A deallocation function with no exception-specification is treated
8024     //   as if it were specified with noexcept(true).
8025     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8026     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8027          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8028         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8029       NewFD->setType(Context.getFunctionType(
8030           FPT->getReturnType(), FPT->getParamTypes(),
8031           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8032   }
8033 
8034   // Filter out previous declarations that don't match the scope.
8035   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8036                        D.getCXXScopeSpec().isNotEmpty() ||
8037                        isExplicitSpecialization ||
8038                        isFunctionTemplateSpecialization);
8039 
8040   // Handle GNU asm-label extension (encoded as an attribute).
8041   if (Expr *E = (Expr*) D.getAsmLabel()) {
8042     // The parser guarantees this is a string.
8043     StringLiteral *SE = cast<StringLiteral>(E);
8044     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8045                                                 SE->getString(), 0));
8046   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8047     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8048       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8049     if (I != ExtnameUndeclaredIdentifiers.end()) {
8050       if (isDeclExternC(NewFD)) {
8051         NewFD->addAttr(I->second);
8052         ExtnameUndeclaredIdentifiers.erase(I);
8053       } else
8054         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8055             << /*Variable*/0 << NewFD;
8056     }
8057   }
8058 
8059   // Copy the parameter declarations from the declarator D to the function
8060   // declaration NewFD, if they are available.  First scavenge them into Params.
8061   SmallVector<ParmVarDecl*, 16> Params;
8062   if (D.isFunctionDeclarator()) {
8063     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8064 
8065     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8066     // function that takes no arguments, not a function that takes a
8067     // single void argument.
8068     // We let through "const void" here because Sema::GetTypeForDeclarator
8069     // already checks for that case.
8070     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8071       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8072         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8073         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8074         Param->setDeclContext(NewFD);
8075         Params.push_back(Param);
8076 
8077         if (Param->isInvalidDecl())
8078           NewFD->setInvalidDecl();
8079       }
8080     }
8081   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8082     // When we're declaring a function with a typedef, typeof, etc as in the
8083     // following example, we'll need to synthesize (unnamed)
8084     // parameters for use in the declaration.
8085     //
8086     // @code
8087     // typedef void fn(int);
8088     // fn f;
8089     // @endcode
8090 
8091     // Synthesize a parameter for each argument type.
8092     for (const auto &AI : FT->param_types()) {
8093       ParmVarDecl *Param =
8094           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8095       Param->setScopeInfo(0, Params.size());
8096       Params.push_back(Param);
8097     }
8098   } else {
8099     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8100            "Should not need args for typedef of non-prototype fn");
8101   }
8102 
8103   // Finally, we know we have the right number of parameters, install them.
8104   NewFD->setParams(Params);
8105 
8106   // Find all anonymous symbols defined during the declaration of this function
8107   // and add to NewFD. This lets us track decls such 'enum Y' in:
8108   //
8109   //   void f(enum Y {AA} x) {}
8110   //
8111   // which would otherwise incorrectly end up in the translation unit scope.
8112   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
8113   DeclsInPrototypeScope.clear();
8114 
8115   if (D.getDeclSpec().isNoreturnSpecified())
8116     NewFD->addAttr(
8117         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8118                                        Context, 0));
8119 
8120   // Functions returning a variably modified type violate C99 6.7.5.2p2
8121   // because all functions have linkage.
8122   if (!NewFD->isInvalidDecl() &&
8123       NewFD->getReturnType()->isVariablyModifiedType()) {
8124     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8125     NewFD->setInvalidDecl();
8126   }
8127 
8128   // Apply an implicit SectionAttr if #pragma code_seg is active.
8129   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8130       !NewFD->hasAttr<SectionAttr>()) {
8131     NewFD->addAttr(
8132         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8133                                     CodeSegStack.CurrentValue->getString(),
8134                                     CodeSegStack.CurrentPragmaLocation));
8135     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8136                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8137                          ASTContext::PSF_Read,
8138                      NewFD))
8139       NewFD->dropAttr<SectionAttr>();
8140   }
8141 
8142   // Handle attributes.
8143   ProcessDeclAttributes(S, NewFD, D);
8144 
8145   if (getLangOpts().CUDA)
8146     maybeAddCUDAHostDeviceAttrs(S, NewFD, Previous);
8147 
8148   if (getLangOpts().OpenCL) {
8149     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8150     // type declaration will generate a compilation error.
8151     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8152     if (AddressSpace == LangAS::opencl_local ||
8153         AddressSpace == LangAS::opencl_global ||
8154         AddressSpace == LangAS::opencl_constant) {
8155       Diag(NewFD->getLocation(),
8156            diag::err_opencl_return_value_with_address_space);
8157       NewFD->setInvalidDecl();
8158     }
8159   }
8160 
8161   if (!getLangOpts().CPlusPlus) {
8162     // Perform semantic checking on the function declaration.
8163     bool isExplicitSpecialization=false;
8164     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8165       CheckMain(NewFD, D.getDeclSpec());
8166 
8167     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8168       CheckMSVCRTEntryPoint(NewFD);
8169 
8170     if (!NewFD->isInvalidDecl())
8171       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8172                                                   isExplicitSpecialization));
8173     else if (!Previous.empty())
8174       // Recover gracefully from an invalid redeclaration.
8175       D.setRedeclaration(true);
8176     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8177             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8178            "previous declaration set still overloaded");
8179 
8180     // Diagnose no-prototype function declarations with calling conventions that
8181     // don't support variadic calls. Only do this in C and do it after merging
8182     // possibly prototyped redeclarations.
8183     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8184     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8185       CallingConv CC = FT->getExtInfo().getCC();
8186       if (!supportsVariadicCall(CC)) {
8187         // Windows system headers sometimes accidentally use stdcall without
8188         // (void) parameters, so we relax this to a warning.
8189         int DiagID =
8190             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8191         Diag(NewFD->getLocation(), DiagID)
8192             << FunctionType::getNameForCallConv(CC);
8193       }
8194     }
8195   } else {
8196     // C++11 [replacement.functions]p3:
8197     //  The program's definitions shall not be specified as inline.
8198     //
8199     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8200     //
8201     // Suppress the diagnostic if the function is __attribute__((used)), since
8202     // that forces an external definition to be emitted.
8203     if (D.getDeclSpec().isInlineSpecified() &&
8204         NewFD->isReplaceableGlobalAllocationFunction() &&
8205         !NewFD->hasAttr<UsedAttr>())
8206       Diag(D.getDeclSpec().getInlineSpecLoc(),
8207            diag::ext_operator_new_delete_declared_inline)
8208         << NewFD->getDeclName();
8209 
8210     // If the declarator is a template-id, translate the parser's template
8211     // argument list into our AST format.
8212     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8213       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8214       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8215       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8216       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8217                                          TemplateId->NumArgs);
8218       translateTemplateArguments(TemplateArgsPtr,
8219                                  TemplateArgs);
8220 
8221       HasExplicitTemplateArgs = true;
8222 
8223       if (NewFD->isInvalidDecl()) {
8224         HasExplicitTemplateArgs = false;
8225       } else if (FunctionTemplate) {
8226         // Function template with explicit template arguments.
8227         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8228           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8229 
8230         HasExplicitTemplateArgs = false;
8231       } else {
8232         assert((isFunctionTemplateSpecialization ||
8233                 D.getDeclSpec().isFriendSpecified()) &&
8234                "should have a 'template<>' for this decl");
8235         // "friend void foo<>(int);" is an implicit specialization decl.
8236         isFunctionTemplateSpecialization = true;
8237       }
8238     } else if (isFriend && isFunctionTemplateSpecialization) {
8239       // This combination is only possible in a recovery case;  the user
8240       // wrote something like:
8241       //   template <> friend void foo(int);
8242       // which we're recovering from as if the user had written:
8243       //   friend void foo<>(int);
8244       // Go ahead and fake up a template id.
8245       HasExplicitTemplateArgs = true;
8246       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8247       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8248     }
8249 
8250     // If it's a friend (and only if it's a friend), it's possible
8251     // that either the specialized function type or the specialized
8252     // template is dependent, and therefore matching will fail.  In
8253     // this case, don't check the specialization yet.
8254     bool InstantiationDependent = false;
8255     if (isFunctionTemplateSpecialization && isFriend &&
8256         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8257          TemplateSpecializationType::anyDependentTemplateArguments(
8258             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
8259             InstantiationDependent))) {
8260       assert(HasExplicitTemplateArgs &&
8261              "friend function specialization without template args");
8262       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8263                                                        Previous))
8264         NewFD->setInvalidDecl();
8265     } else if (isFunctionTemplateSpecialization) {
8266       if (CurContext->isDependentContext() && CurContext->isRecord()
8267           && !isFriend) {
8268         isDependentClassScopeExplicitSpecialization = true;
8269         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8270           diag::ext_function_specialization_in_class :
8271           diag::err_function_specialization_in_class)
8272           << NewFD->getDeclName();
8273       } else if (CheckFunctionTemplateSpecialization(NewFD,
8274                                   (HasExplicitTemplateArgs ? &TemplateArgs
8275                                                            : nullptr),
8276                                                      Previous))
8277         NewFD->setInvalidDecl();
8278 
8279       // C++ [dcl.stc]p1:
8280       //   A storage-class-specifier shall not be specified in an explicit
8281       //   specialization (14.7.3)
8282       FunctionTemplateSpecializationInfo *Info =
8283           NewFD->getTemplateSpecializationInfo();
8284       if (Info && SC != SC_None) {
8285         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8286           Diag(NewFD->getLocation(),
8287                diag::err_explicit_specialization_inconsistent_storage_class)
8288             << SC
8289             << FixItHint::CreateRemoval(
8290                                       D.getDeclSpec().getStorageClassSpecLoc());
8291 
8292         else
8293           Diag(NewFD->getLocation(),
8294                diag::ext_explicit_specialization_storage_class)
8295             << FixItHint::CreateRemoval(
8296                                       D.getDeclSpec().getStorageClassSpecLoc());
8297       }
8298     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8299       if (CheckMemberSpecialization(NewFD, Previous))
8300           NewFD->setInvalidDecl();
8301     }
8302 
8303     // Perform semantic checking on the function declaration.
8304     if (!isDependentClassScopeExplicitSpecialization) {
8305       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8306         CheckMain(NewFD, D.getDeclSpec());
8307 
8308       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8309         CheckMSVCRTEntryPoint(NewFD);
8310 
8311       if (!NewFD->isInvalidDecl())
8312         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8313                                                     isExplicitSpecialization));
8314       else if (!Previous.empty())
8315         // Recover gracefully from an invalid redeclaration.
8316         D.setRedeclaration(true);
8317     }
8318 
8319     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8320             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8321            "previous declaration set still overloaded");
8322 
8323     NamedDecl *PrincipalDecl = (FunctionTemplate
8324                                 ? cast<NamedDecl>(FunctionTemplate)
8325                                 : NewFD);
8326 
8327     if (isFriend && D.isRedeclaration()) {
8328       AccessSpecifier Access = AS_public;
8329       if (!NewFD->isInvalidDecl())
8330         Access = NewFD->getPreviousDecl()->getAccess();
8331 
8332       NewFD->setAccess(Access);
8333       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8334     }
8335 
8336     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8337         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8338       PrincipalDecl->setNonMemberOperator();
8339 
8340     // If we have a function template, check the template parameter
8341     // list. This will check and merge default template arguments.
8342     if (FunctionTemplate) {
8343       FunctionTemplateDecl *PrevTemplate =
8344                                      FunctionTemplate->getPreviousDecl();
8345       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8346                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8347                                     : nullptr,
8348                             D.getDeclSpec().isFriendSpecified()
8349                               ? (D.isFunctionDefinition()
8350                                    ? TPC_FriendFunctionTemplateDefinition
8351                                    : TPC_FriendFunctionTemplate)
8352                               : (D.getCXXScopeSpec().isSet() &&
8353                                  DC && DC->isRecord() &&
8354                                  DC->isDependentContext())
8355                                   ? TPC_ClassTemplateMember
8356                                   : TPC_FunctionTemplate);
8357     }
8358 
8359     if (NewFD->isInvalidDecl()) {
8360       // Ignore all the rest of this.
8361     } else if (!D.isRedeclaration()) {
8362       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8363                                        AddToScope };
8364       // Fake up an access specifier if it's supposed to be a class member.
8365       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8366         NewFD->setAccess(AS_public);
8367 
8368       // Qualified decls generally require a previous declaration.
8369       if (D.getCXXScopeSpec().isSet()) {
8370         // ...with the major exception of templated-scope or
8371         // dependent-scope friend declarations.
8372 
8373         // TODO: we currently also suppress this check in dependent
8374         // contexts because (1) the parameter depth will be off when
8375         // matching friend templates and (2) we might actually be
8376         // selecting a friend based on a dependent factor.  But there
8377         // are situations where these conditions don't apply and we
8378         // can actually do this check immediately.
8379         if (isFriend &&
8380             (TemplateParamLists.size() ||
8381              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8382              CurContext->isDependentContext())) {
8383           // ignore these
8384         } else {
8385           // The user tried to provide an out-of-line definition for a
8386           // function that is a member of a class or namespace, but there
8387           // was no such member function declared (C++ [class.mfct]p2,
8388           // C++ [namespace.memdef]p2). For example:
8389           //
8390           // class X {
8391           //   void f() const;
8392           // };
8393           //
8394           // void X::f() { } // ill-formed
8395           //
8396           // Complain about this problem, and attempt to suggest close
8397           // matches (e.g., those that differ only in cv-qualifiers and
8398           // whether the parameter types are references).
8399 
8400           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8401                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8402             AddToScope = ExtraArgs.AddToScope;
8403             return Result;
8404           }
8405         }
8406 
8407         // Unqualified local friend declarations are required to resolve
8408         // to something.
8409       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8410         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8411                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8412           AddToScope = ExtraArgs.AddToScope;
8413           return Result;
8414         }
8415       }
8416     } else if (!D.isFunctionDefinition() &&
8417                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8418                !isFriend && !isFunctionTemplateSpecialization &&
8419                !isExplicitSpecialization) {
8420       // An out-of-line member function declaration must also be a
8421       // definition (C++ [class.mfct]p2).
8422       // Note that this is not the case for explicit specializations of
8423       // function templates or member functions of class templates, per
8424       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8425       // extension for compatibility with old SWIG code which likes to
8426       // generate them.
8427       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8428         << D.getCXXScopeSpec().getRange();
8429     }
8430   }
8431 
8432   ProcessPragmaWeak(S, NewFD);
8433   checkAttributesAfterMerging(*this, *NewFD);
8434 
8435   AddKnownFunctionAttributes(NewFD);
8436 
8437   if (NewFD->hasAttr<OverloadableAttr>() &&
8438       !NewFD->getType()->getAs<FunctionProtoType>()) {
8439     Diag(NewFD->getLocation(),
8440          diag::err_attribute_overloadable_no_prototype)
8441       << NewFD;
8442 
8443     // Turn this into a variadic function with no parameters.
8444     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8445     FunctionProtoType::ExtProtoInfo EPI(
8446         Context.getDefaultCallingConvention(true, false));
8447     EPI.Variadic = true;
8448     EPI.ExtInfo = FT->getExtInfo();
8449 
8450     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8451     NewFD->setType(R);
8452   }
8453 
8454   // If there's a #pragma GCC visibility in scope, and this isn't a class
8455   // member, set the visibility of this function.
8456   if (!DC->isRecord() && NewFD->isExternallyVisible())
8457     AddPushedVisibilityAttribute(NewFD);
8458 
8459   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8460   // marking the function.
8461   AddCFAuditedAttribute(NewFD);
8462 
8463   // If this is a function definition, check if we have to apply optnone due to
8464   // a pragma.
8465   if(D.isFunctionDefinition())
8466     AddRangeBasedOptnone(NewFD);
8467 
8468   // If this is the first declaration of an extern C variable, update
8469   // the map of such variables.
8470   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8471       isIncompleteDeclExternC(*this, NewFD))
8472     RegisterLocallyScopedExternCDecl(NewFD, S);
8473 
8474   // Set this FunctionDecl's range up to the right paren.
8475   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8476 
8477   if (D.isRedeclaration() && !Previous.empty()) {
8478     checkDLLAttributeRedeclaration(
8479         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8480         isExplicitSpecialization || isFunctionTemplateSpecialization,
8481         D.isFunctionDefinition());
8482   }
8483 
8484   if (getLangOpts().CUDA) {
8485     IdentifierInfo *II = NewFD->getIdentifier();
8486     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8487         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8488       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8489         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8490 
8491       Context.setcudaConfigureCallDecl(NewFD);
8492     }
8493 
8494     // Variadic functions, other than a *declaration* of printf, are not allowed
8495     // in device-side CUDA code, unless someone passed
8496     // -fcuda-allow-variadic-functions.
8497     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8498         (NewFD->hasAttr<CUDADeviceAttr>() ||
8499          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8500         !(II && II->isStr("printf") && NewFD->isExternC() &&
8501           !D.isFunctionDefinition())) {
8502       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8503     }
8504   }
8505 
8506   if (getLangOpts().CPlusPlus) {
8507     if (FunctionTemplate) {
8508       if (NewFD->isInvalidDecl())
8509         FunctionTemplate->setInvalidDecl();
8510       return FunctionTemplate;
8511     }
8512   }
8513 
8514   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8515     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8516     if ((getLangOpts().OpenCLVersion >= 120)
8517         && (SC == SC_Static)) {
8518       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8519       D.setInvalidType();
8520     }
8521 
8522     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8523     if (!NewFD->getReturnType()->isVoidType()) {
8524       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8525       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8526           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8527                                 : FixItHint());
8528       D.setInvalidType();
8529     }
8530 
8531     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8532     for (auto Param : NewFD->params())
8533       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8534   }
8535   for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
8536        PE = NewFD->param_end(); PI != PE; ++PI) {
8537     ParmVarDecl *Param = *PI;
8538     QualType PT = Param->getType();
8539 
8540     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8541     // types.
8542     if (getLangOpts().OpenCLVersion >= 200) {
8543       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8544         QualType ElemTy = PipeTy->getElementType();
8545           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8546             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8547             D.setInvalidType();
8548           }
8549       }
8550     }
8551   }
8552 
8553   MarkUnusedFileScopedDecl(NewFD);
8554 
8555   // Here we have an function template explicit specialization at class scope.
8556   // The actually specialization will be postponed to template instatiation
8557   // time via the ClassScopeFunctionSpecializationDecl node.
8558   if (isDependentClassScopeExplicitSpecialization) {
8559     ClassScopeFunctionSpecializationDecl *NewSpec =
8560                          ClassScopeFunctionSpecializationDecl::Create(
8561                                 Context, CurContext, SourceLocation(),
8562                                 cast<CXXMethodDecl>(NewFD),
8563                                 HasExplicitTemplateArgs, TemplateArgs);
8564     CurContext->addDecl(NewSpec);
8565     AddToScope = false;
8566   }
8567 
8568   return NewFD;
8569 }
8570 
8571 /// \brief Perform semantic checking of a new function declaration.
8572 ///
8573 /// Performs semantic analysis of the new function declaration
8574 /// NewFD. This routine performs all semantic checking that does not
8575 /// require the actual declarator involved in the declaration, and is
8576 /// used both for the declaration of functions as they are parsed
8577 /// (called via ActOnDeclarator) and for the declaration of functions
8578 /// that have been instantiated via C++ template instantiation (called
8579 /// via InstantiateDecl).
8580 ///
8581 /// \param IsExplicitSpecialization whether this new function declaration is
8582 /// an explicit specialization of the previous declaration.
8583 ///
8584 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8585 ///
8586 /// \returns true if the function declaration is a redeclaration.
8587 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8588                                     LookupResult &Previous,
8589                                     bool IsExplicitSpecialization) {
8590   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8591          "Variably modified return types are not handled here");
8592 
8593   // Determine whether the type of this function should be merged with
8594   // a previous visible declaration. This never happens for functions in C++,
8595   // and always happens in C if the previous declaration was visible.
8596   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8597                                !Previous.isShadowed();
8598 
8599   bool Redeclaration = false;
8600   NamedDecl *OldDecl = nullptr;
8601 
8602   // Merge or overload the declaration with an existing declaration of
8603   // the same name, if appropriate.
8604   if (!Previous.empty()) {
8605     // Determine whether NewFD is an overload of PrevDecl or
8606     // a declaration that requires merging. If it's an overload,
8607     // there's no more work to do here; we'll just add the new
8608     // function to the scope.
8609     if (!AllowOverloadingOfFunction(Previous, Context)) {
8610       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8611       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8612         Redeclaration = true;
8613         OldDecl = Candidate;
8614       }
8615     } else {
8616       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8617                             /*NewIsUsingDecl*/ false)) {
8618       case Ovl_Match:
8619         Redeclaration = true;
8620         break;
8621 
8622       case Ovl_NonFunction:
8623         Redeclaration = true;
8624         break;
8625 
8626       case Ovl_Overload:
8627         Redeclaration = false;
8628         break;
8629       }
8630 
8631       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8632         // If a function name is overloadable in C, then every function
8633         // with that name must be marked "overloadable".
8634         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8635           << Redeclaration << NewFD;
8636         NamedDecl *OverloadedDecl = nullptr;
8637         if (Redeclaration)
8638           OverloadedDecl = OldDecl;
8639         else if (!Previous.empty())
8640           OverloadedDecl = Previous.getRepresentativeDecl();
8641         if (OverloadedDecl)
8642           Diag(OverloadedDecl->getLocation(),
8643                diag::note_attribute_overloadable_prev_overload);
8644         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8645       }
8646     }
8647   }
8648 
8649   // Check for a previous extern "C" declaration with this name.
8650   if (!Redeclaration &&
8651       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8652     if (!Previous.empty()) {
8653       // This is an extern "C" declaration with the same name as a previous
8654       // declaration, and thus redeclares that entity...
8655       Redeclaration = true;
8656       OldDecl = Previous.getFoundDecl();
8657       MergeTypeWithPrevious = false;
8658 
8659       // ... except in the presence of __attribute__((overloadable)).
8660       if (OldDecl->hasAttr<OverloadableAttr>()) {
8661         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8662           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8663             << Redeclaration << NewFD;
8664           Diag(Previous.getFoundDecl()->getLocation(),
8665                diag::note_attribute_overloadable_prev_overload);
8666           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8667         }
8668         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8669           Redeclaration = false;
8670           OldDecl = nullptr;
8671         }
8672       }
8673     }
8674   }
8675 
8676   // C++11 [dcl.constexpr]p8:
8677   //   A constexpr specifier for a non-static member function that is not
8678   //   a constructor declares that member function to be const.
8679   //
8680   // This needs to be delayed until we know whether this is an out-of-line
8681   // definition of a static member function.
8682   //
8683   // This rule is not present in C++1y, so we produce a backwards
8684   // compatibility warning whenever it happens in C++11.
8685   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8686   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8687       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8688       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8689     CXXMethodDecl *OldMD = nullptr;
8690     if (OldDecl)
8691       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8692     if (!OldMD || !OldMD->isStatic()) {
8693       const FunctionProtoType *FPT =
8694         MD->getType()->castAs<FunctionProtoType>();
8695       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8696       EPI.TypeQuals |= Qualifiers::Const;
8697       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8698                                           FPT->getParamTypes(), EPI));
8699 
8700       // Warn that we did this, if we're not performing template instantiation.
8701       // In that case, we'll have warned already when the template was defined.
8702       if (ActiveTemplateInstantiations.empty()) {
8703         SourceLocation AddConstLoc;
8704         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8705                 .IgnoreParens().getAs<FunctionTypeLoc>())
8706           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8707 
8708         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8709           << FixItHint::CreateInsertion(AddConstLoc, " const");
8710       }
8711     }
8712   }
8713 
8714   if (Redeclaration) {
8715     // NewFD and OldDecl represent declarations that need to be
8716     // merged.
8717     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8718       NewFD->setInvalidDecl();
8719       return Redeclaration;
8720     }
8721 
8722     Previous.clear();
8723     Previous.addDecl(OldDecl);
8724 
8725     if (FunctionTemplateDecl *OldTemplateDecl
8726                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8727       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8728       FunctionTemplateDecl *NewTemplateDecl
8729         = NewFD->getDescribedFunctionTemplate();
8730       assert(NewTemplateDecl && "Template/non-template mismatch");
8731       if (CXXMethodDecl *Method
8732             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8733         Method->setAccess(OldTemplateDecl->getAccess());
8734         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8735       }
8736 
8737       // If this is an explicit specialization of a member that is a function
8738       // template, mark it as a member specialization.
8739       if (IsExplicitSpecialization &&
8740           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8741         NewTemplateDecl->setMemberSpecialization();
8742         assert(OldTemplateDecl->isMemberSpecialization());
8743         // Explicit specializations of a member template do not inherit deleted
8744         // status from the parent member template that they are specializing.
8745         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
8746           FunctionDecl *const OldTemplatedDecl =
8747               OldTemplateDecl->getTemplatedDecl();
8748           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
8749           OldTemplatedDecl->setDeletedAsWritten(false);
8750         }
8751       }
8752 
8753     } else {
8754       // This needs to happen first so that 'inline' propagates.
8755       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8756 
8757       if (isa<CXXMethodDecl>(NewFD))
8758         NewFD->setAccess(OldDecl->getAccess());
8759     }
8760   }
8761 
8762   // Semantic checking for this function declaration (in isolation).
8763 
8764   if (getLangOpts().CPlusPlus) {
8765     // C++-specific checks.
8766     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8767       CheckConstructor(Constructor);
8768     } else if (CXXDestructorDecl *Destructor =
8769                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8770       CXXRecordDecl *Record = Destructor->getParent();
8771       QualType ClassType = Context.getTypeDeclType(Record);
8772 
8773       // FIXME: Shouldn't we be able to perform this check even when the class
8774       // type is dependent? Both gcc and edg can handle that.
8775       if (!ClassType->isDependentType()) {
8776         DeclarationName Name
8777           = Context.DeclarationNames.getCXXDestructorName(
8778                                         Context.getCanonicalType(ClassType));
8779         if (NewFD->getDeclName() != Name) {
8780           Diag(NewFD->getLocation(), diag::err_destructor_name);
8781           NewFD->setInvalidDecl();
8782           return Redeclaration;
8783         }
8784       }
8785     } else if (CXXConversionDecl *Conversion
8786                = dyn_cast<CXXConversionDecl>(NewFD)) {
8787       ActOnConversionDeclarator(Conversion);
8788     }
8789 
8790     // Find any virtual functions that this function overrides.
8791     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8792       if (!Method->isFunctionTemplateSpecialization() &&
8793           !Method->getDescribedFunctionTemplate() &&
8794           Method->isCanonicalDecl()) {
8795         if (AddOverriddenMethods(Method->getParent(), Method)) {
8796           // If the function was marked as "static", we have a problem.
8797           if (NewFD->getStorageClass() == SC_Static) {
8798             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8799           }
8800         }
8801       }
8802 
8803       if (Method->isStatic())
8804         checkThisInStaticMemberFunctionType(Method);
8805     }
8806 
8807     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8808     if (NewFD->isOverloadedOperator() &&
8809         CheckOverloadedOperatorDeclaration(NewFD)) {
8810       NewFD->setInvalidDecl();
8811       return Redeclaration;
8812     }
8813 
8814     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8815     if (NewFD->getLiteralIdentifier() &&
8816         CheckLiteralOperatorDeclaration(NewFD)) {
8817       NewFD->setInvalidDecl();
8818       return Redeclaration;
8819     }
8820 
8821     // In C++, check default arguments now that we have merged decls. Unless
8822     // the lexical context is the class, because in this case this is done
8823     // during delayed parsing anyway.
8824     if (!CurContext->isRecord())
8825       CheckCXXDefaultArguments(NewFD);
8826 
8827     // If this function declares a builtin function, check the type of this
8828     // declaration against the expected type for the builtin.
8829     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8830       ASTContext::GetBuiltinTypeError Error;
8831       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8832       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8833       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8834         // The type of this function differs from the type of the builtin,
8835         // so forget about the builtin entirely.
8836         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8837       }
8838     }
8839 
8840     // If this function is declared as being extern "C", then check to see if
8841     // the function returns a UDT (class, struct, or union type) that is not C
8842     // compatible, and if it does, warn the user.
8843     // But, issue any diagnostic on the first declaration only.
8844     if (Previous.empty() && NewFD->isExternC()) {
8845       QualType R = NewFD->getReturnType();
8846       if (R->isIncompleteType() && !R->isVoidType())
8847         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8848             << NewFD << R;
8849       else if (!R.isPODType(Context) && !R->isVoidType() &&
8850                !R->isObjCObjectPointerType())
8851         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8852     }
8853   }
8854   return Redeclaration;
8855 }
8856 
8857 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8858   // C++11 [basic.start.main]p3:
8859   //   A program that [...] declares main to be inline, static or
8860   //   constexpr is ill-formed.
8861   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8862   //   appear in a declaration of main.
8863   // static main is not an error under C99, but we should warn about it.
8864   // We accept _Noreturn main as an extension.
8865   if (FD->getStorageClass() == SC_Static)
8866     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8867          ? diag::err_static_main : diag::warn_static_main)
8868       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8869   if (FD->isInlineSpecified())
8870     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8871       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8872   if (DS.isNoreturnSpecified()) {
8873     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8874     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8875     Diag(NoreturnLoc, diag::ext_noreturn_main);
8876     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8877       << FixItHint::CreateRemoval(NoreturnRange);
8878   }
8879   if (FD->isConstexpr()) {
8880     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8881       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8882     FD->setConstexpr(false);
8883   }
8884 
8885   if (getLangOpts().OpenCL) {
8886     Diag(FD->getLocation(), diag::err_opencl_no_main)
8887         << FD->hasAttr<OpenCLKernelAttr>();
8888     FD->setInvalidDecl();
8889     return;
8890   }
8891 
8892   QualType T = FD->getType();
8893   assert(T->isFunctionType() && "function decl is not of function type");
8894   const FunctionType* FT = T->castAs<FunctionType>();
8895 
8896   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8897     // In C with GNU extensions we allow main() to have non-integer return
8898     // type, but we should warn about the extension, and we disable the
8899     // implicit-return-zero rule.
8900 
8901     // GCC in C mode accepts qualified 'int'.
8902     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8903       FD->setHasImplicitReturnZero(true);
8904     else {
8905       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8906       SourceRange RTRange = FD->getReturnTypeSourceRange();
8907       if (RTRange.isValid())
8908         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8909             << FixItHint::CreateReplacement(RTRange, "int");
8910     }
8911   } else {
8912     // In C and C++, main magically returns 0 if you fall off the end;
8913     // set the flag which tells us that.
8914     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8915 
8916     // All the standards say that main() should return 'int'.
8917     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8918       FD->setHasImplicitReturnZero(true);
8919     else {
8920       // Otherwise, this is just a flat-out error.
8921       SourceRange RTRange = FD->getReturnTypeSourceRange();
8922       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8923           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8924                                 : FixItHint());
8925       FD->setInvalidDecl(true);
8926     }
8927   }
8928 
8929   // Treat protoless main() as nullary.
8930   if (isa<FunctionNoProtoType>(FT)) return;
8931 
8932   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8933   unsigned nparams = FTP->getNumParams();
8934   assert(FD->getNumParams() == nparams);
8935 
8936   bool HasExtraParameters = (nparams > 3);
8937 
8938   if (FTP->isVariadic()) {
8939     Diag(FD->getLocation(), diag::ext_variadic_main);
8940     // FIXME: if we had information about the location of the ellipsis, we
8941     // could add a FixIt hint to remove it as a parameter.
8942   }
8943 
8944   // Darwin passes an undocumented fourth argument of type char**.  If
8945   // other platforms start sprouting these, the logic below will start
8946   // getting shifty.
8947   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8948     HasExtraParameters = false;
8949 
8950   if (HasExtraParameters) {
8951     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8952     FD->setInvalidDecl(true);
8953     nparams = 3;
8954   }
8955 
8956   // FIXME: a lot of the following diagnostics would be improved
8957   // if we had some location information about types.
8958 
8959   QualType CharPP =
8960     Context.getPointerType(Context.getPointerType(Context.CharTy));
8961   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8962 
8963   for (unsigned i = 0; i < nparams; ++i) {
8964     QualType AT = FTP->getParamType(i);
8965 
8966     bool mismatch = true;
8967 
8968     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8969       mismatch = false;
8970     else if (Expected[i] == CharPP) {
8971       // As an extension, the following forms are okay:
8972       //   char const **
8973       //   char const * const *
8974       //   char * const *
8975 
8976       QualifierCollector qs;
8977       const PointerType* PT;
8978       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8979           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8980           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8981                               Context.CharTy)) {
8982         qs.removeConst();
8983         mismatch = !qs.empty();
8984       }
8985     }
8986 
8987     if (mismatch) {
8988       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8989       // TODO: suggest replacing given type with expected type
8990       FD->setInvalidDecl(true);
8991     }
8992   }
8993 
8994   if (nparams == 1 && !FD->isInvalidDecl()) {
8995     Diag(FD->getLocation(), diag::warn_main_one_arg);
8996   }
8997 
8998   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8999     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9000     FD->setInvalidDecl();
9001   }
9002 }
9003 
9004 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9005   QualType T = FD->getType();
9006   assert(T->isFunctionType() && "function decl is not of function type");
9007   const FunctionType *FT = T->castAs<FunctionType>();
9008 
9009   // Set an implicit return of 'zero' if the function can return some integral,
9010   // enumeration, pointer or nullptr type.
9011   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9012       FT->getReturnType()->isAnyPointerType() ||
9013       FT->getReturnType()->isNullPtrType())
9014     // DllMain is exempt because a return value of zero means it failed.
9015     if (FD->getName() != "DllMain")
9016       FD->setHasImplicitReturnZero(true);
9017 
9018   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9019     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9020     FD->setInvalidDecl();
9021   }
9022 }
9023 
9024 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9025   // FIXME: Need strict checking.  In C89, we need to check for
9026   // any assignment, increment, decrement, function-calls, or
9027   // commas outside of a sizeof.  In C99, it's the same list,
9028   // except that the aforementioned are allowed in unevaluated
9029   // expressions.  Everything else falls under the
9030   // "may accept other forms of constant expressions" exception.
9031   // (We never end up here for C++, so the constant expression
9032   // rules there don't matter.)
9033   const Expr *Culprit;
9034   if (Init->isConstantInitializer(Context, false, &Culprit))
9035     return false;
9036   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9037     << Culprit->getSourceRange();
9038   return true;
9039 }
9040 
9041 namespace {
9042   // Visits an initialization expression to see if OrigDecl is evaluated in
9043   // its own initialization and throws a warning if it does.
9044   class SelfReferenceChecker
9045       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9046     Sema &S;
9047     Decl *OrigDecl;
9048     bool isRecordType;
9049     bool isPODType;
9050     bool isReferenceType;
9051 
9052     bool isInitList;
9053     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9054 
9055   public:
9056     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9057 
9058     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9059                                                     S(S), OrigDecl(OrigDecl) {
9060       isPODType = false;
9061       isRecordType = false;
9062       isReferenceType = false;
9063       isInitList = false;
9064       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9065         isPODType = VD->getType().isPODType(S.Context);
9066         isRecordType = VD->getType()->isRecordType();
9067         isReferenceType = VD->getType()->isReferenceType();
9068       }
9069     }
9070 
9071     // For most expressions, just call the visitor.  For initializer lists,
9072     // track the index of the field being initialized since fields are
9073     // initialized in order allowing use of previously initialized fields.
9074     void CheckExpr(Expr *E) {
9075       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9076       if (!InitList) {
9077         Visit(E);
9078         return;
9079       }
9080 
9081       // Track and increment the index here.
9082       isInitList = true;
9083       InitFieldIndex.push_back(0);
9084       for (auto Child : InitList->children()) {
9085         CheckExpr(cast<Expr>(Child));
9086         ++InitFieldIndex.back();
9087       }
9088       InitFieldIndex.pop_back();
9089     }
9090 
9091     // Returns true if MemberExpr is checked and no futher checking is needed.
9092     // Returns false if additional checking is required.
9093     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9094       llvm::SmallVector<FieldDecl*, 4> Fields;
9095       Expr *Base = E;
9096       bool ReferenceField = false;
9097 
9098       // Get the field memebers used.
9099       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9100         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9101         if (!FD)
9102           return false;
9103         Fields.push_back(FD);
9104         if (FD->getType()->isReferenceType())
9105           ReferenceField = true;
9106         Base = ME->getBase()->IgnoreParenImpCasts();
9107       }
9108 
9109       // Keep checking only if the base Decl is the same.
9110       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9111       if (!DRE || DRE->getDecl() != OrigDecl)
9112         return false;
9113 
9114       // A reference field can be bound to an unininitialized field.
9115       if (CheckReference && !ReferenceField)
9116         return true;
9117 
9118       // Convert FieldDecls to their index number.
9119       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9120       for (const FieldDecl *I : llvm::reverse(Fields))
9121         UsedFieldIndex.push_back(I->getFieldIndex());
9122 
9123       // See if a warning is needed by checking the first difference in index
9124       // numbers.  If field being used has index less than the field being
9125       // initialized, then the use is safe.
9126       for (auto UsedIter = UsedFieldIndex.begin(),
9127                 UsedEnd = UsedFieldIndex.end(),
9128                 OrigIter = InitFieldIndex.begin(),
9129                 OrigEnd = InitFieldIndex.end();
9130            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9131         if (*UsedIter < *OrigIter)
9132           return true;
9133         if (*UsedIter > *OrigIter)
9134           break;
9135       }
9136 
9137       // TODO: Add a different warning which will print the field names.
9138       HandleDeclRefExpr(DRE);
9139       return true;
9140     }
9141 
9142     // For most expressions, the cast is directly above the DeclRefExpr.
9143     // For conditional operators, the cast can be outside the conditional
9144     // operator if both expressions are DeclRefExpr's.
9145     void HandleValue(Expr *E) {
9146       E = E->IgnoreParens();
9147       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9148         HandleDeclRefExpr(DRE);
9149         return;
9150       }
9151 
9152       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9153         Visit(CO->getCond());
9154         HandleValue(CO->getTrueExpr());
9155         HandleValue(CO->getFalseExpr());
9156         return;
9157       }
9158 
9159       if (BinaryConditionalOperator *BCO =
9160               dyn_cast<BinaryConditionalOperator>(E)) {
9161         Visit(BCO->getCond());
9162         HandleValue(BCO->getFalseExpr());
9163         return;
9164       }
9165 
9166       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9167         HandleValue(OVE->getSourceExpr());
9168         return;
9169       }
9170 
9171       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9172         if (BO->getOpcode() == BO_Comma) {
9173           Visit(BO->getLHS());
9174           HandleValue(BO->getRHS());
9175           return;
9176         }
9177       }
9178 
9179       if (isa<MemberExpr>(E)) {
9180         if (isInitList) {
9181           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9182                                       false /*CheckReference*/))
9183             return;
9184         }
9185 
9186         Expr *Base = E->IgnoreParenImpCasts();
9187         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9188           // Check for static member variables and don't warn on them.
9189           if (!isa<FieldDecl>(ME->getMemberDecl()))
9190             return;
9191           Base = ME->getBase()->IgnoreParenImpCasts();
9192         }
9193         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9194           HandleDeclRefExpr(DRE);
9195         return;
9196       }
9197 
9198       Visit(E);
9199     }
9200 
9201     // Reference types not handled in HandleValue are handled here since all
9202     // uses of references are bad, not just r-value uses.
9203     void VisitDeclRefExpr(DeclRefExpr *E) {
9204       if (isReferenceType)
9205         HandleDeclRefExpr(E);
9206     }
9207 
9208     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9209       if (E->getCastKind() == CK_LValueToRValue) {
9210         HandleValue(E->getSubExpr());
9211         return;
9212       }
9213 
9214       Inherited::VisitImplicitCastExpr(E);
9215     }
9216 
9217     void VisitMemberExpr(MemberExpr *E) {
9218       if (isInitList) {
9219         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9220           return;
9221       }
9222 
9223       // Don't warn on arrays since they can be treated as pointers.
9224       if (E->getType()->canDecayToPointerType()) return;
9225 
9226       // Warn when a non-static method call is followed by non-static member
9227       // field accesses, which is followed by a DeclRefExpr.
9228       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9229       bool Warn = (MD && !MD->isStatic());
9230       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9231       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9232         if (!isa<FieldDecl>(ME->getMemberDecl()))
9233           Warn = false;
9234         Base = ME->getBase()->IgnoreParenImpCasts();
9235       }
9236 
9237       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9238         if (Warn)
9239           HandleDeclRefExpr(DRE);
9240         return;
9241       }
9242 
9243       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9244       // Visit that expression.
9245       Visit(Base);
9246     }
9247 
9248     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9249       Expr *Callee = E->getCallee();
9250 
9251       if (isa<UnresolvedLookupExpr>(Callee))
9252         return Inherited::VisitCXXOperatorCallExpr(E);
9253 
9254       Visit(Callee);
9255       for (auto Arg: E->arguments())
9256         HandleValue(Arg->IgnoreParenImpCasts());
9257     }
9258 
9259     void VisitUnaryOperator(UnaryOperator *E) {
9260       // For POD record types, addresses of its own members are well-defined.
9261       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9262           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9263         if (!isPODType)
9264           HandleValue(E->getSubExpr());
9265         return;
9266       }
9267 
9268       if (E->isIncrementDecrementOp()) {
9269         HandleValue(E->getSubExpr());
9270         return;
9271       }
9272 
9273       Inherited::VisitUnaryOperator(E);
9274     }
9275 
9276     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9277 
9278     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9279       if (E->getConstructor()->isCopyConstructor()) {
9280         Expr *ArgExpr = E->getArg(0);
9281         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9282           if (ILE->getNumInits() == 1)
9283             ArgExpr = ILE->getInit(0);
9284         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9285           if (ICE->getCastKind() == CK_NoOp)
9286             ArgExpr = ICE->getSubExpr();
9287         HandleValue(ArgExpr);
9288         return;
9289       }
9290       Inherited::VisitCXXConstructExpr(E);
9291     }
9292 
9293     void VisitCallExpr(CallExpr *E) {
9294       // Treat std::move as a use.
9295       if (E->getNumArgs() == 1) {
9296         if (FunctionDecl *FD = E->getDirectCallee()) {
9297           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9298               FD->getIdentifier()->isStr("move")) {
9299             HandleValue(E->getArg(0));
9300             return;
9301           }
9302         }
9303       }
9304 
9305       Inherited::VisitCallExpr(E);
9306     }
9307 
9308     void VisitBinaryOperator(BinaryOperator *E) {
9309       if (E->isCompoundAssignmentOp()) {
9310         HandleValue(E->getLHS());
9311         Visit(E->getRHS());
9312         return;
9313       }
9314 
9315       Inherited::VisitBinaryOperator(E);
9316     }
9317 
9318     // A custom visitor for BinaryConditionalOperator is needed because the
9319     // regular visitor would check the condition and true expression separately
9320     // but both point to the same place giving duplicate diagnostics.
9321     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9322       Visit(E->getCond());
9323       Visit(E->getFalseExpr());
9324     }
9325 
9326     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9327       Decl* ReferenceDecl = DRE->getDecl();
9328       if (OrigDecl != ReferenceDecl) return;
9329       unsigned diag;
9330       if (isReferenceType) {
9331         diag = diag::warn_uninit_self_reference_in_reference_init;
9332       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9333         diag = diag::warn_static_self_reference_in_init;
9334       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9335                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9336                  DRE->getDecl()->getType()->isRecordType()) {
9337         diag = diag::warn_uninit_self_reference_in_init;
9338       } else {
9339         // Local variables will be handled by the CFG analysis.
9340         return;
9341       }
9342 
9343       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9344                             S.PDiag(diag)
9345                               << DRE->getNameInfo().getName()
9346                               << OrigDecl->getLocation()
9347                               << DRE->getSourceRange());
9348     }
9349   };
9350 
9351   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9352   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9353                                  bool DirectInit) {
9354     // Parameters arguments are occassionially constructed with itself,
9355     // for instance, in recursive functions.  Skip them.
9356     if (isa<ParmVarDecl>(OrigDecl))
9357       return;
9358 
9359     E = E->IgnoreParens();
9360 
9361     // Skip checking T a = a where T is not a record or reference type.
9362     // Doing so is a way to silence uninitialized warnings.
9363     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9364       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9365         if (ICE->getCastKind() == CK_LValueToRValue)
9366           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9367             if (DRE->getDecl() == OrigDecl)
9368               return;
9369 
9370     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9371   }
9372 } // end anonymous namespace
9373 
9374 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9375                                             DeclarationName Name, QualType Type,
9376                                             TypeSourceInfo *TSI,
9377                                             SourceRange Range, bool DirectInit,
9378                                             Expr *Init) {
9379   bool IsInitCapture = !VDecl;
9380   assert((!VDecl || !VDecl->isInitCapture()) &&
9381          "init captures are expected to be deduced prior to initialization");
9382 
9383   ArrayRef<Expr *> DeduceInits = Init;
9384   if (DirectInit) {
9385     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9386       DeduceInits = PL->exprs();
9387     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9388       DeduceInits = IL->inits();
9389   }
9390 
9391   // Deduction only works if we have exactly one source expression.
9392   if (DeduceInits.empty()) {
9393     // It isn't possible to write this directly, but it is possible to
9394     // end up in this situation with "auto x(some_pack...);"
9395     Diag(Init->getLocStart(), IsInitCapture
9396                                   ? diag::err_init_capture_no_expression
9397                                   : diag::err_auto_var_init_no_expression)
9398         << Name << Type << Range;
9399     return QualType();
9400   }
9401 
9402   if (DeduceInits.size() > 1) {
9403     Diag(DeduceInits[1]->getLocStart(),
9404          IsInitCapture ? diag::err_init_capture_multiple_expressions
9405                        : diag::err_auto_var_init_multiple_expressions)
9406         << Name << Type << Range;
9407     return QualType();
9408   }
9409 
9410   Expr *DeduceInit = DeduceInits[0];
9411   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9412     Diag(Init->getLocStart(), IsInitCapture
9413                                   ? diag::err_init_capture_paren_braces
9414                                   : diag::err_auto_var_init_paren_braces)
9415         << isa<InitListExpr>(Init) << Name << Type << Range;
9416     return QualType();
9417   }
9418 
9419   // Expressions default to 'id' when we're in a debugger.
9420   bool DefaultedAnyToId = false;
9421   if (getLangOpts().DebuggerCastResultToId &&
9422       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9423     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9424     if (Result.isInvalid()) {
9425       return QualType();
9426     }
9427     Init = Result.get();
9428     DefaultedAnyToId = true;
9429   }
9430 
9431   QualType DeducedType;
9432   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9433     if (!IsInitCapture)
9434       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9435     else if (isa<InitListExpr>(Init))
9436       Diag(Range.getBegin(),
9437            diag::err_init_capture_deduction_failure_from_init_list)
9438           << Name
9439           << (DeduceInit->getType().isNull() ? TSI->getType()
9440                                              : DeduceInit->getType())
9441           << DeduceInit->getSourceRange();
9442     else
9443       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9444           << Name << TSI->getType()
9445           << (DeduceInit->getType().isNull() ? TSI->getType()
9446                                              : DeduceInit->getType())
9447           << DeduceInit->getSourceRange();
9448   }
9449 
9450   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9451   // 'id' instead of a specific object type prevents most of our usual
9452   // checks.
9453   // We only want to warn outside of template instantiations, though:
9454   // inside a template, the 'id' could have come from a parameter.
9455   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9456       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9457     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9458     Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9459   }
9460 
9461   return DeducedType;
9462 }
9463 
9464 /// AddInitializerToDecl - Adds the initializer Init to the
9465 /// declaration dcl. If DirectInit is true, this is C++ direct
9466 /// initialization rather than copy initialization.
9467 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9468                                 bool DirectInit, bool TypeMayContainAuto) {
9469   // If there is no declaration, there was an error parsing it.  Just ignore
9470   // the initializer.
9471   if (!RealDecl || RealDecl->isInvalidDecl()) {
9472     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9473     return;
9474   }
9475 
9476   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9477     // Pure-specifiers are handled in ActOnPureSpecifier.
9478     Diag(Method->getLocation(), diag::err_member_function_initialization)
9479       << Method->getDeclName() << Init->getSourceRange();
9480     Method->setInvalidDecl();
9481     return;
9482   }
9483 
9484   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9485   if (!VDecl) {
9486     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9487     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9488     RealDecl->setInvalidDecl();
9489     return;
9490   }
9491 
9492   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9493   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9494     // Attempt typo correction early so that the type of the init expression can
9495     // be deduced based on the chosen correction if the original init contains a
9496     // TypoExpr.
9497     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9498     if (!Res.isUsable()) {
9499       RealDecl->setInvalidDecl();
9500       return;
9501     }
9502     Init = Res.get();
9503 
9504     QualType DeducedType = deduceVarTypeFromInitializer(
9505         VDecl, VDecl->getDeclName(), VDecl->getType(),
9506         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9507     if (DeducedType.isNull()) {
9508       RealDecl->setInvalidDecl();
9509       return;
9510     }
9511 
9512     VDecl->setType(DeducedType);
9513     assert(VDecl->isLinkageValid());
9514 
9515     // In ARC, infer lifetime.
9516     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9517       VDecl->setInvalidDecl();
9518 
9519     // If this is a redeclaration, check that the type we just deduced matches
9520     // the previously declared type.
9521     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9522       // We never need to merge the type, because we cannot form an incomplete
9523       // array of auto, nor deduce such a type.
9524       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9525     }
9526 
9527     // Check the deduced type is valid for a variable declaration.
9528     CheckVariableDeclarationType(VDecl);
9529     if (VDecl->isInvalidDecl())
9530       return;
9531   }
9532 
9533   // dllimport cannot be used on variable definitions.
9534   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9535     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9536     VDecl->setInvalidDecl();
9537     return;
9538   }
9539 
9540   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9541     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9542     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9543     VDecl->setInvalidDecl();
9544     return;
9545   }
9546 
9547   if (!VDecl->getType()->isDependentType()) {
9548     // A definition must end up with a complete type, which means it must be
9549     // complete with the restriction that an array type might be completed by
9550     // the initializer; note that later code assumes this restriction.
9551     QualType BaseDeclType = VDecl->getType();
9552     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9553       BaseDeclType = Array->getElementType();
9554     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9555                             diag::err_typecheck_decl_incomplete_type)) {
9556       RealDecl->setInvalidDecl();
9557       return;
9558     }
9559 
9560     // The variable can not have an abstract class type.
9561     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9562                                diag::err_abstract_type_in_decl,
9563                                AbstractVariableType))
9564       VDecl->setInvalidDecl();
9565   }
9566 
9567   VarDecl *Def;
9568   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9569     NamedDecl *Hidden = nullptr;
9570     if (!hasVisibleDefinition(Def, &Hidden) &&
9571         (VDecl->getFormalLinkage() == InternalLinkage ||
9572          VDecl->getDescribedVarTemplate() ||
9573          VDecl->getNumTemplateParameterLists() ||
9574          VDecl->getDeclContext()->isDependentContext())) {
9575       // The previous definition is hidden, and multiple definitions are
9576       // permitted (in separate TUs). Form another definition of it.
9577     } else {
9578       Diag(VDecl->getLocation(), diag::err_redefinition)
9579         << VDecl->getDeclName();
9580       Diag(Def->getLocation(), diag::note_previous_definition);
9581       VDecl->setInvalidDecl();
9582       return;
9583     }
9584   }
9585 
9586   if (getLangOpts().CPlusPlus) {
9587     // C++ [class.static.data]p4
9588     //   If a static data member is of const integral or const
9589     //   enumeration type, its declaration in the class definition can
9590     //   specify a constant-initializer which shall be an integral
9591     //   constant expression (5.19). In that case, the member can appear
9592     //   in integral constant expressions. The member shall still be
9593     //   defined in a namespace scope if it is used in the program and the
9594     //   namespace scope definition shall not contain an initializer.
9595     //
9596     // We already performed a redefinition check above, but for static
9597     // data members we also need to check whether there was an in-class
9598     // declaration with an initializer.
9599     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9600       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9601           << VDecl->getDeclName();
9602       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9603            diag::note_previous_initializer)
9604           << 0;
9605       return;
9606     }
9607 
9608     if (VDecl->hasLocalStorage())
9609       getCurFunction()->setHasBranchProtectedScope();
9610 
9611     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9612       VDecl->setInvalidDecl();
9613       return;
9614     }
9615   }
9616 
9617   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9618   // a kernel function cannot be initialized."
9619   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9620     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9621     VDecl->setInvalidDecl();
9622     return;
9623   }
9624 
9625   // Get the decls type and save a reference for later, since
9626   // CheckInitializerTypes may change it.
9627   QualType DclT = VDecl->getType(), SavT = DclT;
9628 
9629   // Expressions default to 'id' when we're in a debugger
9630   // and we are assigning it to a variable of Objective-C pointer type.
9631   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9632       Init->getType() == Context.UnknownAnyTy) {
9633     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9634     if (Result.isInvalid()) {
9635       VDecl->setInvalidDecl();
9636       return;
9637     }
9638     Init = Result.get();
9639   }
9640 
9641   // Perform the initialization.
9642   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9643   if (!VDecl->isInvalidDecl()) {
9644     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9645     InitializationKind Kind =
9646         DirectInit
9647             ? CXXDirectInit
9648                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9649                                                      Init->getLocStart(),
9650                                                      Init->getLocEnd())
9651                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9652             : InitializationKind::CreateCopy(VDecl->getLocation(),
9653                                              Init->getLocStart());
9654 
9655     MultiExprArg Args = Init;
9656     if (CXXDirectInit)
9657       Args = MultiExprArg(CXXDirectInit->getExprs(),
9658                           CXXDirectInit->getNumExprs());
9659 
9660     // Try to correct any TypoExprs in the initialization arguments.
9661     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9662       ExprResult Res = CorrectDelayedTyposInExpr(
9663           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9664             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9665             return Init.Failed() ? ExprError() : E;
9666           });
9667       if (Res.isInvalid()) {
9668         VDecl->setInvalidDecl();
9669       } else if (Res.get() != Args[Idx]) {
9670         Args[Idx] = Res.get();
9671       }
9672     }
9673     if (VDecl->isInvalidDecl())
9674       return;
9675 
9676     InitializationSequence InitSeq(*this, Entity, Kind, Args,
9677                                    /*TopLevelOfInitList=*/false,
9678                                    /*TreatUnavailableAsInvalid=*/false);
9679     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9680     if (Result.isInvalid()) {
9681       VDecl->setInvalidDecl();
9682       return;
9683     }
9684 
9685     Init = Result.getAs<Expr>();
9686   }
9687 
9688   // Check for self-references within variable initializers.
9689   // Variables declared within a function/method body (except for references)
9690   // are handled by a dataflow analysis.
9691   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9692       VDecl->getType()->isReferenceType()) {
9693     CheckSelfReference(*this, RealDecl, Init, DirectInit);
9694   }
9695 
9696   // If the type changed, it means we had an incomplete type that was
9697   // completed by the initializer. For example:
9698   //   int ary[] = { 1, 3, 5 };
9699   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9700   if (!VDecl->isInvalidDecl() && (DclT != SavT))
9701     VDecl->setType(DclT);
9702 
9703   if (!VDecl->isInvalidDecl()) {
9704     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9705 
9706     if (VDecl->hasAttr<BlocksAttr>())
9707       checkRetainCycles(VDecl, Init);
9708 
9709     // It is safe to assign a weak reference into a strong variable.
9710     // Although this code can still have problems:
9711     //   id x = self.weakProp;
9712     //   id y = self.weakProp;
9713     // we do not warn to warn spuriously when 'x' and 'y' are on separate
9714     // paths through the function. This should be revisited if
9715     // -Wrepeated-use-of-weak is made flow-sensitive.
9716     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9717         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9718                          Init->getLocStart()))
9719       getCurFunction()->markSafeWeakUse(Init);
9720   }
9721 
9722   // The initialization is usually a full-expression.
9723   //
9724   // FIXME: If this is a braced initialization of an aggregate, it is not
9725   // an expression, and each individual field initializer is a separate
9726   // full-expression. For instance, in:
9727   //
9728   //   struct Temp { ~Temp(); };
9729   //   struct S { S(Temp); };
9730   //   struct T { S a, b; } t = { Temp(), Temp() }
9731   //
9732   // we should destroy the first Temp before constructing the second.
9733   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9734                                           false,
9735                                           VDecl->isConstexpr());
9736   if (Result.isInvalid()) {
9737     VDecl->setInvalidDecl();
9738     return;
9739   }
9740   Init = Result.get();
9741 
9742   // Attach the initializer to the decl.
9743   VDecl->setInit(Init);
9744 
9745   if (VDecl->isLocalVarDecl()) {
9746     // C99 6.7.8p4: All the expressions in an initializer for an object that has
9747     // static storage duration shall be constant expressions or string literals.
9748     // C++ does not have this restriction.
9749     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9750       const Expr *Culprit;
9751       if (VDecl->getStorageClass() == SC_Static)
9752         CheckForConstantInitializer(Init, DclT);
9753       // C89 is stricter than C99 for non-static aggregate types.
9754       // C89 6.5.7p3: All the expressions [...] in an initializer list
9755       // for an object that has aggregate or union type shall be
9756       // constant expressions.
9757       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9758                isa<InitListExpr>(Init) &&
9759                !Init->isConstantInitializer(Context, false, &Culprit))
9760         Diag(Culprit->getExprLoc(),
9761              diag::ext_aggregate_init_not_constant)
9762           << Culprit->getSourceRange();
9763     }
9764   } else if (VDecl->isStaticDataMember() &&
9765              VDecl->getLexicalDeclContext()->isRecord()) {
9766     // This is an in-class initialization for a static data member, e.g.,
9767     //
9768     // struct S {
9769     //   static const int value = 17;
9770     // };
9771 
9772     // C++ [class.mem]p4:
9773     //   A member-declarator can contain a constant-initializer only
9774     //   if it declares a static member (9.4) of const integral or
9775     //   const enumeration type, see 9.4.2.
9776     //
9777     // C++11 [class.static.data]p3:
9778     //   If a non-volatile const static data member is of integral or
9779     //   enumeration type, its declaration in the class definition can
9780     //   specify a brace-or-equal-initializer in which every initalizer-clause
9781     //   that is an assignment-expression is a constant expression. A static
9782     //   data member of literal type can be declared in the class definition
9783     //   with the constexpr specifier; if so, its declaration shall specify a
9784     //   brace-or-equal-initializer in which every initializer-clause that is
9785     //   an assignment-expression is a constant expression.
9786 
9787     // Do nothing on dependent types.
9788     if (DclT->isDependentType()) {
9789 
9790     // Allow any 'static constexpr' members, whether or not they are of literal
9791     // type. We separately check that every constexpr variable is of literal
9792     // type.
9793     } else if (VDecl->isConstexpr()) {
9794 
9795     // Require constness.
9796     } else if (!DclT.isConstQualified()) {
9797       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9798         << Init->getSourceRange();
9799       VDecl->setInvalidDecl();
9800 
9801     // We allow integer constant expressions in all cases.
9802     } else if (DclT->isIntegralOrEnumerationType()) {
9803       // Check whether the expression is a constant expression.
9804       SourceLocation Loc;
9805       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9806         // In C++11, a non-constexpr const static data member with an
9807         // in-class initializer cannot be volatile.
9808         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9809       else if (Init->isValueDependent())
9810         ; // Nothing to check.
9811       else if (Init->isIntegerConstantExpr(Context, &Loc))
9812         ; // Ok, it's an ICE!
9813       else if (Init->isEvaluatable(Context)) {
9814         // If we can constant fold the initializer through heroics, accept it,
9815         // but report this as a use of an extension for -pedantic.
9816         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9817           << Init->getSourceRange();
9818       } else {
9819         // Otherwise, this is some crazy unknown case.  Report the issue at the
9820         // location provided by the isIntegerConstantExpr failed check.
9821         Diag(Loc, diag::err_in_class_initializer_non_constant)
9822           << Init->getSourceRange();
9823         VDecl->setInvalidDecl();
9824       }
9825 
9826     // We allow foldable floating-point constants as an extension.
9827     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9828       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9829       // it anyway and provide a fixit to add the 'constexpr'.
9830       if (getLangOpts().CPlusPlus11) {
9831         Diag(VDecl->getLocation(),
9832              diag::ext_in_class_initializer_float_type_cxx11)
9833             << DclT << Init->getSourceRange();
9834         Diag(VDecl->getLocStart(),
9835              diag::note_in_class_initializer_float_type_cxx11)
9836             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9837       } else {
9838         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9839           << DclT << Init->getSourceRange();
9840 
9841         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9842           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9843             << Init->getSourceRange();
9844           VDecl->setInvalidDecl();
9845         }
9846       }
9847 
9848     // Suggest adding 'constexpr' in C++11 for literal types.
9849     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9850       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9851         << DclT << Init->getSourceRange()
9852         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9853       VDecl->setConstexpr(true);
9854 
9855     } else {
9856       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9857         << DclT << Init->getSourceRange();
9858       VDecl->setInvalidDecl();
9859     }
9860   } else if (VDecl->isFileVarDecl()) {
9861     if (VDecl->getStorageClass() == SC_Extern &&
9862         (!getLangOpts().CPlusPlus ||
9863          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9864            VDecl->isExternC())) &&
9865         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9866       Diag(VDecl->getLocation(), diag::warn_extern_init);
9867 
9868     // C99 6.7.8p4. All file scoped initializers need to be constant.
9869     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9870       CheckForConstantInitializer(Init, DclT);
9871   }
9872 
9873   // We will represent direct-initialization similarly to copy-initialization:
9874   //    int x(1);  -as-> int x = 1;
9875   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9876   //
9877   // Clients that want to distinguish between the two forms, can check for
9878   // direct initializer using VarDecl::getInitStyle().
9879   // A major benefit is that clients that don't particularly care about which
9880   // exactly form was it (like the CodeGen) can handle both cases without
9881   // special case code.
9882 
9883   // C++ 8.5p11:
9884   // The form of initialization (using parentheses or '=') is generally
9885   // insignificant, but does matter when the entity being initialized has a
9886   // class type.
9887   if (CXXDirectInit) {
9888     assert(DirectInit && "Call-style initializer must be direct init.");
9889     VDecl->setInitStyle(VarDecl::CallInit);
9890   } else if (DirectInit) {
9891     // This must be list-initialization. No other way is direct-initialization.
9892     VDecl->setInitStyle(VarDecl::ListInit);
9893   }
9894 
9895   CheckCompleteVariableDeclaration(VDecl);
9896 }
9897 
9898 /// ActOnInitializerError - Given that there was an error parsing an
9899 /// initializer for the given declaration, try to return to some form
9900 /// of sanity.
9901 void Sema::ActOnInitializerError(Decl *D) {
9902   // Our main concern here is re-establishing invariants like "a
9903   // variable's type is either dependent or complete".
9904   if (!D || D->isInvalidDecl()) return;
9905 
9906   VarDecl *VD = dyn_cast<VarDecl>(D);
9907   if (!VD) return;
9908 
9909   // Auto types are meaningless if we can't make sense of the initializer.
9910   if (ParsingInitForAutoVars.count(D)) {
9911     D->setInvalidDecl();
9912     return;
9913   }
9914 
9915   QualType Ty = VD->getType();
9916   if (Ty->isDependentType()) return;
9917 
9918   // Require a complete type.
9919   if (RequireCompleteType(VD->getLocation(),
9920                           Context.getBaseElementType(Ty),
9921                           diag::err_typecheck_decl_incomplete_type)) {
9922     VD->setInvalidDecl();
9923     return;
9924   }
9925 
9926   // Require a non-abstract type.
9927   if (RequireNonAbstractType(VD->getLocation(), Ty,
9928                              diag::err_abstract_type_in_decl,
9929                              AbstractVariableType)) {
9930     VD->setInvalidDecl();
9931     return;
9932   }
9933 
9934   // Don't bother complaining about constructors or destructors,
9935   // though.
9936 }
9937 
9938 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9939                                   bool TypeMayContainAuto) {
9940   // If there is no declaration, there was an error parsing it. Just ignore it.
9941   if (!RealDecl)
9942     return;
9943 
9944   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9945     QualType Type = Var->getType();
9946 
9947     // C++11 [dcl.spec.auto]p3
9948     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9949       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9950         << Var->getDeclName() << Type;
9951       Var->setInvalidDecl();
9952       return;
9953     }
9954 
9955     // C++11 [class.static.data]p3: A static data member can be declared with
9956     // the constexpr specifier; if so, its declaration shall specify
9957     // a brace-or-equal-initializer.
9958     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9959     // the definition of a variable [...] or the declaration of a static data
9960     // member.
9961     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9962       if (Var->isStaticDataMember())
9963         Diag(Var->getLocation(),
9964              diag::err_constexpr_static_mem_var_requires_init)
9965           << Var->getDeclName();
9966       else
9967         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9968       Var->setInvalidDecl();
9969       return;
9970     }
9971 
9972     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
9973     // definition having the concept specifier is called a variable concept. A
9974     // concept definition refers to [...] a variable concept and its initializer.
9975     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
9976       if (VTD->isConcept()) {
9977         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
9978         Var->setInvalidDecl();
9979         return;
9980       }
9981     }
9982 
9983     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9984     // be initialized.
9985     if (!Var->isInvalidDecl() &&
9986         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9987         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9988       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9989       Var->setInvalidDecl();
9990       return;
9991     }
9992 
9993     switch (Var->isThisDeclarationADefinition()) {
9994     case VarDecl::Definition:
9995       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9996         break;
9997 
9998       // We have an out-of-line definition of a static data member
9999       // that has an in-class initializer, so we type-check this like
10000       // a declaration.
10001       //
10002       // Fall through
10003 
10004     case VarDecl::DeclarationOnly:
10005       // It's only a declaration.
10006 
10007       // Block scope. C99 6.7p7: If an identifier for an object is
10008       // declared with no linkage (C99 6.2.2p6), the type for the
10009       // object shall be complete.
10010       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10011           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10012           RequireCompleteType(Var->getLocation(), Type,
10013                               diag::err_typecheck_decl_incomplete_type))
10014         Var->setInvalidDecl();
10015 
10016       // Make sure that the type is not abstract.
10017       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10018           RequireNonAbstractType(Var->getLocation(), Type,
10019                                  diag::err_abstract_type_in_decl,
10020                                  AbstractVariableType))
10021         Var->setInvalidDecl();
10022       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10023           Var->getStorageClass() == SC_PrivateExtern) {
10024         Diag(Var->getLocation(), diag::warn_private_extern);
10025         Diag(Var->getLocation(), diag::note_private_extern);
10026       }
10027 
10028       return;
10029 
10030     case VarDecl::TentativeDefinition:
10031       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10032       // object that has file scope without an initializer, and without a
10033       // storage-class specifier or with the storage-class specifier "static",
10034       // constitutes a tentative definition. Note: A tentative definition with
10035       // external linkage is valid (C99 6.2.2p5).
10036       if (!Var->isInvalidDecl()) {
10037         if (const IncompleteArrayType *ArrayT
10038                                     = Context.getAsIncompleteArrayType(Type)) {
10039           if (RequireCompleteType(Var->getLocation(),
10040                                   ArrayT->getElementType(),
10041                                   diag::err_illegal_decl_array_incomplete_type))
10042             Var->setInvalidDecl();
10043         } else if (Var->getStorageClass() == SC_Static) {
10044           // C99 6.9.2p3: If the declaration of an identifier for an object is
10045           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10046           // declared type shall not be an incomplete type.
10047           // NOTE: code such as the following
10048           //     static struct s;
10049           //     struct s { int a; };
10050           // is accepted by gcc. Hence here we issue a warning instead of
10051           // an error and we do not invalidate the static declaration.
10052           // NOTE: to avoid multiple warnings, only check the first declaration.
10053           if (Var->isFirstDecl())
10054             RequireCompleteType(Var->getLocation(), Type,
10055                                 diag::ext_typecheck_decl_incomplete_type);
10056         }
10057       }
10058 
10059       // Record the tentative definition; we're done.
10060       if (!Var->isInvalidDecl())
10061         TentativeDefinitions.push_back(Var);
10062       return;
10063     }
10064 
10065     // Provide a specific diagnostic for uninitialized variable
10066     // definitions with incomplete array type.
10067     if (Type->isIncompleteArrayType()) {
10068       Diag(Var->getLocation(),
10069            diag::err_typecheck_incomplete_array_needs_initializer);
10070       Var->setInvalidDecl();
10071       return;
10072     }
10073 
10074     // Provide a specific diagnostic for uninitialized variable
10075     // definitions with reference type.
10076     if (Type->isReferenceType()) {
10077       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10078         << Var->getDeclName()
10079         << SourceRange(Var->getLocation(), Var->getLocation());
10080       Var->setInvalidDecl();
10081       return;
10082     }
10083 
10084     // Do not attempt to type-check the default initializer for a
10085     // variable with dependent type.
10086     if (Type->isDependentType())
10087       return;
10088 
10089     if (Var->isInvalidDecl())
10090       return;
10091 
10092     if (!Var->hasAttr<AliasAttr>()) {
10093       if (RequireCompleteType(Var->getLocation(),
10094                               Context.getBaseElementType(Type),
10095                               diag::err_typecheck_decl_incomplete_type)) {
10096         Var->setInvalidDecl();
10097         return;
10098       }
10099     } else {
10100       return;
10101     }
10102 
10103     // The variable can not have an abstract class type.
10104     if (RequireNonAbstractType(Var->getLocation(), Type,
10105                                diag::err_abstract_type_in_decl,
10106                                AbstractVariableType)) {
10107       Var->setInvalidDecl();
10108       return;
10109     }
10110 
10111     // Check for jumps past the implicit initializer.  C++0x
10112     // clarifies that this applies to a "variable with automatic
10113     // storage duration", not a "local variable".
10114     // C++11 [stmt.dcl]p3
10115     //   A program that jumps from a point where a variable with automatic
10116     //   storage duration is not in scope to a point where it is in scope is
10117     //   ill-formed unless the variable has scalar type, class type with a
10118     //   trivial default constructor and a trivial destructor, a cv-qualified
10119     //   version of one of these types, or an array of one of the preceding
10120     //   types and is declared without an initializer.
10121     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10122       if (const RecordType *Record
10123             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10124         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10125         // Mark the function for further checking even if the looser rules of
10126         // C++11 do not require such checks, so that we can diagnose
10127         // incompatibilities with C++98.
10128         if (!CXXRecord->isPOD())
10129           getCurFunction()->setHasBranchProtectedScope();
10130       }
10131     }
10132 
10133     // C++03 [dcl.init]p9:
10134     //   If no initializer is specified for an object, and the
10135     //   object is of (possibly cv-qualified) non-POD class type (or
10136     //   array thereof), the object shall be default-initialized; if
10137     //   the object is of const-qualified type, the underlying class
10138     //   type shall have a user-declared default
10139     //   constructor. Otherwise, if no initializer is specified for
10140     //   a non- static object, the object and its subobjects, if
10141     //   any, have an indeterminate initial value); if the object
10142     //   or any of its subobjects are of const-qualified type, the
10143     //   program is ill-formed.
10144     // C++0x [dcl.init]p11:
10145     //   If no initializer is specified for an object, the object is
10146     //   default-initialized; [...].
10147     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10148     InitializationKind Kind
10149       = InitializationKind::CreateDefault(Var->getLocation());
10150 
10151     InitializationSequence InitSeq(*this, Entity, Kind, None);
10152     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10153     if (Init.isInvalid())
10154       Var->setInvalidDecl();
10155     else if (Init.get()) {
10156       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10157       // This is important for template substitution.
10158       Var->setInitStyle(VarDecl::CallInit);
10159     }
10160 
10161     CheckCompleteVariableDeclaration(Var);
10162   }
10163 }
10164 
10165 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10166   // If there is no declaration, there was an error parsing it. Ignore it.
10167   if (!D)
10168     return;
10169 
10170   VarDecl *VD = dyn_cast<VarDecl>(D);
10171   if (!VD) {
10172     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10173     D->setInvalidDecl();
10174     return;
10175   }
10176 
10177   VD->setCXXForRangeDecl(true);
10178 
10179   // for-range-declaration cannot be given a storage class specifier.
10180   int Error = -1;
10181   switch (VD->getStorageClass()) {
10182   case SC_None:
10183     break;
10184   case SC_Extern:
10185     Error = 0;
10186     break;
10187   case SC_Static:
10188     Error = 1;
10189     break;
10190   case SC_PrivateExtern:
10191     Error = 2;
10192     break;
10193   case SC_Auto:
10194     Error = 3;
10195     break;
10196   case SC_Register:
10197     Error = 4;
10198     break;
10199   }
10200   if (Error != -1) {
10201     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10202       << VD->getDeclName() << Error;
10203     D->setInvalidDecl();
10204   }
10205 }
10206 
10207 StmtResult
10208 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10209                                  IdentifierInfo *Ident,
10210                                  ParsedAttributes &Attrs,
10211                                  SourceLocation AttrEnd) {
10212   // C++1y [stmt.iter]p1:
10213   //   A range-based for statement of the form
10214   //      for ( for-range-identifier : for-range-initializer ) statement
10215   //   is equivalent to
10216   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10217   DeclSpec DS(Attrs.getPool().getFactory());
10218 
10219   const char *PrevSpec;
10220   unsigned DiagID;
10221   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10222                      getPrintingPolicy());
10223 
10224   Declarator D(DS, Declarator::ForContext);
10225   D.SetIdentifier(Ident, IdentLoc);
10226   D.takeAttributes(Attrs, AttrEnd);
10227 
10228   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10229   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10230                 EmptyAttrs, IdentLoc);
10231   Decl *Var = ActOnDeclarator(S, D);
10232   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10233   FinalizeDeclaration(Var);
10234   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10235                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10236 }
10237 
10238 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10239   if (var->isInvalidDecl()) return;
10240 
10241   if (getLangOpts().OpenCL) {
10242     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10243     // initialiser
10244     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10245         !var->hasInit()) {
10246       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10247           << 1 /*Init*/;
10248       var->setInvalidDecl();
10249       return;
10250     }
10251   }
10252 
10253   // In Objective-C, don't allow jumps past the implicit initialization of a
10254   // local retaining variable.
10255   if (getLangOpts().ObjC1 &&
10256       var->hasLocalStorage()) {
10257     switch (var->getType().getObjCLifetime()) {
10258     case Qualifiers::OCL_None:
10259     case Qualifiers::OCL_ExplicitNone:
10260     case Qualifiers::OCL_Autoreleasing:
10261       break;
10262 
10263     case Qualifiers::OCL_Weak:
10264     case Qualifiers::OCL_Strong:
10265       getCurFunction()->setHasBranchProtectedScope();
10266       break;
10267     }
10268   }
10269 
10270   // Warn about externally-visible variables being defined without a
10271   // prior declaration.  We only want to do this for global
10272   // declarations, but we also specifically need to avoid doing it for
10273   // class members because the linkage of an anonymous class can
10274   // change if it's later given a typedef name.
10275   if (var->isThisDeclarationADefinition() &&
10276       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10277       var->isExternallyVisible() && var->hasLinkage() &&
10278       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10279                                   var->getLocation())) {
10280     // Find a previous declaration that's not a definition.
10281     VarDecl *prev = var->getPreviousDecl();
10282     while (prev && prev->isThisDeclarationADefinition())
10283       prev = prev->getPreviousDecl();
10284 
10285     if (!prev)
10286       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10287   }
10288 
10289   if (var->getTLSKind() == VarDecl::TLS_Static) {
10290     const Expr *Culprit;
10291     if (var->getType().isDestructedType()) {
10292       // GNU C++98 edits for __thread, [basic.start.term]p3:
10293       //   The type of an object with thread storage duration shall not
10294       //   have a non-trivial destructor.
10295       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10296       if (getLangOpts().CPlusPlus11)
10297         Diag(var->getLocation(), diag::note_use_thread_local);
10298     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
10299                !var->getInit()->isConstantInitializer(
10300                    Context, var->getType()->isReferenceType(), &Culprit)) {
10301       // GNU C++98 edits for __thread, [basic.start.init]p4:
10302       //   An object of thread storage duration shall not require dynamic
10303       //   initialization.
10304       // FIXME: Need strict checking here.
10305       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
10306         << Culprit->getSourceRange();
10307       if (getLangOpts().CPlusPlus11)
10308         Diag(var->getLocation(), diag::note_use_thread_local);
10309     }
10310   }
10311 
10312   // Apply section attributes and pragmas to global variables.
10313   bool GlobalStorage = var->hasGlobalStorage();
10314   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10315       ActiveTemplateInstantiations.empty()) {
10316     PragmaStack<StringLiteral *> *Stack = nullptr;
10317     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10318     if (var->getType().isConstQualified())
10319       Stack = &ConstSegStack;
10320     else if (!var->getInit()) {
10321       Stack = &BSSSegStack;
10322       SectionFlags |= ASTContext::PSF_Write;
10323     } else {
10324       Stack = &DataSegStack;
10325       SectionFlags |= ASTContext::PSF_Write;
10326     }
10327     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10328       var->addAttr(SectionAttr::CreateImplicit(
10329           Context, SectionAttr::Declspec_allocate,
10330           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10331     }
10332     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10333       if (UnifySection(SA->getName(), SectionFlags, var))
10334         var->dropAttr<SectionAttr>();
10335 
10336     // Apply the init_seg attribute if this has an initializer.  If the
10337     // initializer turns out to not be dynamic, we'll end up ignoring this
10338     // attribute.
10339     if (CurInitSeg && var->getInit())
10340       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10341                                                CurInitSegLoc));
10342   }
10343 
10344   // All the following checks are C++ only.
10345   if (!getLangOpts().CPlusPlus) return;
10346 
10347   QualType type = var->getType();
10348   if (type->isDependentType()) return;
10349 
10350   // __block variables might require us to capture a copy-initializer.
10351   if (var->hasAttr<BlocksAttr>()) {
10352     // It's currently invalid to ever have a __block variable with an
10353     // array type; should we diagnose that here?
10354 
10355     // Regardless, we don't want to ignore array nesting when
10356     // constructing this copy.
10357     if (type->isStructureOrClassType()) {
10358       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10359       SourceLocation poi = var->getLocation();
10360       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10361       ExprResult result
10362         = PerformMoveOrCopyInitialization(
10363             InitializedEntity::InitializeBlock(poi, type, false),
10364             var, var->getType(), varRef, /*AllowNRVO=*/true);
10365       if (!result.isInvalid()) {
10366         result = MaybeCreateExprWithCleanups(result);
10367         Expr *init = result.getAs<Expr>();
10368         Context.setBlockVarCopyInits(var, init);
10369       }
10370     }
10371   }
10372 
10373   Expr *Init = var->getInit();
10374   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10375   QualType baseType = Context.getBaseElementType(type);
10376 
10377   if (!var->getDeclContext()->isDependentContext() &&
10378       Init && !Init->isValueDependent()) {
10379     if (IsGlobal && !var->isConstexpr() &&
10380         !getDiagnostics().isIgnored(diag::warn_global_constructor,
10381                                     var->getLocation())) {
10382       // Warn about globals which don't have a constant initializer.  Don't
10383       // warn about globals with a non-trivial destructor because we already
10384       // warned about them.
10385       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10386       if (!(RD && !RD->hasTrivialDestructor()) &&
10387           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10388         Diag(var->getLocation(), diag::warn_global_constructor)
10389           << Init->getSourceRange();
10390     }
10391 
10392     if (var->isConstexpr()) {
10393       SmallVector<PartialDiagnosticAt, 8> Notes;
10394       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10395         SourceLocation DiagLoc = var->getLocation();
10396         // If the note doesn't add any useful information other than a source
10397         // location, fold it into the primary diagnostic.
10398         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10399               diag::note_invalid_subexpr_in_const_expr) {
10400           DiagLoc = Notes[0].first;
10401           Notes.clear();
10402         }
10403         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10404           << var << Init->getSourceRange();
10405         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10406           Diag(Notes[I].first, Notes[I].second);
10407       }
10408     } else if (var->isUsableInConstantExpressions(Context)) {
10409       // Check whether the initializer of a const variable of integral or
10410       // enumeration type is an ICE now, since we can't tell whether it was
10411       // initialized by a constant expression if we check later.
10412       var->checkInitIsICE();
10413     }
10414   }
10415 
10416   // Require the destructor.
10417   if (const RecordType *recordType = baseType->getAs<RecordType>())
10418     FinalizeVarWithDestructor(var, recordType);
10419 }
10420 
10421 /// \brief Determines if a variable's alignment is dependent.
10422 static bool hasDependentAlignment(VarDecl *VD) {
10423   if (VD->getType()->isDependentType())
10424     return true;
10425   for (auto *I : VD->specific_attrs<AlignedAttr>())
10426     if (I->isAlignmentDependent())
10427       return true;
10428   return false;
10429 }
10430 
10431 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10432 /// any semantic actions necessary after any initializer has been attached.
10433 void
10434 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10435   // Note that we are no longer parsing the initializer for this declaration.
10436   ParsingInitForAutoVars.erase(ThisDecl);
10437 
10438   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10439   if (!VD)
10440     return;
10441 
10442   checkAttributesAfterMerging(*this, *VD);
10443 
10444   // Perform TLS alignment check here after attributes attached to the variable
10445   // which may affect the alignment have been processed. Only perform the check
10446   // if the target has a maximum TLS alignment (zero means no constraints).
10447   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10448     // Protect the check so that it's not performed on dependent types and
10449     // dependent alignments (we can't determine the alignment in that case).
10450     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10451       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10452       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10453         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10454           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10455           << (unsigned)MaxAlignChars.getQuantity();
10456       }
10457     }
10458   }
10459 
10460   if (VD->isStaticLocal()) {
10461     if (FunctionDecl *FD =
10462             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10463       // Static locals inherit dll attributes from their function.
10464       if (Attr *A = getDLLAttr(FD)) {
10465         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10466         NewAttr->setInherited(true);
10467         VD->addAttr(NewAttr);
10468       }
10469       // CUDA E.2.9.4: Within the body of a __device__ or __global__
10470       // function, only __shared__ variables may be declared with
10471       // static storage class.
10472       if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
10473           (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>()) &&
10474           !VD->hasAttr<CUDASharedAttr>()) {
10475         Diag(VD->getLocation(), diag::err_device_static_local_var);
10476         VD->setInvalidDecl();
10477       }
10478     }
10479   }
10480 
10481   // Perform check for initializers of device-side global variables.
10482   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10483   // 7.5). We must also apply the same checks to all __shared__
10484   // variables whether they are local or not. CUDA also allows
10485   // constant initializers for __constant__ and __device__ variables.
10486   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
10487     const Expr *Init = VD->getInit();
10488     if (Init && VD->hasGlobalStorage() &&
10489         (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10490          VD->hasAttr<CUDASharedAttr>())) {
10491       assert((!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()));
10492       bool AllowedInit = false;
10493       if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10494         AllowedInit =
10495             isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10496       // We'll allow constant initializers even if it's a non-empty
10497       // constructor according to CUDA rules. This deviates from NVCC,
10498       // but allows us to handle things like constexpr constructors.
10499       if (!AllowedInit &&
10500           (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10501         AllowedInit = VD->getInit()->isConstantInitializer(
10502             Context, VD->getType()->isReferenceType());
10503 
10504       // Also make sure that destructor, if there is one, is empty.
10505       if (AllowedInit)
10506         if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
10507           AllowedInit =
10508               isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
10509 
10510       if (!AllowedInit) {
10511         Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10512                                     ? diag::err_shared_var_init
10513                                     : diag::err_dynamic_var_init)
10514             << Init->getSourceRange();
10515         VD->setInvalidDecl();
10516       }
10517     }
10518   }
10519 
10520   // Grab the dllimport or dllexport attribute off of the VarDecl.
10521   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10522 
10523   // Imported static data members cannot be defined out-of-line.
10524   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10525     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10526         VD->isThisDeclarationADefinition()) {
10527       // We allow definitions of dllimport class template static data members
10528       // with a warning.
10529       CXXRecordDecl *Context =
10530         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10531       bool IsClassTemplateMember =
10532           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10533           Context->getDescribedClassTemplate();
10534 
10535       Diag(VD->getLocation(),
10536            IsClassTemplateMember
10537                ? diag::warn_attribute_dllimport_static_field_definition
10538                : diag::err_attribute_dllimport_static_field_definition);
10539       Diag(IA->getLocation(), diag::note_attribute);
10540       if (!IsClassTemplateMember)
10541         VD->setInvalidDecl();
10542     }
10543   }
10544 
10545   // dllimport/dllexport variables cannot be thread local, their TLS index
10546   // isn't exported with the variable.
10547   if (DLLAttr && VD->getTLSKind()) {
10548     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10549     if (F && getDLLAttr(F)) {
10550       assert(VD->isStaticLocal());
10551       // But if this is a static local in a dlimport/dllexport function, the
10552       // function will never be inlined, which means the var would never be
10553       // imported, so having it marked import/export is safe.
10554     } else {
10555       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10556                                                                     << DLLAttr;
10557       VD->setInvalidDecl();
10558     }
10559   }
10560 
10561   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10562     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10563       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10564       VD->dropAttr<UsedAttr>();
10565     }
10566   }
10567 
10568   const DeclContext *DC = VD->getDeclContext();
10569   // If there's a #pragma GCC visibility in scope, and this isn't a class
10570   // member, set the visibility of this variable.
10571   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10572     AddPushedVisibilityAttribute(VD);
10573 
10574   // FIXME: Warn on unused templates.
10575   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10576       !isa<VarTemplatePartialSpecializationDecl>(VD))
10577     MarkUnusedFileScopedDecl(VD);
10578 
10579   // Now we have parsed the initializer and can update the table of magic
10580   // tag values.
10581   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10582       !VD->getType()->isIntegralOrEnumerationType())
10583     return;
10584 
10585   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10586     const Expr *MagicValueExpr = VD->getInit();
10587     if (!MagicValueExpr) {
10588       continue;
10589     }
10590     llvm::APSInt MagicValueInt;
10591     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10592       Diag(I->getRange().getBegin(),
10593            diag::err_type_tag_for_datatype_not_ice)
10594         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10595       continue;
10596     }
10597     if (MagicValueInt.getActiveBits() > 64) {
10598       Diag(I->getRange().getBegin(),
10599            diag::err_type_tag_for_datatype_too_large)
10600         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10601       continue;
10602     }
10603     uint64_t MagicValue = MagicValueInt.getZExtValue();
10604     RegisterTypeTagForDatatype(I->getArgumentKind(),
10605                                MagicValue,
10606                                I->getMatchingCType(),
10607                                I->getLayoutCompatible(),
10608                                I->getMustBeNull());
10609   }
10610 }
10611 
10612 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10613                                                    ArrayRef<Decl *> Group) {
10614   SmallVector<Decl*, 8> Decls;
10615 
10616   if (DS.isTypeSpecOwned())
10617     Decls.push_back(DS.getRepAsDecl());
10618 
10619   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10620   for (unsigned i = 0, e = Group.size(); i != e; ++i)
10621     if (Decl *D = Group[i]) {
10622       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10623         if (!FirstDeclaratorInGroup)
10624           FirstDeclaratorInGroup = DD;
10625       Decls.push_back(D);
10626     }
10627 
10628   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10629     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10630       handleTagNumbering(Tag, S);
10631       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10632           getLangOpts().CPlusPlus)
10633         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10634     }
10635   }
10636 
10637   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10638 }
10639 
10640 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10641 /// group, performing any necessary semantic checking.
10642 Sema::DeclGroupPtrTy
10643 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10644                            bool TypeMayContainAuto) {
10645   // C++0x [dcl.spec.auto]p7:
10646   //   If the type deduced for the template parameter U is not the same in each
10647   //   deduction, the program is ill-formed.
10648   // FIXME: When initializer-list support is added, a distinction is needed
10649   // between the deduced type U and the deduced type which 'auto' stands for.
10650   //   auto a = 0, b = { 1, 2, 3 };
10651   // is legal because the deduced type U is 'int' in both cases.
10652   if (TypeMayContainAuto && Group.size() > 1) {
10653     QualType Deduced;
10654     CanQualType DeducedCanon;
10655     VarDecl *DeducedDecl = nullptr;
10656     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10657       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10658         AutoType *AT = D->getType()->getContainedAutoType();
10659         // Don't reissue diagnostics when instantiating a template.
10660         if (AT && D->isInvalidDecl())
10661           break;
10662         QualType U = AT ? AT->getDeducedType() : QualType();
10663         if (!U.isNull()) {
10664           CanQualType UCanon = Context.getCanonicalType(U);
10665           if (Deduced.isNull()) {
10666             Deduced = U;
10667             DeducedCanon = UCanon;
10668             DeducedDecl = D;
10669           } else if (DeducedCanon != UCanon) {
10670             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10671                  diag::err_auto_different_deductions)
10672               << (unsigned)AT->getKeyword()
10673               << Deduced << DeducedDecl->getDeclName()
10674               << U << D->getDeclName()
10675               << DeducedDecl->getInit()->getSourceRange()
10676               << D->getInit()->getSourceRange();
10677             D->setInvalidDecl();
10678             break;
10679           }
10680         }
10681       }
10682     }
10683   }
10684 
10685   ActOnDocumentableDecls(Group);
10686 
10687   return DeclGroupPtrTy::make(
10688       DeclGroupRef::Create(Context, Group.data(), Group.size()));
10689 }
10690 
10691 void Sema::ActOnDocumentableDecl(Decl *D) {
10692   ActOnDocumentableDecls(D);
10693 }
10694 
10695 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10696   // Don't parse the comment if Doxygen diagnostics are ignored.
10697   if (Group.empty() || !Group[0])
10698     return;
10699 
10700   if (Diags.isIgnored(diag::warn_doc_param_not_found,
10701                       Group[0]->getLocation()) &&
10702       Diags.isIgnored(diag::warn_unknown_comment_command_name,
10703                       Group[0]->getLocation()))
10704     return;
10705 
10706   if (Group.size() >= 2) {
10707     // This is a decl group.  Normally it will contain only declarations
10708     // produced from declarator list.  But in case we have any definitions or
10709     // additional declaration references:
10710     //   'typedef struct S {} S;'
10711     //   'typedef struct S *S;'
10712     //   'struct S *pS;'
10713     // FinalizeDeclaratorGroup adds these as separate declarations.
10714     Decl *MaybeTagDecl = Group[0];
10715     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10716       Group = Group.slice(1);
10717     }
10718   }
10719 
10720   // See if there are any new comments that are not attached to a decl.
10721   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10722   if (!Comments.empty() &&
10723       !Comments.back()->isAttached()) {
10724     // There is at least one comment that not attached to a decl.
10725     // Maybe it should be attached to one of these decls?
10726     //
10727     // Note that this way we pick up not only comments that precede the
10728     // declaration, but also comments that *follow* the declaration -- thanks to
10729     // the lookahead in the lexer: we've consumed the semicolon and looked
10730     // ahead through comments.
10731     for (unsigned i = 0, e = Group.size(); i != e; ++i)
10732       Context.getCommentForDecl(Group[i], &PP);
10733   }
10734 }
10735 
10736 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10737 /// to introduce parameters into function prototype scope.
10738 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10739   const DeclSpec &DS = D.getDeclSpec();
10740 
10741   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10742 
10743   // C++03 [dcl.stc]p2 also permits 'auto'.
10744   StorageClass SC = SC_None;
10745   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10746     SC = SC_Register;
10747   } else if (getLangOpts().CPlusPlus &&
10748              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10749     SC = SC_Auto;
10750   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10751     Diag(DS.getStorageClassSpecLoc(),
10752          diag::err_invalid_storage_class_in_func_decl);
10753     D.getMutableDeclSpec().ClearStorageClassSpecs();
10754   }
10755 
10756   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10757     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10758       << DeclSpec::getSpecifierName(TSCS);
10759   if (DS.isConstexprSpecified())
10760     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10761       << 0;
10762   if (DS.isConceptSpecified())
10763     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10764 
10765   DiagnoseFunctionSpecifiers(DS);
10766 
10767   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10768   QualType parmDeclType = TInfo->getType();
10769 
10770   if (getLangOpts().CPlusPlus) {
10771     // Check that there are no default arguments inside the type of this
10772     // parameter.
10773     CheckExtraCXXDefaultArguments(D);
10774 
10775     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10776     if (D.getCXXScopeSpec().isSet()) {
10777       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10778         << D.getCXXScopeSpec().getRange();
10779       D.getCXXScopeSpec().clear();
10780     }
10781   }
10782 
10783   // Ensure we have a valid name
10784   IdentifierInfo *II = nullptr;
10785   if (D.hasName()) {
10786     II = D.getIdentifier();
10787     if (!II) {
10788       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10789         << GetNameForDeclarator(D).getName();
10790       D.setInvalidType(true);
10791     }
10792   }
10793 
10794   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10795   if (II) {
10796     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10797                    ForRedeclaration);
10798     LookupName(R, S);
10799     if (R.isSingleResult()) {
10800       NamedDecl *PrevDecl = R.getFoundDecl();
10801       if (PrevDecl->isTemplateParameter()) {
10802         // Maybe we will complain about the shadowed template parameter.
10803         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10804         // Just pretend that we didn't see the previous declaration.
10805         PrevDecl = nullptr;
10806       } else if (S->isDeclScope(PrevDecl)) {
10807         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10808         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10809 
10810         // Recover by removing the name
10811         II = nullptr;
10812         D.SetIdentifier(nullptr, D.getIdentifierLoc());
10813         D.setInvalidType(true);
10814       }
10815     }
10816   }
10817 
10818   // Temporarily put parameter variables in the translation unit, not
10819   // the enclosing context.  This prevents them from accidentally
10820   // looking like class members in C++.
10821   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10822                                     D.getLocStart(),
10823                                     D.getIdentifierLoc(), II,
10824                                     parmDeclType, TInfo,
10825                                     SC);
10826 
10827   if (D.isInvalidType())
10828     New->setInvalidDecl();
10829 
10830   assert(S->isFunctionPrototypeScope());
10831   assert(S->getFunctionPrototypeDepth() >= 1);
10832   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10833                     S->getNextFunctionPrototypeIndex());
10834 
10835   // Add the parameter declaration into this scope.
10836   S->AddDecl(New);
10837   if (II)
10838     IdResolver.AddDecl(New);
10839 
10840   ProcessDeclAttributes(S, New, D);
10841 
10842   if (D.getDeclSpec().isModulePrivateSpecified())
10843     Diag(New->getLocation(), diag::err_module_private_local)
10844       << 1 << New->getDeclName()
10845       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10846       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10847 
10848   if (New->hasAttr<BlocksAttr>()) {
10849     Diag(New->getLocation(), diag::err_block_on_nonlocal);
10850   }
10851   return New;
10852 }
10853 
10854 /// \brief Synthesizes a variable for a parameter arising from a
10855 /// typedef.
10856 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10857                                               SourceLocation Loc,
10858                                               QualType T) {
10859   /* FIXME: setting StartLoc == Loc.
10860      Would it be worth to modify callers so as to provide proper source
10861      location for the unnamed parameters, embedding the parameter's type? */
10862   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10863                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
10864                                            SC_None, nullptr);
10865   Param->setImplicit();
10866   return Param;
10867 }
10868 
10869 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
10870                                     ParmVarDecl * const *ParamEnd) {
10871   // Don't diagnose unused-parameter errors in template instantiations; we
10872   // will already have done so in the template itself.
10873   if (!ActiveTemplateInstantiations.empty())
10874     return;
10875 
10876   for (; Param != ParamEnd; ++Param) {
10877     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10878         !(*Param)->hasAttr<UnusedAttr>()) {
10879       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10880         << (*Param)->getDeclName();
10881     }
10882   }
10883 }
10884 
10885 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
10886                                                   ParmVarDecl * const *ParamEnd,
10887                                                   QualType ReturnTy,
10888                                                   NamedDecl *D) {
10889   if (LangOpts.NumLargeByValueCopy == 0) // No check.
10890     return;
10891 
10892   // Warn if the return value is pass-by-value and larger than the specified
10893   // threshold.
10894   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10895     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10896     if (Size > LangOpts.NumLargeByValueCopy)
10897       Diag(D->getLocation(), diag::warn_return_value_size)
10898           << D->getDeclName() << Size;
10899   }
10900 
10901   // Warn if any parameter is pass-by-value and larger than the specified
10902   // threshold.
10903   for (; Param != ParamEnd; ++Param) {
10904     QualType T = (*Param)->getType();
10905     if (T->isDependentType() || !T.isPODType(Context))
10906       continue;
10907     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10908     if (Size > LangOpts.NumLargeByValueCopy)
10909       Diag((*Param)->getLocation(), diag::warn_parameter_size)
10910           << (*Param)->getDeclName() << Size;
10911   }
10912 }
10913 
10914 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10915                                   SourceLocation NameLoc, IdentifierInfo *Name,
10916                                   QualType T, TypeSourceInfo *TSInfo,
10917                                   StorageClass SC) {
10918   // In ARC, infer a lifetime qualifier for appropriate parameter types.
10919   if (getLangOpts().ObjCAutoRefCount &&
10920       T.getObjCLifetime() == Qualifiers::OCL_None &&
10921       T->isObjCLifetimeType()) {
10922 
10923     Qualifiers::ObjCLifetime lifetime;
10924 
10925     // Special cases for arrays:
10926     //   - if it's const, use __unsafe_unretained
10927     //   - otherwise, it's an error
10928     if (T->isArrayType()) {
10929       if (!T.isConstQualified()) {
10930         DelayedDiagnostics.add(
10931             sema::DelayedDiagnostic::makeForbiddenType(
10932             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10933       }
10934       lifetime = Qualifiers::OCL_ExplicitNone;
10935     } else {
10936       lifetime = T->getObjCARCImplicitLifetime();
10937     }
10938     T = Context.getLifetimeQualifiedType(T, lifetime);
10939   }
10940 
10941   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10942                                          Context.getAdjustedParameterType(T),
10943                                          TSInfo, SC, nullptr);
10944 
10945   // Parameters can not be abstract class types.
10946   // For record types, this is done by the AbstractClassUsageDiagnoser once
10947   // the class has been completely parsed.
10948   if (!CurContext->isRecord() &&
10949       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10950                              AbstractParamType))
10951     New->setInvalidDecl();
10952 
10953   // Parameter declarators cannot be interface types. All ObjC objects are
10954   // passed by reference.
10955   if (T->isObjCObjectType()) {
10956     SourceLocation TypeEndLoc =
10957         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
10958     Diag(NameLoc,
10959          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10960       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10961     T = Context.getObjCObjectPointerType(T);
10962     New->setType(T);
10963   }
10964 
10965   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10966   // duration shall not be qualified by an address-space qualifier."
10967   // Since all parameters have automatic store duration, they can not have
10968   // an address space.
10969   if (T.getAddressSpace() != 0) {
10970     // OpenCL allows function arguments declared to be an array of a type
10971     // to be qualified with an address space.
10972     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10973       Diag(NameLoc, diag::err_arg_with_address_space);
10974       New->setInvalidDecl();
10975     }
10976   }
10977 
10978   // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
10979   // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
10980   if (getLangOpts().OpenCL && T->isPointerType()) {
10981     const QualType PTy = T->getPointeeType();
10982     if (PTy->isImageType() || PTy->isSamplerT() || PTy->isPipeType()) {
10983       Diag(NameLoc, diag::err_opencl_pointer_to_type) << PTy;
10984       New->setInvalidDecl();
10985     }
10986   }
10987 
10988   return New;
10989 }
10990 
10991 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10992                                            SourceLocation LocAfterDecls) {
10993   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10994 
10995   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10996   // for a K&R function.
10997   if (!FTI.hasPrototype) {
10998     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10999       --i;
11000       if (FTI.Params[i].Param == nullptr) {
11001         SmallString<256> Code;
11002         llvm::raw_svector_ostream(Code)
11003             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11004         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11005             << FTI.Params[i].Ident
11006             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11007 
11008         // Implicitly declare the argument as type 'int' for lack of a better
11009         // type.
11010         AttributeFactory attrs;
11011         DeclSpec DS(attrs);
11012         const char* PrevSpec; // unused
11013         unsigned DiagID; // unused
11014         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11015                            DiagID, Context.getPrintingPolicy());
11016         // Use the identifier location for the type source range.
11017         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11018         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11019         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11020         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11021         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11022       }
11023     }
11024   }
11025 }
11026 
11027 Decl *
11028 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11029                               MultiTemplateParamsArg TemplateParameterLists,
11030                               SkipBodyInfo *SkipBody) {
11031   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11032   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11033   Scope *ParentScope = FnBodyScope->getParent();
11034 
11035   D.setFunctionDefinitionKind(FDK_Definition);
11036   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11037   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11038 }
11039 
11040 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11041   Consumer.HandleInlineFunctionDefinition(D);
11042 }
11043 
11044 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11045                              const FunctionDecl*& PossibleZeroParamPrototype) {
11046   // Don't warn about invalid declarations.
11047   if (FD->isInvalidDecl())
11048     return false;
11049 
11050   // Or declarations that aren't global.
11051   if (!FD->isGlobal())
11052     return false;
11053 
11054   // Don't warn about C++ member functions.
11055   if (isa<CXXMethodDecl>(FD))
11056     return false;
11057 
11058   // Don't warn about 'main'.
11059   if (FD->isMain())
11060     return false;
11061 
11062   // Don't warn about inline functions.
11063   if (FD->isInlined())
11064     return false;
11065 
11066   // Don't warn about function templates.
11067   if (FD->getDescribedFunctionTemplate())
11068     return false;
11069 
11070   // Don't warn about function template specializations.
11071   if (FD->isFunctionTemplateSpecialization())
11072     return false;
11073 
11074   // Don't warn for OpenCL kernels.
11075   if (FD->hasAttr<OpenCLKernelAttr>())
11076     return false;
11077 
11078   // Don't warn on explicitly deleted functions.
11079   if (FD->isDeleted())
11080     return false;
11081 
11082   bool MissingPrototype = true;
11083   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11084        Prev; Prev = Prev->getPreviousDecl()) {
11085     // Ignore any declarations that occur in function or method
11086     // scope, because they aren't visible from the header.
11087     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11088       continue;
11089 
11090     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11091     if (FD->getNumParams() == 0)
11092       PossibleZeroParamPrototype = Prev;
11093     break;
11094   }
11095 
11096   return MissingPrototype;
11097 }
11098 
11099 void
11100 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11101                                    const FunctionDecl *EffectiveDefinition,
11102                                    SkipBodyInfo *SkipBody) {
11103   // Don't complain if we're in GNU89 mode and the previous definition
11104   // was an extern inline function.
11105   const FunctionDecl *Definition = EffectiveDefinition;
11106   if (!Definition)
11107     if (!FD->isDefined(Definition))
11108       return;
11109 
11110   if (canRedefineFunction(Definition, getLangOpts()))
11111     return;
11112 
11113   // If we don't have a visible definition of the function, and it's inline or
11114   // a template, skip the new definition.
11115   if (SkipBody && !hasVisibleDefinition(Definition) &&
11116       (Definition->getFormalLinkage() == InternalLinkage ||
11117        Definition->isInlined() ||
11118        Definition->getDescribedFunctionTemplate() ||
11119        Definition->getNumTemplateParameterLists())) {
11120     SkipBody->ShouldSkip = true;
11121     if (auto *TD = Definition->getDescribedFunctionTemplate())
11122       makeMergedDefinitionVisible(TD, FD->getLocation());
11123     else
11124       makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11125                                   FD->getLocation());
11126     return;
11127   }
11128 
11129   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11130       Definition->getStorageClass() == SC_Extern)
11131     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11132         << FD->getDeclName() << getLangOpts().CPlusPlus;
11133   else
11134     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11135 
11136   Diag(Definition->getLocation(), diag::note_previous_definition);
11137   FD->setInvalidDecl();
11138 }
11139 
11140 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11141                                    Sema &S) {
11142   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11143 
11144   LambdaScopeInfo *LSI = S.PushLambdaScope();
11145   LSI->CallOperator = CallOperator;
11146   LSI->Lambda = LambdaClass;
11147   LSI->ReturnType = CallOperator->getReturnType();
11148   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11149 
11150   if (LCD == LCD_None)
11151     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11152   else if (LCD == LCD_ByCopy)
11153     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11154   else if (LCD == LCD_ByRef)
11155     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11156   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11157 
11158   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11159   LSI->Mutable = !CallOperator->isConst();
11160 
11161   // Add the captures to the LSI so they can be noted as already
11162   // captured within tryCaptureVar.
11163   auto I = LambdaClass->field_begin();
11164   for (const auto &C : LambdaClass->captures()) {
11165     if (C.capturesVariable()) {
11166       VarDecl *VD = C.getCapturedVar();
11167       if (VD->isInitCapture())
11168         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11169       QualType CaptureType = VD->getType();
11170       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11171       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11172           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11173           /*EllipsisLoc*/C.isPackExpansion()
11174                          ? C.getEllipsisLoc() : SourceLocation(),
11175           CaptureType, /*Expr*/ nullptr);
11176 
11177     } else if (C.capturesThis()) {
11178       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11179                               /*Expr*/ nullptr,
11180                               C.getCaptureKind() == LCK_StarThis);
11181     } else {
11182       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11183     }
11184     ++I;
11185   }
11186 }
11187 
11188 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11189                                     SkipBodyInfo *SkipBody) {
11190   // Clear the last template instantiation error context.
11191   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11192 
11193   if (!D)
11194     return D;
11195   FunctionDecl *FD = nullptr;
11196 
11197   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11198     FD = FunTmpl->getTemplatedDecl();
11199   else
11200     FD = cast<FunctionDecl>(D);
11201 
11202   // See if this is a redefinition.
11203   if (!FD->isLateTemplateParsed()) {
11204     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11205 
11206     // If we're skipping the body, we're done. Don't enter the scope.
11207     if (SkipBody && SkipBody->ShouldSkip)
11208       return D;
11209   }
11210 
11211   // If we are instantiating a generic lambda call operator, push
11212   // a LambdaScopeInfo onto the function stack.  But use the information
11213   // that's already been calculated (ActOnLambdaExpr) to prime the current
11214   // LambdaScopeInfo.
11215   // When the template operator is being specialized, the LambdaScopeInfo,
11216   // has to be properly restored so that tryCaptureVariable doesn't try
11217   // and capture any new variables. In addition when calculating potential
11218   // captures during transformation of nested lambdas, it is necessary to
11219   // have the LSI properly restored.
11220   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11221     assert(ActiveTemplateInstantiations.size() &&
11222       "There should be an active template instantiation on the stack "
11223       "when instantiating a generic lambda!");
11224     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11225   }
11226   else
11227     // Enter a new function scope
11228     PushFunctionScope();
11229 
11230   // Builtin functions cannot be defined.
11231   if (unsigned BuiltinID = FD->getBuiltinID()) {
11232     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11233         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11234       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11235       FD->setInvalidDecl();
11236     }
11237   }
11238 
11239   // The return type of a function definition must be complete
11240   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11241   QualType ResultType = FD->getReturnType();
11242   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11243       !FD->isInvalidDecl() &&
11244       RequireCompleteType(FD->getLocation(), ResultType,
11245                           diag::err_func_def_incomplete_result))
11246     FD->setInvalidDecl();
11247 
11248   if (FnBodyScope)
11249     PushDeclContext(FnBodyScope, FD);
11250 
11251   // Check the validity of our function parameters
11252   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
11253                            /*CheckParameterNames=*/true);
11254 
11255   // Introduce our parameters into the function scope
11256   for (auto Param : FD->params()) {
11257     Param->setOwningFunction(FD);
11258 
11259     // If this has an identifier, add it to the scope stack.
11260     if (Param->getIdentifier() && FnBodyScope) {
11261       CheckShadow(FnBodyScope, Param);
11262 
11263       PushOnScopeChains(Param, FnBodyScope);
11264     }
11265   }
11266 
11267   // If we had any tags defined in the function prototype,
11268   // introduce them into the function scope.
11269   if (FnBodyScope) {
11270     for (ArrayRef<NamedDecl *>::iterator
11271              I = FD->getDeclsInPrototypeScope().begin(),
11272              E = FD->getDeclsInPrototypeScope().end();
11273          I != E; ++I) {
11274       NamedDecl *D = *I;
11275 
11276       // Some of these decls (like enums) may have been pinned to the
11277       // translation unit for lack of a real context earlier. If so, remove
11278       // from the translation unit and reattach to the current context.
11279       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
11280         // Is the decl actually in the context?
11281         if (Context.getTranslationUnitDecl()->containsDecl(D))
11282           Context.getTranslationUnitDecl()->removeDecl(D);
11283         // Either way, reassign the lexical decl context to our FunctionDecl.
11284         D->setLexicalDeclContext(CurContext);
11285       }
11286 
11287       // If the decl has a non-null name, make accessible in the current scope.
11288       if (!D->getName().empty())
11289         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
11290 
11291       // Similarly, dive into enums and fish their constants out, making them
11292       // accessible in this scope.
11293       if (auto *ED = dyn_cast<EnumDecl>(D)) {
11294         for (auto *EI : ED->enumerators())
11295           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11296       }
11297     }
11298   }
11299 
11300   // Ensure that the function's exception specification is instantiated.
11301   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11302     ResolveExceptionSpec(D->getLocation(), FPT);
11303 
11304   // dllimport cannot be applied to non-inline function definitions.
11305   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11306       !FD->isTemplateInstantiation()) {
11307     assert(!FD->hasAttr<DLLExportAttr>());
11308     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11309     FD->setInvalidDecl();
11310     return D;
11311   }
11312   // We want to attach documentation to original Decl (which might be
11313   // a function template).
11314   ActOnDocumentableDecl(D);
11315   if (getCurLexicalContext()->isObjCContainer() &&
11316       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11317       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11318     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11319 
11320   return D;
11321 }
11322 
11323 /// \brief Given the set of return statements within a function body,
11324 /// compute the variables that are subject to the named return value
11325 /// optimization.
11326 ///
11327 /// Each of the variables that is subject to the named return value
11328 /// optimization will be marked as NRVO variables in the AST, and any
11329 /// return statement that has a marked NRVO variable as its NRVO candidate can
11330 /// use the named return value optimization.
11331 ///
11332 /// This function applies a very simplistic algorithm for NRVO: if every return
11333 /// statement in the scope of a variable has the same NRVO candidate, that
11334 /// candidate is an NRVO variable.
11335 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11336   ReturnStmt **Returns = Scope->Returns.data();
11337 
11338   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11339     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11340       if (!NRVOCandidate->isNRVOVariable())
11341         Returns[I]->setNRVOCandidate(nullptr);
11342     }
11343   }
11344 }
11345 
11346 bool Sema::canDelayFunctionBody(const Declarator &D) {
11347   // We can't delay parsing the body of a constexpr function template (yet).
11348   if (D.getDeclSpec().isConstexprSpecified())
11349     return false;
11350 
11351   // We can't delay parsing the body of a function template with a deduced
11352   // return type (yet).
11353   if (D.getDeclSpec().containsPlaceholderType()) {
11354     // If the placeholder introduces a non-deduced trailing return type,
11355     // we can still delay parsing it.
11356     if (D.getNumTypeObjects()) {
11357       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11358       if (Outer.Kind == DeclaratorChunk::Function &&
11359           Outer.Fun.hasTrailingReturnType()) {
11360         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11361         return Ty.isNull() || !Ty->isUndeducedType();
11362       }
11363     }
11364     return false;
11365   }
11366 
11367   return true;
11368 }
11369 
11370 bool Sema::canSkipFunctionBody(Decl *D) {
11371   // We cannot skip the body of a function (or function template) which is
11372   // constexpr, since we may need to evaluate its body in order to parse the
11373   // rest of the file.
11374   // We cannot skip the body of a function with an undeduced return type,
11375   // because any callers of that function need to know the type.
11376   if (const FunctionDecl *FD = D->getAsFunction())
11377     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11378       return false;
11379   return Consumer.shouldSkipFunctionBody(D);
11380 }
11381 
11382 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11383   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11384     FD->setHasSkippedBody();
11385   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11386     MD->setHasSkippedBody();
11387   return Decl;
11388 }
11389 
11390 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11391   return ActOnFinishFunctionBody(D, BodyArg, false);
11392 }
11393 
11394 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11395                                     bool IsInstantiation) {
11396   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11397 
11398   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11399   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11400 
11401   if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
11402     CheckCompletedCoroutineBody(FD, Body);
11403 
11404   if (FD) {
11405     FD->setBody(Body);
11406 
11407     if (getLangOpts().CPlusPlus14) {
11408       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11409           FD->getReturnType()->isUndeducedType()) {
11410         // If the function has a deduced result type but contains no 'return'
11411         // statements, the result type as written must be exactly 'auto', and
11412         // the deduced result type is 'void'.
11413         if (!FD->getReturnType()->getAs<AutoType>()) {
11414           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11415               << FD->getReturnType();
11416           FD->setInvalidDecl();
11417         } else {
11418           // Substitute 'void' for the 'auto' in the type.
11419           TypeLoc ResultType = getReturnTypeLoc(FD);
11420           Context.adjustDeducedFunctionResultType(
11421               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11422         }
11423       }
11424     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11425       // In C++11, we don't use 'auto' deduction rules for lambda call
11426       // operators because we don't support return type deduction.
11427       auto *LSI = getCurLambda();
11428       if (LSI->HasImplicitReturnType) {
11429         deduceClosureReturnType(*LSI);
11430 
11431         // C++11 [expr.prim.lambda]p4:
11432         //   [...] if there are no return statements in the compound-statement
11433         //   [the deduced type is] the type void
11434         QualType RetType =
11435             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11436 
11437         // Update the return type to the deduced type.
11438         const FunctionProtoType *Proto =
11439             FD->getType()->getAs<FunctionProtoType>();
11440         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11441                                             Proto->getExtProtoInfo()));
11442       }
11443     }
11444 
11445     // The only way to be included in UndefinedButUsed is if there is an
11446     // ODR use before the definition. Avoid the expensive map lookup if this
11447     // is the first declaration.
11448     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11449       if (!FD->isExternallyVisible())
11450         UndefinedButUsed.erase(FD);
11451       else if (FD->isInlined() &&
11452                !LangOpts.GNUInline &&
11453                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11454         UndefinedButUsed.erase(FD);
11455     }
11456 
11457     // If the function implicitly returns zero (like 'main') or is naked,
11458     // don't complain about missing return statements.
11459     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11460       WP.disableCheckFallThrough();
11461 
11462     // MSVC permits the use of pure specifier (=0) on function definition,
11463     // defined at class scope, warn about this non-standard construct.
11464     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11465       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11466 
11467     if (!FD->isInvalidDecl()) {
11468       // Don't diagnose unused parameters of defaulted or deleted functions.
11469       if (!FD->isDeleted() && !FD->isDefaulted())
11470         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
11471       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
11472                                              FD->getReturnType(), FD);
11473 
11474       // If this is a structor, we need a vtable.
11475       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11476         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11477       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11478         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11479 
11480       // Try to apply the named return value optimization. We have to check
11481       // if we can do this here because lambdas keep return statements around
11482       // to deduce an implicit return type.
11483       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11484           !FD->isDependentContext())
11485         computeNRVO(Body, getCurFunction());
11486     }
11487 
11488     // GNU warning -Wmissing-prototypes:
11489     //   Warn if a global function is defined without a previous
11490     //   prototype declaration. This warning is issued even if the
11491     //   definition itself provides a prototype. The aim is to detect
11492     //   global functions that fail to be declared in header files.
11493     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11494     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11495       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11496 
11497       if (PossibleZeroParamPrototype) {
11498         // We found a declaration that is not a prototype,
11499         // but that could be a zero-parameter prototype
11500         if (TypeSourceInfo *TI =
11501                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11502           TypeLoc TL = TI->getTypeLoc();
11503           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11504             Diag(PossibleZeroParamPrototype->getLocation(),
11505                  diag::note_declaration_not_a_prototype)
11506                 << PossibleZeroParamPrototype
11507                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11508         }
11509       }
11510     }
11511 
11512     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11513       const CXXMethodDecl *KeyFunction;
11514       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11515           MD->isVirtual() &&
11516           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11517           MD == KeyFunction->getCanonicalDecl()) {
11518         // Update the key-function state if necessary for this ABI.
11519         if (FD->isInlined() &&
11520             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11521           Context.setNonKeyFunction(MD);
11522 
11523           // If the newly-chosen key function is already defined, then we
11524           // need to mark the vtable as used retroactively.
11525           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11526           const FunctionDecl *Definition;
11527           if (KeyFunction && KeyFunction->isDefined(Definition))
11528             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11529         } else {
11530           // We just defined they key function; mark the vtable as used.
11531           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11532         }
11533       }
11534     }
11535 
11536     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11537            "Function parsing confused");
11538   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11539     assert(MD == getCurMethodDecl() && "Method parsing confused");
11540     MD->setBody(Body);
11541     if (!MD->isInvalidDecl()) {
11542       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
11543       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
11544                                              MD->getReturnType(), MD);
11545 
11546       if (Body)
11547         computeNRVO(Body, getCurFunction());
11548     }
11549     if (getCurFunction()->ObjCShouldCallSuper) {
11550       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11551         << MD->getSelector().getAsString();
11552       getCurFunction()->ObjCShouldCallSuper = false;
11553     }
11554     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11555       const ObjCMethodDecl *InitMethod = nullptr;
11556       bool isDesignated =
11557           MD->isDesignatedInitializerForTheInterface(&InitMethod);
11558       assert(isDesignated && InitMethod);
11559       (void)isDesignated;
11560 
11561       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11562         auto IFace = MD->getClassInterface();
11563         if (!IFace)
11564           return false;
11565         auto SuperD = IFace->getSuperClass();
11566         if (!SuperD)
11567           return false;
11568         return SuperD->getIdentifier() ==
11569             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11570       };
11571       // Don't issue this warning for unavailable inits or direct subclasses
11572       // of NSObject.
11573       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11574         Diag(MD->getLocation(),
11575              diag::warn_objc_designated_init_missing_super_call);
11576         Diag(InitMethod->getLocation(),
11577              diag::note_objc_designated_init_marked_here);
11578       }
11579       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11580     }
11581     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11582       // Don't issue this warning for unavaialable inits.
11583       if (!MD->isUnavailable())
11584         Diag(MD->getLocation(),
11585              diag::warn_objc_secondary_init_missing_init_call);
11586       getCurFunction()->ObjCWarnForNoInitDelegation = false;
11587     }
11588   } else {
11589     return nullptr;
11590   }
11591 
11592   assert(!getCurFunction()->ObjCShouldCallSuper &&
11593          "This should only be set for ObjC methods, which should have been "
11594          "handled in the block above.");
11595 
11596   // Verify and clean out per-function state.
11597   if (Body && (!FD || !FD->isDefaulted())) {
11598     // C++ constructors that have function-try-blocks can't have return
11599     // statements in the handlers of that block. (C++ [except.handle]p14)
11600     // Verify this.
11601     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11602       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11603 
11604     // Verify that gotos and switch cases don't jump into scopes illegally.
11605     if (getCurFunction()->NeedsScopeChecking() &&
11606         !PP.isCodeCompletionEnabled())
11607       DiagnoseInvalidJumps(Body);
11608 
11609     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11610       if (!Destructor->getParent()->isDependentType())
11611         CheckDestructor(Destructor);
11612 
11613       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11614                                              Destructor->getParent());
11615     }
11616 
11617     // If any errors have occurred, clear out any temporaries that may have
11618     // been leftover. This ensures that these temporaries won't be picked up for
11619     // deletion in some later function.
11620     if (getDiagnostics().hasErrorOccurred() ||
11621         getDiagnostics().getSuppressAllDiagnostics()) {
11622       DiscardCleanupsInEvaluationContext();
11623     }
11624     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11625         !isa<FunctionTemplateDecl>(dcl)) {
11626       // Since the body is valid, issue any analysis-based warnings that are
11627       // enabled.
11628       ActivePolicy = &WP;
11629     }
11630 
11631     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11632         (!CheckConstexprFunctionDecl(FD) ||
11633          !CheckConstexprFunctionBody(FD, Body)))
11634       FD->setInvalidDecl();
11635 
11636     if (FD && FD->hasAttr<NakedAttr>()) {
11637       for (const Stmt *S : Body->children()) {
11638         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11639           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11640           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11641           FD->setInvalidDecl();
11642           break;
11643         }
11644       }
11645     }
11646 
11647     assert(ExprCleanupObjects.size() ==
11648                ExprEvalContexts.back().NumCleanupObjects &&
11649            "Leftover temporaries in function");
11650     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
11651     assert(MaybeODRUseExprs.empty() &&
11652            "Leftover expressions for odr-use checking");
11653   }
11654 
11655   if (!IsInstantiation)
11656     PopDeclContext();
11657 
11658   PopFunctionScopeInfo(ActivePolicy, dcl);
11659   // If any errors have occurred, clear out any temporaries that may have
11660   // been leftover. This ensures that these temporaries won't be picked up for
11661   // deletion in some later function.
11662   if (getDiagnostics().hasErrorOccurred()) {
11663     DiscardCleanupsInEvaluationContext();
11664   }
11665 
11666   return dcl;
11667 }
11668 
11669 /// When we finish delayed parsing of an attribute, we must attach it to the
11670 /// relevant Decl.
11671 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11672                                        ParsedAttributes &Attrs) {
11673   // Always attach attributes to the underlying decl.
11674   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11675     D = TD->getTemplatedDecl();
11676   ProcessDeclAttributeList(S, D, Attrs.getList());
11677 
11678   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11679     if (Method->isStatic())
11680       checkThisInStaticMemberFunctionAttributes(Method);
11681 }
11682 
11683 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11684 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11685 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11686                                           IdentifierInfo &II, Scope *S) {
11687   // Before we produce a declaration for an implicitly defined
11688   // function, see whether there was a locally-scoped declaration of
11689   // this name as a function or variable. If so, use that
11690   // (non-visible) declaration, and complain about it.
11691   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11692     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11693     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11694     return ExternCPrev;
11695   }
11696 
11697   // Extension in C99.  Legal in C90, but warn about it.
11698   unsigned diag_id;
11699   if (II.getName().startswith("__builtin_"))
11700     diag_id = diag::warn_builtin_unknown;
11701   else if (getLangOpts().C99)
11702     diag_id = diag::ext_implicit_function_decl;
11703   else
11704     diag_id = diag::warn_implicit_function_decl;
11705   Diag(Loc, diag_id) << &II;
11706 
11707   // Because typo correction is expensive, only do it if the implicit
11708   // function declaration is going to be treated as an error.
11709   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11710     TypoCorrection Corrected;
11711     if (S &&
11712         (Corrected = CorrectTypo(
11713              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11714              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11715       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11716                    /*ErrorRecovery*/false);
11717   }
11718 
11719   // Set a Declarator for the implicit definition: int foo();
11720   const char *Dummy;
11721   AttributeFactory attrFactory;
11722   DeclSpec DS(attrFactory);
11723   unsigned DiagID;
11724   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11725                                   Context.getPrintingPolicy());
11726   (void)Error; // Silence warning.
11727   assert(!Error && "Error setting up implicit decl!");
11728   SourceLocation NoLoc;
11729   Declarator D(DS, Declarator::BlockContext);
11730   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11731                                              /*IsAmbiguous=*/false,
11732                                              /*LParenLoc=*/NoLoc,
11733                                              /*Params=*/nullptr,
11734                                              /*NumParams=*/0,
11735                                              /*EllipsisLoc=*/NoLoc,
11736                                              /*RParenLoc=*/NoLoc,
11737                                              /*TypeQuals=*/0,
11738                                              /*RefQualifierIsLvalueRef=*/true,
11739                                              /*RefQualifierLoc=*/NoLoc,
11740                                              /*ConstQualifierLoc=*/NoLoc,
11741                                              /*VolatileQualifierLoc=*/NoLoc,
11742                                              /*RestrictQualifierLoc=*/NoLoc,
11743                                              /*MutableLoc=*/NoLoc,
11744                                              EST_None,
11745                                              /*ESpecRange=*/SourceRange(),
11746                                              /*Exceptions=*/nullptr,
11747                                              /*ExceptionRanges=*/nullptr,
11748                                              /*NumExceptions=*/0,
11749                                              /*NoexceptExpr=*/nullptr,
11750                                              /*ExceptionSpecTokens=*/nullptr,
11751                                              Loc, Loc, D),
11752                 DS.getAttributes(),
11753                 SourceLocation());
11754   D.SetIdentifier(&II, Loc);
11755 
11756   // Insert this function into translation-unit scope.
11757 
11758   DeclContext *PrevDC = CurContext;
11759   CurContext = Context.getTranslationUnitDecl();
11760 
11761   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11762   FD->setImplicit();
11763 
11764   CurContext = PrevDC;
11765 
11766   AddKnownFunctionAttributes(FD);
11767 
11768   return FD;
11769 }
11770 
11771 /// \brief Adds any function attributes that we know a priori based on
11772 /// the declaration of this function.
11773 ///
11774 /// These attributes can apply both to implicitly-declared builtins
11775 /// (like __builtin___printf_chk) or to library-declared functions
11776 /// like NSLog or printf.
11777 ///
11778 /// We need to check for duplicate attributes both here and where user-written
11779 /// attributes are applied to declarations.
11780 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11781   if (FD->isInvalidDecl())
11782     return;
11783 
11784   // If this is a built-in function, map its builtin attributes to
11785   // actual attributes.
11786   if (unsigned BuiltinID = FD->getBuiltinID()) {
11787     // Handle printf-formatting attributes.
11788     unsigned FormatIdx;
11789     bool HasVAListArg;
11790     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11791       if (!FD->hasAttr<FormatAttr>()) {
11792         const char *fmt = "printf";
11793         unsigned int NumParams = FD->getNumParams();
11794         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11795             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11796           fmt = "NSString";
11797         FD->addAttr(FormatAttr::CreateImplicit(Context,
11798                                                &Context.Idents.get(fmt),
11799                                                FormatIdx+1,
11800                                                HasVAListArg ? 0 : FormatIdx+2,
11801                                                FD->getLocation()));
11802       }
11803     }
11804     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11805                                              HasVAListArg)) {
11806      if (!FD->hasAttr<FormatAttr>())
11807        FD->addAttr(FormatAttr::CreateImplicit(Context,
11808                                               &Context.Idents.get("scanf"),
11809                                               FormatIdx+1,
11810                                               HasVAListArg ? 0 : FormatIdx+2,
11811                                               FD->getLocation()));
11812     }
11813 
11814     // Mark const if we don't care about errno and that is the only
11815     // thing preventing the function from being const. This allows
11816     // IRgen to use LLVM intrinsics for such functions.
11817     if (!getLangOpts().MathErrno &&
11818         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11819       if (!FD->hasAttr<ConstAttr>())
11820         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11821     }
11822 
11823     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11824         !FD->hasAttr<ReturnsTwiceAttr>())
11825       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11826                                          FD->getLocation()));
11827     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11828       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11829     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
11830       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
11831     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11832       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11833     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11834         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11835       // Add the appropriate attribute, depending on the CUDA compilation mode
11836       // and which target the builtin belongs to. For example, during host
11837       // compilation, aux builtins are __device__, while the rest are __host__.
11838       if (getLangOpts().CUDAIsDevice !=
11839           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11840         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11841       else
11842         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11843     }
11844   }
11845 
11846   // If C++ exceptions are enabled but we are told extern "C" functions cannot
11847   // throw, add an implicit nothrow attribute to any extern "C" function we come
11848   // across.
11849   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
11850       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
11851     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
11852     if (!FPT || FPT->getExceptionSpecType() == EST_None)
11853       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11854   }
11855 
11856   IdentifierInfo *Name = FD->getIdentifier();
11857   if (!Name)
11858     return;
11859   if ((!getLangOpts().CPlusPlus &&
11860        FD->getDeclContext()->isTranslationUnit()) ||
11861       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11862        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11863        LinkageSpecDecl::lang_c)) {
11864     // Okay: this could be a libc/libm/Objective-C function we know
11865     // about.
11866   } else
11867     return;
11868 
11869   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11870     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11871     // target-specific builtins, perhaps?
11872     if (!FD->hasAttr<FormatAttr>())
11873       FD->addAttr(FormatAttr::CreateImplicit(Context,
11874                                              &Context.Idents.get("printf"), 2,
11875                                              Name->isStr("vasprintf") ? 0 : 3,
11876                                              FD->getLocation()));
11877   }
11878 
11879   if (Name->isStr("__CFStringMakeConstantString")) {
11880     // We already have a __builtin___CFStringMakeConstantString,
11881     // but builds that use -fno-constant-cfstrings don't go through that.
11882     if (!FD->hasAttr<FormatArgAttr>())
11883       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11884                                                 FD->getLocation()));
11885   }
11886 }
11887 
11888 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11889                                     TypeSourceInfo *TInfo) {
11890   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11891   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11892 
11893   if (!TInfo) {
11894     assert(D.isInvalidType() && "no declarator info for valid type");
11895     TInfo = Context.getTrivialTypeSourceInfo(T);
11896   }
11897 
11898   // Scope manipulation handled by caller.
11899   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11900                                            D.getLocStart(),
11901                                            D.getIdentifierLoc(),
11902                                            D.getIdentifier(),
11903                                            TInfo);
11904 
11905   // Bail out immediately if we have an invalid declaration.
11906   if (D.isInvalidType()) {
11907     NewTD->setInvalidDecl();
11908     return NewTD;
11909   }
11910 
11911   if (D.getDeclSpec().isModulePrivateSpecified()) {
11912     if (CurContext->isFunctionOrMethod())
11913       Diag(NewTD->getLocation(), diag::err_module_private_local)
11914         << 2 << NewTD->getDeclName()
11915         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11916         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11917     else
11918       NewTD->setModulePrivate();
11919   }
11920 
11921   // C++ [dcl.typedef]p8:
11922   //   If the typedef declaration defines an unnamed class (or
11923   //   enum), the first typedef-name declared by the declaration
11924   //   to be that class type (or enum type) is used to denote the
11925   //   class type (or enum type) for linkage purposes only.
11926   // We need to check whether the type was declared in the declaration.
11927   switch (D.getDeclSpec().getTypeSpecType()) {
11928   case TST_enum:
11929   case TST_struct:
11930   case TST_interface:
11931   case TST_union:
11932   case TST_class: {
11933     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11934     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11935     break;
11936   }
11937 
11938   default:
11939     break;
11940   }
11941 
11942   return NewTD;
11943 }
11944 
11945 /// \brief Check that this is a valid underlying type for an enum declaration.
11946 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11947   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11948   QualType T = TI->getType();
11949 
11950   if (T->isDependentType())
11951     return false;
11952 
11953   if (const BuiltinType *BT = T->getAs<BuiltinType>())
11954     if (BT->isInteger())
11955       return false;
11956 
11957   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11958   return true;
11959 }
11960 
11961 /// Check whether this is a valid redeclaration of a previous enumeration.
11962 /// \return true if the redeclaration was invalid.
11963 bool Sema::CheckEnumRedeclaration(
11964     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
11965     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
11966   bool IsFixed = !EnumUnderlyingTy.isNull();
11967 
11968   if (IsScoped != Prev->isScoped()) {
11969     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11970       << Prev->isScoped();
11971     Diag(Prev->getLocation(), diag::note_previous_declaration);
11972     return true;
11973   }
11974 
11975   if (IsFixed && Prev->isFixed()) {
11976     if (!EnumUnderlyingTy->isDependentType() &&
11977         !Prev->getIntegerType()->isDependentType() &&
11978         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11979                                         Prev->getIntegerType())) {
11980       // TODO: Highlight the underlying type of the redeclaration.
11981       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11982         << EnumUnderlyingTy << Prev->getIntegerType();
11983       Diag(Prev->getLocation(), diag::note_previous_declaration)
11984           << Prev->getIntegerTypeRange();
11985       return true;
11986     }
11987   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
11988     ;
11989   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
11990     ;
11991   } else if (IsFixed != Prev->isFixed()) {
11992     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11993       << Prev->isFixed();
11994     Diag(Prev->getLocation(), diag::note_previous_declaration);
11995     return true;
11996   }
11997 
11998   return false;
11999 }
12000 
12001 /// \brief Get diagnostic %select index for tag kind for
12002 /// redeclaration diagnostic message.
12003 /// WARNING: Indexes apply to particular diagnostics only!
12004 ///
12005 /// \returns diagnostic %select index.
12006 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12007   switch (Tag) {
12008   case TTK_Struct: return 0;
12009   case TTK_Interface: return 1;
12010   case TTK_Class:  return 2;
12011   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12012   }
12013 }
12014 
12015 /// \brief Determine if tag kind is a class-key compatible with
12016 /// class for redeclaration (class, struct, or __interface).
12017 ///
12018 /// \returns true iff the tag kind is compatible.
12019 static bool isClassCompatTagKind(TagTypeKind Tag)
12020 {
12021   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12022 }
12023 
12024 /// \brief Determine whether a tag with a given kind is acceptable
12025 /// as a redeclaration of the given tag declaration.
12026 ///
12027 /// \returns true if the new tag kind is acceptable, false otherwise.
12028 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12029                                         TagTypeKind NewTag, bool isDefinition,
12030                                         SourceLocation NewTagLoc,
12031                                         const IdentifierInfo *Name) {
12032   // C++ [dcl.type.elab]p3:
12033   //   The class-key or enum keyword present in the
12034   //   elaborated-type-specifier shall agree in kind with the
12035   //   declaration to which the name in the elaborated-type-specifier
12036   //   refers. This rule also applies to the form of
12037   //   elaborated-type-specifier that declares a class-name or
12038   //   friend class since it can be construed as referring to the
12039   //   definition of the class. Thus, in any
12040   //   elaborated-type-specifier, the enum keyword shall be used to
12041   //   refer to an enumeration (7.2), the union class-key shall be
12042   //   used to refer to a union (clause 9), and either the class or
12043   //   struct class-key shall be used to refer to a class (clause 9)
12044   //   declared using the class or struct class-key.
12045   TagTypeKind OldTag = Previous->getTagKind();
12046   if (!isDefinition || !isClassCompatTagKind(NewTag))
12047     if (OldTag == NewTag)
12048       return true;
12049 
12050   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12051     // Warn about the struct/class tag mismatch.
12052     bool isTemplate = false;
12053     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12054       isTemplate = Record->getDescribedClassTemplate();
12055 
12056     if (!ActiveTemplateInstantiations.empty()) {
12057       // In a template instantiation, do not offer fix-its for tag mismatches
12058       // since they usually mess up the template instead of fixing the problem.
12059       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12060         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12061         << getRedeclDiagFromTagKind(OldTag);
12062       return true;
12063     }
12064 
12065     if (isDefinition) {
12066       // On definitions, check previous tags and issue a fix-it for each
12067       // one that doesn't match the current tag.
12068       if (Previous->getDefinition()) {
12069         // Don't suggest fix-its for redefinitions.
12070         return true;
12071       }
12072 
12073       bool previousMismatch = false;
12074       for (auto I : Previous->redecls()) {
12075         if (I->getTagKind() != NewTag) {
12076           if (!previousMismatch) {
12077             previousMismatch = true;
12078             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12079               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12080               << getRedeclDiagFromTagKind(I->getTagKind());
12081           }
12082           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12083             << getRedeclDiagFromTagKind(NewTag)
12084             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12085                  TypeWithKeyword::getTagTypeKindName(NewTag));
12086         }
12087       }
12088       return true;
12089     }
12090 
12091     // Check for a previous definition.  If current tag and definition
12092     // are same type, do nothing.  If no definition, but disagree with
12093     // with previous tag type, give a warning, but no fix-it.
12094     const TagDecl *Redecl = Previous->getDefinition() ?
12095                             Previous->getDefinition() : Previous;
12096     if (Redecl->getTagKind() == NewTag) {
12097       return true;
12098     }
12099 
12100     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12101       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12102       << getRedeclDiagFromTagKind(OldTag);
12103     Diag(Redecl->getLocation(), diag::note_previous_use);
12104 
12105     // If there is a previous definition, suggest a fix-it.
12106     if (Previous->getDefinition()) {
12107         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12108           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12109           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12110                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12111     }
12112 
12113     return true;
12114   }
12115   return false;
12116 }
12117 
12118 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12119 /// from an outer enclosing namespace or file scope inside a friend declaration.
12120 /// This should provide the commented out code in the following snippet:
12121 ///   namespace N {
12122 ///     struct X;
12123 ///     namespace M {
12124 ///       struct Y { friend struct /*N::*/ X; };
12125 ///     }
12126 ///   }
12127 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12128                                          SourceLocation NameLoc) {
12129   // While the decl is in a namespace, do repeated lookup of that name and see
12130   // if we get the same namespace back.  If we do not, continue until
12131   // translation unit scope, at which point we have a fully qualified NNS.
12132   SmallVector<IdentifierInfo *, 4> Namespaces;
12133   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12134   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12135     // This tag should be declared in a namespace, which can only be enclosed by
12136     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12137     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12138     if (!Namespace || Namespace->isAnonymousNamespace())
12139       return FixItHint();
12140     IdentifierInfo *II = Namespace->getIdentifier();
12141     Namespaces.push_back(II);
12142     NamedDecl *Lookup = SemaRef.LookupSingleName(
12143         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12144     if (Lookup == Namespace)
12145       break;
12146   }
12147 
12148   // Once we have all the namespaces, reverse them to go outermost first, and
12149   // build an NNS.
12150   SmallString<64> Insertion;
12151   llvm::raw_svector_ostream OS(Insertion);
12152   if (DC->isTranslationUnit())
12153     OS << "::";
12154   std::reverse(Namespaces.begin(), Namespaces.end());
12155   for (auto *II : Namespaces)
12156     OS << II->getName() << "::";
12157   return FixItHint::CreateInsertion(NameLoc, Insertion);
12158 }
12159 
12160 /// \brief Determine whether a tag originally declared in context \p OldDC can
12161 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12162 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12163 /// using-declaration).
12164 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12165                                          DeclContext *NewDC) {
12166   OldDC = OldDC->getRedeclContext();
12167   NewDC = NewDC->getRedeclContext();
12168 
12169   if (OldDC->Equals(NewDC))
12170     return true;
12171 
12172   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12173   // encloses the other).
12174   if (S.getLangOpts().MSVCCompat &&
12175       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12176     return true;
12177 
12178   return false;
12179 }
12180 
12181 /// Find the DeclContext in which a tag is implicitly declared if we see an
12182 /// elaborated type specifier in the specified context, and lookup finds
12183 /// nothing.
12184 static DeclContext *getTagInjectionContext(DeclContext *DC) {
12185   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
12186     DC = DC->getParent();
12187   return DC;
12188 }
12189 
12190 /// Find the Scope in which a tag is implicitly declared if we see an
12191 /// elaborated type specifier in the specified context, and lookup finds
12192 /// nothing.
12193 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
12194   while (S->isClassScope() ||
12195          (LangOpts.CPlusPlus &&
12196           S->isFunctionPrototypeScope()) ||
12197          ((S->getFlags() & Scope::DeclScope) == 0) ||
12198          (S->getEntity() && S->getEntity()->isTransparentContext()))
12199     S = S->getParent();
12200   return S;
12201 }
12202 
12203 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12204 /// former case, Name will be non-null.  In the later case, Name will be null.
12205 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12206 /// reference/declaration/definition of a tag.
12207 ///
12208 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12209 /// trailing-type-specifier) other than one in an alias-declaration.
12210 ///
12211 /// \param SkipBody If non-null, will be set to indicate if the caller should
12212 /// skip the definition of this tag and treat it as if it were a declaration.
12213 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12214                      SourceLocation KWLoc, CXXScopeSpec &SS,
12215                      IdentifierInfo *Name, SourceLocation NameLoc,
12216                      AttributeList *Attr, AccessSpecifier AS,
12217                      SourceLocation ModulePrivateLoc,
12218                      MultiTemplateParamsArg TemplateParameterLists,
12219                      bool &OwnedDecl, bool &IsDependent,
12220                      SourceLocation ScopedEnumKWLoc,
12221                      bool ScopedEnumUsesClassTag,
12222                      TypeResult UnderlyingType,
12223                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12224   // If this is not a definition, it must have a name.
12225   IdentifierInfo *OrigName = Name;
12226   assert((Name != nullptr || TUK == TUK_Definition) &&
12227          "Nameless record must be a definition!");
12228   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12229 
12230   OwnedDecl = false;
12231   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12232   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12233 
12234   // FIXME: Check explicit specializations more carefully.
12235   bool isExplicitSpecialization = false;
12236   bool Invalid = false;
12237 
12238   // We only need to do this matching if we have template parameters
12239   // or a scope specifier, which also conveniently avoids this work
12240   // for non-C++ cases.
12241   if (TemplateParameterLists.size() > 0 ||
12242       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12243     if (TemplateParameterList *TemplateParams =
12244             MatchTemplateParametersToScopeSpecifier(
12245                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12246                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12247       if (Kind == TTK_Enum) {
12248         Diag(KWLoc, diag::err_enum_template);
12249         return nullptr;
12250       }
12251 
12252       if (TemplateParams->size() > 0) {
12253         // This is a declaration or definition of a class template (which may
12254         // be a member of another template).
12255 
12256         if (Invalid)
12257           return nullptr;
12258 
12259         OwnedDecl = false;
12260         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12261                                                SS, Name, NameLoc, Attr,
12262                                                TemplateParams, AS,
12263                                                ModulePrivateLoc,
12264                                                /*FriendLoc*/SourceLocation(),
12265                                                TemplateParameterLists.size()-1,
12266                                                TemplateParameterLists.data(),
12267                                                SkipBody);
12268         return Result.get();
12269       } else {
12270         // The "template<>" header is extraneous.
12271         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12272           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12273         isExplicitSpecialization = true;
12274       }
12275     }
12276   }
12277 
12278   // Figure out the underlying type if this a enum declaration. We need to do
12279   // this early, because it's needed to detect if this is an incompatible
12280   // redeclaration.
12281   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12282   bool EnumUnderlyingIsImplicit = false;
12283 
12284   if (Kind == TTK_Enum) {
12285     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12286       // No underlying type explicitly specified, or we failed to parse the
12287       // type, default to int.
12288       EnumUnderlying = Context.IntTy.getTypePtr();
12289     else if (UnderlyingType.get()) {
12290       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12291       // integral type; any cv-qualification is ignored.
12292       TypeSourceInfo *TI = nullptr;
12293       GetTypeFromParser(UnderlyingType.get(), &TI);
12294       EnumUnderlying = TI;
12295 
12296       if (CheckEnumUnderlyingType(TI))
12297         // Recover by falling back to int.
12298         EnumUnderlying = Context.IntTy.getTypePtr();
12299 
12300       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12301                                           UPPC_FixedUnderlyingType))
12302         EnumUnderlying = Context.IntTy.getTypePtr();
12303 
12304     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12305       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12306         // Microsoft enums are always of int type.
12307         EnumUnderlying = Context.IntTy.getTypePtr();
12308         EnumUnderlyingIsImplicit = true;
12309       }
12310     }
12311   }
12312 
12313   DeclContext *SearchDC = CurContext;
12314   DeclContext *DC = CurContext;
12315   bool isStdBadAlloc = false;
12316 
12317   RedeclarationKind Redecl = ForRedeclaration;
12318   if (TUK == TUK_Friend || TUK == TUK_Reference)
12319     Redecl = NotForRedeclaration;
12320 
12321   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12322   if (Name && SS.isNotEmpty()) {
12323     // We have a nested-name tag ('struct foo::bar').
12324 
12325     // Check for invalid 'foo::'.
12326     if (SS.isInvalid()) {
12327       Name = nullptr;
12328       goto CreateNewDecl;
12329     }
12330 
12331     // If this is a friend or a reference to a class in a dependent
12332     // context, don't try to make a decl for it.
12333     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12334       DC = computeDeclContext(SS, false);
12335       if (!DC) {
12336         IsDependent = true;
12337         return nullptr;
12338       }
12339     } else {
12340       DC = computeDeclContext(SS, true);
12341       if (!DC) {
12342         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12343           << SS.getRange();
12344         return nullptr;
12345       }
12346     }
12347 
12348     if (RequireCompleteDeclContext(SS, DC))
12349       return nullptr;
12350 
12351     SearchDC = DC;
12352     // Look-up name inside 'foo::'.
12353     LookupQualifiedName(Previous, DC);
12354 
12355     if (Previous.isAmbiguous())
12356       return nullptr;
12357 
12358     if (Previous.empty()) {
12359       // Name lookup did not find anything. However, if the
12360       // nested-name-specifier refers to the current instantiation,
12361       // and that current instantiation has any dependent base
12362       // classes, we might find something at instantiation time: treat
12363       // this as a dependent elaborated-type-specifier.
12364       // But this only makes any sense for reference-like lookups.
12365       if (Previous.wasNotFoundInCurrentInstantiation() &&
12366           (TUK == TUK_Reference || TUK == TUK_Friend)) {
12367         IsDependent = true;
12368         return nullptr;
12369       }
12370 
12371       // A tag 'foo::bar' must already exist.
12372       Diag(NameLoc, diag::err_not_tag_in_scope)
12373         << Kind << Name << DC << SS.getRange();
12374       Name = nullptr;
12375       Invalid = true;
12376       goto CreateNewDecl;
12377     }
12378   } else if (Name) {
12379     // C++14 [class.mem]p14:
12380     //   If T is the name of a class, then each of the following shall have a
12381     //   name different from T:
12382     //    -- every member of class T that is itself a type
12383     if (TUK != TUK_Reference && TUK != TUK_Friend &&
12384         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12385       return nullptr;
12386 
12387     // If this is a named struct, check to see if there was a previous forward
12388     // declaration or definition.
12389     // FIXME: We're looking into outer scopes here, even when we
12390     // shouldn't be. Doing so can result in ambiguities that we
12391     // shouldn't be diagnosing.
12392     LookupName(Previous, S);
12393 
12394     // When declaring or defining a tag, ignore ambiguities introduced
12395     // by types using'ed into this scope.
12396     if (Previous.isAmbiguous() &&
12397         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12398       LookupResult::Filter F = Previous.makeFilter();
12399       while (F.hasNext()) {
12400         NamedDecl *ND = F.next();
12401         if (!ND->getDeclContext()->getRedeclContext()->Equals(
12402                 SearchDC->getRedeclContext()))
12403           F.erase();
12404       }
12405       F.done();
12406     }
12407 
12408     // C++11 [namespace.memdef]p3:
12409     //   If the name in a friend declaration is neither qualified nor
12410     //   a template-id and the declaration is a function or an
12411     //   elaborated-type-specifier, the lookup to determine whether
12412     //   the entity has been previously declared shall not consider
12413     //   any scopes outside the innermost enclosing namespace.
12414     //
12415     // MSVC doesn't implement the above rule for types, so a friend tag
12416     // declaration may be a redeclaration of a type declared in an enclosing
12417     // scope.  They do implement this rule for friend functions.
12418     //
12419     // Does it matter that this should be by scope instead of by
12420     // semantic context?
12421     if (!Previous.empty() && TUK == TUK_Friend) {
12422       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12423       LookupResult::Filter F = Previous.makeFilter();
12424       bool FriendSawTagOutsideEnclosingNamespace = false;
12425       while (F.hasNext()) {
12426         NamedDecl *ND = F.next();
12427         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12428         if (DC->isFileContext() &&
12429             !EnclosingNS->Encloses(ND->getDeclContext())) {
12430           if (getLangOpts().MSVCCompat)
12431             FriendSawTagOutsideEnclosingNamespace = true;
12432           else
12433             F.erase();
12434         }
12435       }
12436       F.done();
12437 
12438       // Diagnose this MSVC extension in the easy case where lookup would have
12439       // unambiguously found something outside the enclosing namespace.
12440       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12441         NamedDecl *ND = Previous.getFoundDecl();
12442         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12443             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12444       }
12445     }
12446 
12447     // Note:  there used to be some attempt at recovery here.
12448     if (Previous.isAmbiguous())
12449       return nullptr;
12450 
12451     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12452       // FIXME: This makes sure that we ignore the contexts associated
12453       // with C structs, unions, and enums when looking for a matching
12454       // tag declaration or definition. See the similar lookup tweak
12455       // in Sema::LookupName; is there a better way to deal with this?
12456       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12457         SearchDC = SearchDC->getParent();
12458     }
12459   }
12460 
12461   if (Previous.isSingleResult() &&
12462       Previous.getFoundDecl()->isTemplateParameter()) {
12463     // Maybe we will complain about the shadowed template parameter.
12464     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12465     // Just pretend that we didn't see the previous declaration.
12466     Previous.clear();
12467   }
12468 
12469   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12470       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12471     // This is a declaration of or a reference to "std::bad_alloc".
12472     isStdBadAlloc = true;
12473 
12474     if (Previous.empty() && StdBadAlloc) {
12475       // std::bad_alloc has been implicitly declared (but made invisible to
12476       // name lookup). Fill in this implicit declaration as the previous
12477       // declaration, so that the declarations get chained appropriately.
12478       Previous.addDecl(getStdBadAlloc());
12479     }
12480   }
12481 
12482   // If we didn't find a previous declaration, and this is a reference
12483   // (or friend reference), move to the correct scope.  In C++, we
12484   // also need to do a redeclaration lookup there, just in case
12485   // there's a shadow friend decl.
12486   if (Name && Previous.empty() &&
12487       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12488     if (Invalid) goto CreateNewDecl;
12489     assert(SS.isEmpty());
12490 
12491     if (TUK == TUK_Reference) {
12492       // C++ [basic.scope.pdecl]p5:
12493       //   -- for an elaborated-type-specifier of the form
12494       //
12495       //          class-key identifier
12496       //
12497       //      if the elaborated-type-specifier is used in the
12498       //      decl-specifier-seq or parameter-declaration-clause of a
12499       //      function defined in namespace scope, the identifier is
12500       //      declared as a class-name in the namespace that contains
12501       //      the declaration; otherwise, except as a friend
12502       //      declaration, the identifier is declared in the smallest
12503       //      non-class, non-function-prototype scope that contains the
12504       //      declaration.
12505       //
12506       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12507       // C structs and unions.
12508       //
12509       // It is an error in C++ to declare (rather than define) an enum
12510       // type, including via an elaborated type specifier.  We'll
12511       // diagnose that later; for now, declare the enum in the same
12512       // scope as we would have picked for any other tag type.
12513       //
12514       // GNU C also supports this behavior as part of its incomplete
12515       // enum types extension, while GNU C++ does not.
12516       //
12517       // Find the context where we'll be declaring the tag.
12518       // FIXME: We would like to maintain the current DeclContext as the
12519       // lexical context,
12520       SearchDC = getTagInjectionContext(SearchDC);
12521 
12522       // Find the scope where we'll be declaring the tag.
12523       S = getTagInjectionScope(S, getLangOpts());
12524     } else {
12525       assert(TUK == TUK_Friend);
12526       // C++ [namespace.memdef]p3:
12527       //   If a friend declaration in a non-local class first declares a
12528       //   class or function, the friend class or function is a member of
12529       //   the innermost enclosing namespace.
12530       SearchDC = SearchDC->getEnclosingNamespaceContext();
12531     }
12532 
12533     // In C++, we need to do a redeclaration lookup to properly
12534     // diagnose some problems.
12535     // FIXME: redeclaration lookup is also used (with and without C++) to find a
12536     // hidden declaration so that we don't get ambiguity errors when using a
12537     // type declared by an elaborated-type-specifier.  In C that is not correct
12538     // and we should instead merge compatible types found by lookup.
12539     if (getLangOpts().CPlusPlus) {
12540       Previous.setRedeclarationKind(ForRedeclaration);
12541       LookupQualifiedName(Previous, SearchDC);
12542     } else {
12543       Previous.setRedeclarationKind(ForRedeclaration);
12544       LookupName(Previous, S);
12545     }
12546   }
12547 
12548   // If we have a known previous declaration to use, then use it.
12549   if (Previous.empty() && SkipBody && SkipBody->Previous)
12550     Previous.addDecl(SkipBody->Previous);
12551 
12552   if (!Previous.empty()) {
12553     NamedDecl *PrevDecl = Previous.getFoundDecl();
12554     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12555 
12556     // It's okay to have a tag decl in the same scope as a typedef
12557     // which hides a tag decl in the same scope.  Finding this
12558     // insanity with a redeclaration lookup can only actually happen
12559     // in C++.
12560     //
12561     // This is also okay for elaborated-type-specifiers, which is
12562     // technically forbidden by the current standard but which is
12563     // okay according to the likely resolution of an open issue;
12564     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12565     if (getLangOpts().CPlusPlus) {
12566       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12567         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12568           TagDecl *Tag = TT->getDecl();
12569           if (Tag->getDeclName() == Name &&
12570               Tag->getDeclContext()->getRedeclContext()
12571                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
12572             PrevDecl = Tag;
12573             Previous.clear();
12574             Previous.addDecl(Tag);
12575             Previous.resolveKind();
12576           }
12577         }
12578       }
12579     }
12580 
12581     // If this is a redeclaration of a using shadow declaration, it must
12582     // declare a tag in the same context. In MSVC mode, we allow a
12583     // redefinition if either context is within the other.
12584     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12585       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12586       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12587           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12588           !(OldTag && isAcceptableTagRedeclContext(
12589                           *this, OldTag->getDeclContext(), SearchDC))) {
12590         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12591         Diag(Shadow->getTargetDecl()->getLocation(),
12592              diag::note_using_decl_target);
12593         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12594             << 0;
12595         // Recover by ignoring the old declaration.
12596         Previous.clear();
12597         goto CreateNewDecl;
12598       }
12599     }
12600 
12601     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12602       // If this is a use of a previous tag, or if the tag is already declared
12603       // in the same scope (so that the definition/declaration completes or
12604       // rementions the tag), reuse the decl.
12605       if (TUK == TUK_Reference || TUK == TUK_Friend ||
12606           isDeclInScope(DirectPrevDecl, SearchDC, S,
12607                         SS.isNotEmpty() || isExplicitSpecialization)) {
12608         // Make sure that this wasn't declared as an enum and now used as a
12609         // struct or something similar.
12610         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12611                                           TUK == TUK_Definition, KWLoc,
12612                                           Name)) {
12613           bool SafeToContinue
12614             = (PrevTagDecl->getTagKind() != TTK_Enum &&
12615                Kind != TTK_Enum);
12616           if (SafeToContinue)
12617             Diag(KWLoc, diag::err_use_with_wrong_tag)
12618               << Name
12619               << FixItHint::CreateReplacement(SourceRange(KWLoc),
12620                                               PrevTagDecl->getKindName());
12621           else
12622             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12623           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12624 
12625           if (SafeToContinue)
12626             Kind = PrevTagDecl->getTagKind();
12627           else {
12628             // Recover by making this an anonymous redefinition.
12629             Name = nullptr;
12630             Previous.clear();
12631             Invalid = true;
12632           }
12633         }
12634 
12635         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12636           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12637 
12638           // If this is an elaborated-type-specifier for a scoped enumeration,
12639           // the 'class' keyword is not necessary and not permitted.
12640           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12641             if (ScopedEnum)
12642               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12643                 << PrevEnum->isScoped()
12644                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12645             return PrevTagDecl;
12646           }
12647 
12648           QualType EnumUnderlyingTy;
12649           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12650             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12651           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12652             EnumUnderlyingTy = QualType(T, 0);
12653 
12654           // All conflicts with previous declarations are recovered by
12655           // returning the previous declaration, unless this is a definition,
12656           // in which case we want the caller to bail out.
12657           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12658                                      ScopedEnum, EnumUnderlyingTy,
12659                                      EnumUnderlyingIsImplicit, PrevEnum))
12660             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12661         }
12662 
12663         // C++11 [class.mem]p1:
12664         //   A member shall not be declared twice in the member-specification,
12665         //   except that a nested class or member class template can be declared
12666         //   and then later defined.
12667         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12668             S->isDeclScope(PrevDecl)) {
12669           Diag(NameLoc, diag::ext_member_redeclared);
12670           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12671         }
12672 
12673         if (!Invalid) {
12674           // If this is a use, just return the declaration we found, unless
12675           // we have attributes.
12676           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12677             if (Attr) {
12678               // FIXME: Diagnose these attributes. For now, we create a new
12679               // declaration to hold them.
12680             } else if (TUK == TUK_Reference &&
12681                        (PrevTagDecl->getFriendObjectKind() ==
12682                             Decl::FOK_Undeclared ||
12683                         PP.getModuleContainingLocation(
12684                             PrevDecl->getLocation()) !=
12685                             PP.getModuleContainingLocation(KWLoc)) &&
12686                        SS.isEmpty()) {
12687               // This declaration is a reference to an existing entity, but
12688               // has different visibility from that entity: it either makes
12689               // a friend visible or it makes a type visible in a new module.
12690               // In either case, create a new declaration. We only do this if
12691               // the declaration would have meant the same thing if no prior
12692               // declaration were found, that is, if it was found in the same
12693               // scope where we would have injected a declaration.
12694               if (!getTagInjectionContext(CurContext)->getRedeclContext()
12695                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
12696                 return PrevTagDecl;
12697               // This is in the injected scope, create a new declaration in
12698               // that scope.
12699               S = getTagInjectionScope(S, getLangOpts());
12700             } else {
12701               return PrevTagDecl;
12702             }
12703           }
12704 
12705           // Diagnose attempts to redefine a tag.
12706           if (TUK == TUK_Definition) {
12707             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12708               // If we're defining a specialization and the previous definition
12709               // is from an implicit instantiation, don't emit an error
12710               // here; we'll catch this in the general case below.
12711               bool IsExplicitSpecializationAfterInstantiation = false;
12712               if (isExplicitSpecialization) {
12713                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12714                   IsExplicitSpecializationAfterInstantiation =
12715                     RD->getTemplateSpecializationKind() !=
12716                     TSK_ExplicitSpecialization;
12717                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12718                   IsExplicitSpecializationAfterInstantiation =
12719                     ED->getTemplateSpecializationKind() !=
12720                     TSK_ExplicitSpecialization;
12721               }
12722 
12723               NamedDecl *Hidden = nullptr;
12724               if (SkipBody && getLangOpts().CPlusPlus &&
12725                   !hasVisibleDefinition(Def, &Hidden)) {
12726                 // There is a definition of this tag, but it is not visible. We
12727                 // explicitly make use of C++'s one definition rule here, and
12728                 // assume that this definition is identical to the hidden one
12729                 // we already have. Make the existing definition visible and
12730                 // use it in place of this one.
12731                 SkipBody->ShouldSkip = true;
12732                 makeMergedDefinitionVisible(Hidden, KWLoc);
12733                 return Def;
12734               } else if (!IsExplicitSpecializationAfterInstantiation) {
12735                 // A redeclaration in function prototype scope in C isn't
12736                 // visible elsewhere, so merely issue a warning.
12737                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12738                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12739                 else
12740                   Diag(NameLoc, diag::err_redefinition) << Name;
12741                 Diag(Def->getLocation(), diag::note_previous_definition);
12742                 // If this is a redefinition, recover by making this
12743                 // struct be anonymous, which will make any later
12744                 // references get the previous definition.
12745                 Name = nullptr;
12746                 Previous.clear();
12747                 Invalid = true;
12748               }
12749             } else {
12750               // If the type is currently being defined, complain
12751               // about a nested redefinition.
12752               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12753               if (TD->isBeingDefined()) {
12754                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12755                 Diag(PrevTagDecl->getLocation(),
12756                      diag::note_previous_definition);
12757                 Name = nullptr;
12758                 Previous.clear();
12759                 Invalid = true;
12760               }
12761             }
12762 
12763             // Okay, this is definition of a previously declared or referenced
12764             // tag. We're going to create a new Decl for it.
12765           }
12766 
12767           // Okay, we're going to make a redeclaration.  If this is some kind
12768           // of reference, make sure we build the redeclaration in the same DC
12769           // as the original, and ignore the current access specifier.
12770           if (TUK == TUK_Friend || TUK == TUK_Reference) {
12771             SearchDC = PrevTagDecl->getDeclContext();
12772             AS = AS_none;
12773           }
12774         }
12775         // If we get here we have (another) forward declaration or we
12776         // have a definition.  Just create a new decl.
12777 
12778       } else {
12779         // If we get here, this is a definition of a new tag type in a nested
12780         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12781         // new decl/type.  We set PrevDecl to NULL so that the entities
12782         // have distinct types.
12783         Previous.clear();
12784       }
12785       // If we get here, we're going to create a new Decl. If PrevDecl
12786       // is non-NULL, it's a definition of the tag declared by
12787       // PrevDecl. If it's NULL, we have a new definition.
12788 
12789     // Otherwise, PrevDecl is not a tag, but was found with tag
12790     // lookup.  This is only actually possible in C++, where a few
12791     // things like templates still live in the tag namespace.
12792     } else {
12793       // Use a better diagnostic if an elaborated-type-specifier
12794       // found the wrong kind of type on the first
12795       // (non-redeclaration) lookup.
12796       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12797           !Previous.isForRedeclaration()) {
12798         unsigned Kind = 0;
12799         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12800         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12801         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12802         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12803         Diag(PrevDecl->getLocation(), diag::note_declared_at);
12804         Invalid = true;
12805 
12806       // Otherwise, only diagnose if the declaration is in scope.
12807       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12808                                 SS.isNotEmpty() || isExplicitSpecialization)) {
12809         // do nothing
12810 
12811       // Diagnose implicit declarations introduced by elaborated types.
12812       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12813         unsigned Kind = 0;
12814         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12815         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12816         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12817         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12818         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12819         Invalid = true;
12820 
12821       // Otherwise it's a declaration.  Call out a particularly common
12822       // case here.
12823       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12824         unsigned Kind = 0;
12825         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12826         Diag(NameLoc, diag::err_tag_definition_of_typedef)
12827           << Name << Kind << TND->getUnderlyingType();
12828         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12829         Invalid = true;
12830 
12831       // Otherwise, diagnose.
12832       } else {
12833         // The tag name clashes with something else in the target scope,
12834         // issue an error and recover by making this tag be anonymous.
12835         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12836         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12837         Name = nullptr;
12838         Invalid = true;
12839       }
12840 
12841       // The existing declaration isn't relevant to us; we're in a
12842       // new scope, so clear out the previous declaration.
12843       Previous.clear();
12844     }
12845   }
12846 
12847 CreateNewDecl:
12848 
12849   TagDecl *PrevDecl = nullptr;
12850   if (Previous.isSingleResult())
12851     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12852 
12853   // If there is an identifier, use the location of the identifier as the
12854   // location of the decl, otherwise use the location of the struct/union
12855   // keyword.
12856   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12857 
12858   // Otherwise, create a new declaration. If there is a previous
12859   // declaration of the same entity, the two will be linked via
12860   // PrevDecl.
12861   TagDecl *New;
12862 
12863   bool IsForwardReference = false;
12864   if (Kind == TTK_Enum) {
12865     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12866     // enum X { A, B, C } D;    D should chain to X.
12867     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12868                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12869                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12870     // If this is an undefined enum, warn.
12871     if (TUK != TUK_Definition && !Invalid) {
12872       TagDecl *Def;
12873       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12874           cast<EnumDecl>(New)->isFixed()) {
12875         // C++0x: 7.2p2: opaque-enum-declaration.
12876         // Conflicts are diagnosed above. Do nothing.
12877       }
12878       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12879         Diag(Loc, diag::ext_forward_ref_enum_def)
12880           << New;
12881         Diag(Def->getLocation(), diag::note_previous_definition);
12882       } else {
12883         unsigned DiagID = diag::ext_forward_ref_enum;
12884         if (getLangOpts().MSVCCompat)
12885           DiagID = diag::ext_ms_forward_ref_enum;
12886         else if (getLangOpts().CPlusPlus)
12887           DiagID = diag::err_forward_ref_enum;
12888         Diag(Loc, DiagID);
12889 
12890         // If this is a forward-declared reference to an enumeration, make a
12891         // note of it; we won't actually be introducing the declaration into
12892         // the declaration context.
12893         if (TUK == TUK_Reference)
12894           IsForwardReference = true;
12895       }
12896     }
12897 
12898     if (EnumUnderlying) {
12899       EnumDecl *ED = cast<EnumDecl>(New);
12900       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12901         ED->setIntegerTypeSourceInfo(TI);
12902       else
12903         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12904       ED->setPromotionType(ED->getIntegerType());
12905     }
12906   } else {
12907     // struct/union/class
12908 
12909     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12910     // struct X { int A; } D;    D should chain to X.
12911     if (getLangOpts().CPlusPlus) {
12912       // FIXME: Look for a way to use RecordDecl for simple structs.
12913       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12914                                   cast_or_null<CXXRecordDecl>(PrevDecl));
12915 
12916       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12917         StdBadAlloc = cast<CXXRecordDecl>(New);
12918     } else
12919       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12920                                cast_or_null<RecordDecl>(PrevDecl));
12921   }
12922 
12923   // C++11 [dcl.type]p3:
12924   //   A type-specifier-seq shall not define a class or enumeration [...].
12925   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12926     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12927       << Context.getTagDeclType(New);
12928     Invalid = true;
12929   }
12930 
12931   // Maybe add qualifier info.
12932   if (SS.isNotEmpty()) {
12933     if (SS.isSet()) {
12934       // If this is either a declaration or a definition, check the
12935       // nested-name-specifier against the current context. We don't do this
12936       // for explicit specializations, because they have similar checking
12937       // (with more specific diagnostics) in the call to
12938       // CheckMemberSpecialization, below.
12939       if (!isExplicitSpecialization &&
12940           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12941           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12942         Invalid = true;
12943 
12944       New->setQualifierInfo(SS.getWithLocInContext(Context));
12945       if (TemplateParameterLists.size() > 0) {
12946         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12947       }
12948     }
12949     else
12950       Invalid = true;
12951   }
12952 
12953   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12954     // Add alignment attributes if necessary; these attributes are checked when
12955     // the ASTContext lays out the structure.
12956     //
12957     // It is important for implementing the correct semantics that this
12958     // happen here (in act on tag decl). The #pragma pack stack is
12959     // maintained as a result of parser callbacks which can occur at
12960     // many points during the parsing of a struct declaration (because
12961     // the #pragma tokens are effectively skipped over during the
12962     // parsing of the struct).
12963     if (TUK == TUK_Definition) {
12964       AddAlignmentAttributesForRecord(RD);
12965       AddMsStructLayoutForRecord(RD);
12966     }
12967   }
12968 
12969   if (ModulePrivateLoc.isValid()) {
12970     if (isExplicitSpecialization)
12971       Diag(New->getLocation(), diag::err_module_private_specialization)
12972         << 2
12973         << FixItHint::CreateRemoval(ModulePrivateLoc);
12974     // __module_private__ does not apply to local classes. However, we only
12975     // diagnose this as an error when the declaration specifiers are
12976     // freestanding. Here, we just ignore the __module_private__.
12977     else if (!SearchDC->isFunctionOrMethod())
12978       New->setModulePrivate();
12979   }
12980 
12981   // If this is a specialization of a member class (of a class template),
12982   // check the specialization.
12983   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12984     Invalid = true;
12985 
12986   // If we're declaring or defining a tag in function prototype scope in C,
12987   // note that this type can only be used within the function and add it to
12988   // the list of decls to inject into the function definition scope.
12989   if ((Name || Kind == TTK_Enum) &&
12990       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12991     if (getLangOpts().CPlusPlus) {
12992       // C++ [dcl.fct]p6:
12993       //   Types shall not be defined in return or parameter types.
12994       if (TUK == TUK_Definition && !IsTypeSpecifier) {
12995         Diag(Loc, diag::err_type_defined_in_param_type)
12996             << Name;
12997         Invalid = true;
12998       }
12999     } else if (!PrevDecl) {
13000       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13001     }
13002     DeclsInPrototypeScope.push_back(New);
13003   }
13004 
13005   if (Invalid)
13006     New->setInvalidDecl();
13007 
13008   if (Attr)
13009     ProcessDeclAttributeList(S, New, Attr);
13010 
13011   // Set the lexical context. If the tag has a C++ scope specifier, the
13012   // lexical context will be different from the semantic context.
13013   New->setLexicalDeclContext(CurContext);
13014 
13015   // Mark this as a friend decl if applicable.
13016   // In Microsoft mode, a friend declaration also acts as a forward
13017   // declaration so we always pass true to setObjectOfFriendDecl to make
13018   // the tag name visible.
13019   if (TUK == TUK_Friend)
13020     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13021 
13022   // Set the access specifier.
13023   if (!Invalid && SearchDC->isRecord())
13024     SetMemberAccessSpecifier(New, PrevDecl, AS);
13025 
13026   if (TUK == TUK_Definition)
13027     New->startDefinition();
13028 
13029   // If this has an identifier, add it to the scope stack.
13030   if (TUK == TUK_Friend) {
13031     // We might be replacing an existing declaration in the lookup tables;
13032     // if so, borrow its access specifier.
13033     if (PrevDecl)
13034       New->setAccess(PrevDecl->getAccess());
13035 
13036     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13037     DC->makeDeclVisibleInContext(New);
13038     if (Name) // can be null along some error paths
13039       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13040         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13041   } else if (Name) {
13042     S = getNonFieldDeclScope(S);
13043     PushOnScopeChains(New, S, !IsForwardReference);
13044     if (IsForwardReference)
13045       SearchDC->makeDeclVisibleInContext(New);
13046   } else {
13047     CurContext->addDecl(New);
13048   }
13049 
13050   // If this is the C FILE type, notify the AST context.
13051   if (IdentifierInfo *II = New->getIdentifier())
13052     if (!New->isInvalidDecl() &&
13053         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13054         II->isStr("FILE"))
13055       Context.setFILEDecl(New);
13056 
13057   if (PrevDecl)
13058     mergeDeclAttributes(New, PrevDecl);
13059 
13060   // If there's a #pragma GCC visibility in scope, set the visibility of this
13061   // record.
13062   AddPushedVisibilityAttribute(New);
13063 
13064   OwnedDecl = true;
13065   // In C++, don't return an invalid declaration. We can't recover well from
13066   // the cases where we make the type anonymous.
13067   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
13068 }
13069 
13070 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13071   AdjustDeclIfTemplate(TagD);
13072   TagDecl *Tag = cast<TagDecl>(TagD);
13073 
13074   // Enter the tag context.
13075   PushDeclContext(S, Tag);
13076 
13077   ActOnDocumentableDecl(TagD);
13078 
13079   // If there's a #pragma GCC visibility in scope, set the visibility of this
13080   // record.
13081   AddPushedVisibilityAttribute(Tag);
13082 }
13083 
13084 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13085   assert(isa<ObjCContainerDecl>(IDecl) &&
13086          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13087   DeclContext *OCD = cast<DeclContext>(IDecl);
13088   assert(getContainingDC(OCD) == CurContext &&
13089       "The next DeclContext should be lexically contained in the current one.");
13090   CurContext = OCD;
13091   return IDecl;
13092 }
13093 
13094 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13095                                            SourceLocation FinalLoc,
13096                                            bool IsFinalSpelledSealed,
13097                                            SourceLocation LBraceLoc) {
13098   AdjustDeclIfTemplate(TagD);
13099   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13100 
13101   FieldCollector->StartClass();
13102 
13103   if (!Record->getIdentifier())
13104     return;
13105 
13106   if (FinalLoc.isValid())
13107     Record->addAttr(new (Context)
13108                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13109 
13110   // C++ [class]p2:
13111   //   [...] The class-name is also inserted into the scope of the
13112   //   class itself; this is known as the injected-class-name. For
13113   //   purposes of access checking, the injected-class-name is treated
13114   //   as if it were a public member name.
13115   CXXRecordDecl *InjectedClassName
13116     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13117                             Record->getLocStart(), Record->getLocation(),
13118                             Record->getIdentifier(),
13119                             /*PrevDecl=*/nullptr,
13120                             /*DelayTypeCreation=*/true);
13121   Context.getTypeDeclType(InjectedClassName, Record);
13122   InjectedClassName->setImplicit();
13123   InjectedClassName->setAccess(AS_public);
13124   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13125       InjectedClassName->setDescribedClassTemplate(Template);
13126   PushOnScopeChains(InjectedClassName, S);
13127   assert(InjectedClassName->isInjectedClassName() &&
13128          "Broken injected-class-name");
13129 }
13130 
13131 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13132                                     SourceLocation RBraceLoc) {
13133   AdjustDeclIfTemplate(TagD);
13134   TagDecl *Tag = cast<TagDecl>(TagD);
13135   Tag->setRBraceLoc(RBraceLoc);
13136 
13137   // Make sure we "complete" the definition even it is invalid.
13138   if (Tag->isBeingDefined()) {
13139     assert(Tag->isInvalidDecl() && "We should already have completed it");
13140     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13141       RD->completeDefinition();
13142   }
13143 
13144   if (isa<CXXRecordDecl>(Tag))
13145     FieldCollector->FinishClass();
13146 
13147   // Exit this scope of this tag's definition.
13148   PopDeclContext();
13149 
13150   if (getCurLexicalContext()->isObjCContainer() &&
13151       Tag->getDeclContext()->isFileContext())
13152     Tag->setTopLevelDeclInObjCContainer();
13153 
13154   // Notify the consumer that we've defined a tag.
13155   if (!Tag->isInvalidDecl())
13156     Consumer.HandleTagDeclDefinition(Tag);
13157 }
13158 
13159 void Sema::ActOnObjCContainerFinishDefinition() {
13160   // Exit this scope of this interface definition.
13161   PopDeclContext();
13162 }
13163 
13164 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13165   assert(DC == CurContext && "Mismatch of container contexts");
13166   OriginalLexicalContext = DC;
13167   ActOnObjCContainerFinishDefinition();
13168 }
13169 
13170 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13171   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13172   OriginalLexicalContext = nullptr;
13173 }
13174 
13175 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13176   AdjustDeclIfTemplate(TagD);
13177   TagDecl *Tag = cast<TagDecl>(TagD);
13178   Tag->setInvalidDecl();
13179 
13180   // Make sure we "complete" the definition even it is invalid.
13181   if (Tag->isBeingDefined()) {
13182     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13183       RD->completeDefinition();
13184   }
13185 
13186   // We're undoing ActOnTagStartDefinition here, not
13187   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13188   // the FieldCollector.
13189 
13190   PopDeclContext();
13191 }
13192 
13193 // Note that FieldName may be null for anonymous bitfields.
13194 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13195                                 IdentifierInfo *FieldName,
13196                                 QualType FieldTy, bool IsMsStruct,
13197                                 Expr *BitWidth, bool *ZeroWidth) {
13198   // Default to true; that shouldn't confuse checks for emptiness
13199   if (ZeroWidth)
13200     *ZeroWidth = true;
13201 
13202   // C99 6.7.2.1p4 - verify the field type.
13203   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13204   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13205     // Handle incomplete types with specific error.
13206     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13207       return ExprError();
13208     if (FieldName)
13209       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13210         << FieldName << FieldTy << BitWidth->getSourceRange();
13211     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13212       << FieldTy << BitWidth->getSourceRange();
13213   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13214                                              UPPC_BitFieldWidth))
13215     return ExprError();
13216 
13217   // If the bit-width is type- or value-dependent, don't try to check
13218   // it now.
13219   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13220     return BitWidth;
13221 
13222   llvm::APSInt Value;
13223   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13224   if (ICE.isInvalid())
13225     return ICE;
13226   BitWidth = ICE.get();
13227 
13228   if (Value != 0 && ZeroWidth)
13229     *ZeroWidth = false;
13230 
13231   // Zero-width bitfield is ok for anonymous field.
13232   if (Value == 0 && FieldName)
13233     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13234 
13235   if (Value.isSigned() && Value.isNegative()) {
13236     if (FieldName)
13237       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13238                << FieldName << Value.toString(10);
13239     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13240       << Value.toString(10);
13241   }
13242 
13243   if (!FieldTy->isDependentType()) {
13244     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13245     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13246     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13247 
13248     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13249     // ABI.
13250     bool CStdConstraintViolation =
13251         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13252     bool MSBitfieldViolation =
13253         Value.ugt(TypeStorageSize) &&
13254         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13255     if (CStdConstraintViolation || MSBitfieldViolation) {
13256       unsigned DiagWidth =
13257           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13258       if (FieldName)
13259         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13260                << FieldName << (unsigned)Value.getZExtValue()
13261                << !CStdConstraintViolation << DiagWidth;
13262 
13263       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13264              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13265              << DiagWidth;
13266     }
13267 
13268     // Warn on types where the user might conceivably expect to get all
13269     // specified bits as value bits: that's all integral types other than
13270     // 'bool'.
13271     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13272       if (FieldName)
13273         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13274             << FieldName << (unsigned)Value.getZExtValue()
13275             << (unsigned)TypeWidth;
13276       else
13277         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13278             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13279     }
13280   }
13281 
13282   return BitWidth;
13283 }
13284 
13285 /// ActOnField - Each field of a C struct/union is passed into this in order
13286 /// to create a FieldDecl object for it.
13287 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13288                        Declarator &D, Expr *BitfieldWidth) {
13289   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13290                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13291                                /*InitStyle=*/ICIS_NoInit, AS_public);
13292   return Res;
13293 }
13294 
13295 /// HandleField - Analyze a field of a C struct or a C++ data member.
13296 ///
13297 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13298                              SourceLocation DeclStart,
13299                              Declarator &D, Expr *BitWidth,
13300                              InClassInitStyle InitStyle,
13301                              AccessSpecifier AS) {
13302   IdentifierInfo *II = D.getIdentifier();
13303   SourceLocation Loc = DeclStart;
13304   if (II) Loc = D.getIdentifierLoc();
13305 
13306   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13307   QualType T = TInfo->getType();
13308   if (getLangOpts().CPlusPlus) {
13309     CheckExtraCXXDefaultArguments(D);
13310 
13311     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13312                                         UPPC_DataMemberType)) {
13313       D.setInvalidType();
13314       T = Context.IntTy;
13315       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13316     }
13317   }
13318 
13319   // TR 18037 does not allow fields to be declared with address spaces.
13320   if (T.getQualifiers().hasAddressSpace()) {
13321     Diag(Loc, diag::err_field_with_address_space);
13322     D.setInvalidType();
13323   }
13324 
13325   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13326   // used as structure or union field: image, sampler, event or block types.
13327   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13328                           T->isSamplerT() || T->isBlockPointerType())) {
13329     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13330     D.setInvalidType();
13331   }
13332 
13333   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13334 
13335   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13336     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13337          diag::err_invalid_thread)
13338       << DeclSpec::getSpecifierName(TSCS);
13339 
13340   // Check to see if this name was declared as a member previously
13341   NamedDecl *PrevDecl = nullptr;
13342   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13343   LookupName(Previous, S);
13344   switch (Previous.getResultKind()) {
13345     case LookupResult::Found:
13346     case LookupResult::FoundUnresolvedValue:
13347       PrevDecl = Previous.getAsSingle<NamedDecl>();
13348       break;
13349 
13350     case LookupResult::FoundOverloaded:
13351       PrevDecl = Previous.getRepresentativeDecl();
13352       break;
13353 
13354     case LookupResult::NotFound:
13355     case LookupResult::NotFoundInCurrentInstantiation:
13356     case LookupResult::Ambiguous:
13357       break;
13358   }
13359   Previous.suppressDiagnostics();
13360 
13361   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13362     // Maybe we will complain about the shadowed template parameter.
13363     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13364     // Just pretend that we didn't see the previous declaration.
13365     PrevDecl = nullptr;
13366   }
13367 
13368   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13369     PrevDecl = nullptr;
13370 
13371   bool Mutable
13372     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13373   SourceLocation TSSL = D.getLocStart();
13374   FieldDecl *NewFD
13375     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13376                      TSSL, AS, PrevDecl, &D);
13377 
13378   if (NewFD->isInvalidDecl())
13379     Record->setInvalidDecl();
13380 
13381   if (D.getDeclSpec().isModulePrivateSpecified())
13382     NewFD->setModulePrivate();
13383 
13384   if (NewFD->isInvalidDecl() && PrevDecl) {
13385     // Don't introduce NewFD into scope; there's already something
13386     // with the same name in the same scope.
13387   } else if (II) {
13388     PushOnScopeChains(NewFD, S);
13389   } else
13390     Record->addDecl(NewFD);
13391 
13392   return NewFD;
13393 }
13394 
13395 /// \brief Build a new FieldDecl and check its well-formedness.
13396 ///
13397 /// This routine builds a new FieldDecl given the fields name, type,
13398 /// record, etc. \p PrevDecl should refer to any previous declaration
13399 /// with the same name and in the same scope as the field to be
13400 /// created.
13401 ///
13402 /// \returns a new FieldDecl.
13403 ///
13404 /// \todo The Declarator argument is a hack. It will be removed once
13405 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13406                                 TypeSourceInfo *TInfo,
13407                                 RecordDecl *Record, SourceLocation Loc,
13408                                 bool Mutable, Expr *BitWidth,
13409                                 InClassInitStyle InitStyle,
13410                                 SourceLocation TSSL,
13411                                 AccessSpecifier AS, NamedDecl *PrevDecl,
13412                                 Declarator *D) {
13413   IdentifierInfo *II = Name.getAsIdentifierInfo();
13414   bool InvalidDecl = false;
13415   if (D) InvalidDecl = D->isInvalidType();
13416 
13417   // If we receive a broken type, recover by assuming 'int' and
13418   // marking this declaration as invalid.
13419   if (T.isNull()) {
13420     InvalidDecl = true;
13421     T = Context.IntTy;
13422   }
13423 
13424   QualType EltTy = Context.getBaseElementType(T);
13425   if (!EltTy->isDependentType()) {
13426     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13427       // Fields of incomplete type force their record to be invalid.
13428       Record->setInvalidDecl();
13429       InvalidDecl = true;
13430     } else {
13431       NamedDecl *Def;
13432       EltTy->isIncompleteType(&Def);
13433       if (Def && Def->isInvalidDecl()) {
13434         Record->setInvalidDecl();
13435         InvalidDecl = true;
13436       }
13437     }
13438   }
13439 
13440   // OpenCL v1.2 s6.9.c: bitfields are not supported.
13441   if (BitWidth && getLangOpts().OpenCL) {
13442     Diag(Loc, diag::err_opencl_bitfields);
13443     InvalidDecl = true;
13444   }
13445 
13446   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13447   // than a variably modified type.
13448   if (!InvalidDecl && T->isVariablyModifiedType()) {
13449     bool SizeIsNegative;
13450     llvm::APSInt Oversized;
13451 
13452     TypeSourceInfo *FixedTInfo =
13453       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13454                                                     SizeIsNegative,
13455                                                     Oversized);
13456     if (FixedTInfo) {
13457       Diag(Loc, diag::warn_illegal_constant_array_size);
13458       TInfo = FixedTInfo;
13459       T = FixedTInfo->getType();
13460     } else {
13461       if (SizeIsNegative)
13462         Diag(Loc, diag::err_typecheck_negative_array_size);
13463       else if (Oversized.getBoolValue())
13464         Diag(Loc, diag::err_array_too_large)
13465           << Oversized.toString(10);
13466       else
13467         Diag(Loc, diag::err_typecheck_field_variable_size);
13468       InvalidDecl = true;
13469     }
13470   }
13471 
13472   // Fields can not have abstract class types
13473   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13474                                              diag::err_abstract_type_in_decl,
13475                                              AbstractFieldType))
13476     InvalidDecl = true;
13477 
13478   bool ZeroWidth = false;
13479   if (InvalidDecl)
13480     BitWidth = nullptr;
13481   // If this is declared as a bit-field, check the bit-field.
13482   if (BitWidth) {
13483     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13484                               &ZeroWidth).get();
13485     if (!BitWidth) {
13486       InvalidDecl = true;
13487       BitWidth = nullptr;
13488       ZeroWidth = false;
13489     }
13490   }
13491 
13492   // Check that 'mutable' is consistent with the type of the declaration.
13493   if (!InvalidDecl && Mutable) {
13494     unsigned DiagID = 0;
13495     if (T->isReferenceType())
13496       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13497                                         : diag::err_mutable_reference;
13498     else if (T.isConstQualified())
13499       DiagID = diag::err_mutable_const;
13500 
13501     if (DiagID) {
13502       SourceLocation ErrLoc = Loc;
13503       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13504         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13505       Diag(ErrLoc, DiagID);
13506       if (DiagID != diag::ext_mutable_reference) {
13507         Mutable = false;
13508         InvalidDecl = true;
13509       }
13510     }
13511   }
13512 
13513   // C++11 [class.union]p8 (DR1460):
13514   //   At most one variant member of a union may have a
13515   //   brace-or-equal-initializer.
13516   if (InitStyle != ICIS_NoInit)
13517     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13518 
13519   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13520                                        BitWidth, Mutable, InitStyle);
13521   if (InvalidDecl)
13522     NewFD->setInvalidDecl();
13523 
13524   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13525     Diag(Loc, diag::err_duplicate_member) << II;
13526     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13527     NewFD->setInvalidDecl();
13528   }
13529 
13530   if (!InvalidDecl && getLangOpts().CPlusPlus) {
13531     if (Record->isUnion()) {
13532       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13533         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13534         if (RDecl->getDefinition()) {
13535           // C++ [class.union]p1: An object of a class with a non-trivial
13536           // constructor, a non-trivial copy constructor, a non-trivial
13537           // destructor, or a non-trivial copy assignment operator
13538           // cannot be a member of a union, nor can an array of such
13539           // objects.
13540           if (CheckNontrivialField(NewFD))
13541             NewFD->setInvalidDecl();
13542         }
13543       }
13544 
13545       // C++ [class.union]p1: If a union contains a member of reference type,
13546       // the program is ill-formed, except when compiling with MSVC extensions
13547       // enabled.
13548       if (EltTy->isReferenceType()) {
13549         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13550                                     diag::ext_union_member_of_reference_type :
13551                                     diag::err_union_member_of_reference_type)
13552           << NewFD->getDeclName() << EltTy;
13553         if (!getLangOpts().MicrosoftExt)
13554           NewFD->setInvalidDecl();
13555       }
13556     }
13557   }
13558 
13559   // FIXME: We need to pass in the attributes given an AST
13560   // representation, not a parser representation.
13561   if (D) {
13562     // FIXME: The current scope is almost... but not entirely... correct here.
13563     ProcessDeclAttributes(getCurScope(), NewFD, *D);
13564 
13565     if (NewFD->hasAttrs())
13566       CheckAlignasUnderalignment(NewFD);
13567   }
13568 
13569   // In auto-retain/release, infer strong retension for fields of
13570   // retainable type.
13571   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13572     NewFD->setInvalidDecl();
13573 
13574   if (T.isObjCGCWeak())
13575     Diag(Loc, diag::warn_attribute_weak_on_field);
13576 
13577   NewFD->setAccess(AS);
13578   return NewFD;
13579 }
13580 
13581 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13582   assert(FD);
13583   assert(getLangOpts().CPlusPlus && "valid check only for C++");
13584 
13585   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13586     return false;
13587 
13588   QualType EltTy = Context.getBaseElementType(FD->getType());
13589   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13590     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13591     if (RDecl->getDefinition()) {
13592       // We check for copy constructors before constructors
13593       // because otherwise we'll never get complaints about
13594       // copy constructors.
13595 
13596       CXXSpecialMember member = CXXInvalid;
13597       // We're required to check for any non-trivial constructors. Since the
13598       // implicit default constructor is suppressed if there are any
13599       // user-declared constructors, we just need to check that there is a
13600       // trivial default constructor and a trivial copy constructor. (We don't
13601       // worry about move constructors here, since this is a C++98 check.)
13602       if (RDecl->hasNonTrivialCopyConstructor())
13603         member = CXXCopyConstructor;
13604       else if (!RDecl->hasTrivialDefaultConstructor())
13605         member = CXXDefaultConstructor;
13606       else if (RDecl->hasNonTrivialCopyAssignment())
13607         member = CXXCopyAssignment;
13608       else if (RDecl->hasNonTrivialDestructor())
13609         member = CXXDestructor;
13610 
13611       if (member != CXXInvalid) {
13612         if (!getLangOpts().CPlusPlus11 &&
13613             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13614           // Objective-C++ ARC: it is an error to have a non-trivial field of
13615           // a union. However, system headers in Objective-C programs
13616           // occasionally have Objective-C lifetime objects within unions,
13617           // and rather than cause the program to fail, we make those
13618           // members unavailable.
13619           SourceLocation Loc = FD->getLocation();
13620           if (getSourceManager().isInSystemHeader(Loc)) {
13621             if (!FD->hasAttr<UnavailableAttr>())
13622               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13623                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13624             return false;
13625           }
13626         }
13627 
13628         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13629                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13630                diag::err_illegal_union_or_anon_struct_member)
13631           << FD->getParent()->isUnion() << FD->getDeclName() << member;
13632         DiagnoseNontrivial(RDecl, member);
13633         return !getLangOpts().CPlusPlus11;
13634       }
13635     }
13636   }
13637 
13638   return false;
13639 }
13640 
13641 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13642 ///  AST enum value.
13643 static ObjCIvarDecl::AccessControl
13644 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13645   switch (ivarVisibility) {
13646   default: llvm_unreachable("Unknown visitibility kind");
13647   case tok::objc_private: return ObjCIvarDecl::Private;
13648   case tok::objc_public: return ObjCIvarDecl::Public;
13649   case tok::objc_protected: return ObjCIvarDecl::Protected;
13650   case tok::objc_package: return ObjCIvarDecl::Package;
13651   }
13652 }
13653 
13654 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13655 /// in order to create an IvarDecl object for it.
13656 Decl *Sema::ActOnIvar(Scope *S,
13657                                 SourceLocation DeclStart,
13658                                 Declarator &D, Expr *BitfieldWidth,
13659                                 tok::ObjCKeywordKind Visibility) {
13660 
13661   IdentifierInfo *II = D.getIdentifier();
13662   Expr *BitWidth = (Expr*)BitfieldWidth;
13663   SourceLocation Loc = DeclStart;
13664   if (II) Loc = D.getIdentifierLoc();
13665 
13666   // FIXME: Unnamed fields can be handled in various different ways, for
13667   // example, unnamed unions inject all members into the struct namespace!
13668 
13669   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13670   QualType T = TInfo->getType();
13671 
13672   if (BitWidth) {
13673     // 6.7.2.1p3, 6.7.2.1p4
13674     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13675     if (!BitWidth)
13676       D.setInvalidType();
13677   } else {
13678     // Not a bitfield.
13679 
13680     // validate II.
13681 
13682   }
13683   if (T->isReferenceType()) {
13684     Diag(Loc, diag::err_ivar_reference_type);
13685     D.setInvalidType();
13686   }
13687   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13688   // than a variably modified type.
13689   else if (T->isVariablyModifiedType()) {
13690     Diag(Loc, diag::err_typecheck_ivar_variable_size);
13691     D.setInvalidType();
13692   }
13693 
13694   // Get the visibility (access control) for this ivar.
13695   ObjCIvarDecl::AccessControl ac =
13696     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13697                                         : ObjCIvarDecl::None;
13698   // Must set ivar's DeclContext to its enclosing interface.
13699   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13700   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13701     return nullptr;
13702   ObjCContainerDecl *EnclosingContext;
13703   if (ObjCImplementationDecl *IMPDecl =
13704       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13705     if (LangOpts.ObjCRuntime.isFragile()) {
13706     // Case of ivar declared in an implementation. Context is that of its class.
13707       EnclosingContext = IMPDecl->getClassInterface();
13708       assert(EnclosingContext && "Implementation has no class interface!");
13709     }
13710     else
13711       EnclosingContext = EnclosingDecl;
13712   } else {
13713     if (ObjCCategoryDecl *CDecl =
13714         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13715       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13716         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13717         return nullptr;
13718       }
13719     }
13720     EnclosingContext = EnclosingDecl;
13721   }
13722 
13723   // Construct the decl.
13724   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13725                                              DeclStart, Loc, II, T,
13726                                              TInfo, ac, (Expr *)BitfieldWidth);
13727 
13728   if (II) {
13729     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13730                                            ForRedeclaration);
13731     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13732         && !isa<TagDecl>(PrevDecl)) {
13733       Diag(Loc, diag::err_duplicate_member) << II;
13734       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13735       NewID->setInvalidDecl();
13736     }
13737   }
13738 
13739   // Process attributes attached to the ivar.
13740   ProcessDeclAttributes(S, NewID, D);
13741 
13742   if (D.isInvalidType())
13743     NewID->setInvalidDecl();
13744 
13745   // In ARC, infer 'retaining' for ivars of retainable type.
13746   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13747     NewID->setInvalidDecl();
13748 
13749   if (D.getDeclSpec().isModulePrivateSpecified())
13750     NewID->setModulePrivate();
13751 
13752   if (II) {
13753     // FIXME: When interfaces are DeclContexts, we'll need to add
13754     // these to the interface.
13755     S->AddDecl(NewID);
13756     IdResolver.AddDecl(NewID);
13757   }
13758 
13759   if (LangOpts.ObjCRuntime.isNonFragile() &&
13760       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13761     Diag(Loc, diag::warn_ivars_in_interface);
13762 
13763   return NewID;
13764 }
13765 
13766 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13767 /// class and class extensions. For every class \@interface and class
13768 /// extension \@interface, if the last ivar is a bitfield of any type,
13769 /// then add an implicit `char :0` ivar to the end of that interface.
13770 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13771                              SmallVectorImpl<Decl *> &AllIvarDecls) {
13772   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13773     return;
13774 
13775   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13776   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13777 
13778   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13779     return;
13780   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13781   if (!ID) {
13782     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13783       if (!CD->IsClassExtension())
13784         return;
13785     }
13786     // No need to add this to end of @implementation.
13787     else
13788       return;
13789   }
13790   // All conditions are met. Add a new bitfield to the tail end of ivars.
13791   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13792   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13793 
13794   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13795                               DeclLoc, DeclLoc, nullptr,
13796                               Context.CharTy,
13797                               Context.getTrivialTypeSourceInfo(Context.CharTy,
13798                                                                DeclLoc),
13799                               ObjCIvarDecl::Private, BW,
13800                               true);
13801   AllIvarDecls.push_back(Ivar);
13802 }
13803 
13804 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13805                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
13806                        SourceLocation RBrac, AttributeList *Attr) {
13807   assert(EnclosingDecl && "missing record or interface decl");
13808 
13809   // If this is an Objective-C @implementation or category and we have
13810   // new fields here we should reset the layout of the interface since
13811   // it will now change.
13812   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13813     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13814     switch (DC->getKind()) {
13815     default: break;
13816     case Decl::ObjCCategory:
13817       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13818       break;
13819     case Decl::ObjCImplementation:
13820       Context.
13821         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13822       break;
13823     }
13824   }
13825 
13826   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13827 
13828   // Start counting up the number of named members; make sure to include
13829   // members of anonymous structs and unions in the total.
13830   unsigned NumNamedMembers = 0;
13831   if (Record) {
13832     for (const auto *I : Record->decls()) {
13833       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13834         if (IFD->getDeclName())
13835           ++NumNamedMembers;
13836     }
13837   }
13838 
13839   // Verify that all the fields are okay.
13840   SmallVector<FieldDecl*, 32> RecFields;
13841 
13842   bool ARCErrReported = false;
13843   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13844        i != end; ++i) {
13845     FieldDecl *FD = cast<FieldDecl>(*i);
13846 
13847     // Get the type for the field.
13848     const Type *FDTy = FD->getType().getTypePtr();
13849 
13850     if (!FD->isAnonymousStructOrUnion()) {
13851       // Remember all fields written by the user.
13852       RecFields.push_back(FD);
13853     }
13854 
13855     // If the field is already invalid for some reason, don't emit more
13856     // diagnostics about it.
13857     if (FD->isInvalidDecl()) {
13858       EnclosingDecl->setInvalidDecl();
13859       continue;
13860     }
13861 
13862     // C99 6.7.2.1p2:
13863     //   A structure or union shall not contain a member with
13864     //   incomplete or function type (hence, a structure shall not
13865     //   contain an instance of itself, but may contain a pointer to
13866     //   an instance of itself), except that the last member of a
13867     //   structure with more than one named member may have incomplete
13868     //   array type; such a structure (and any union containing,
13869     //   possibly recursively, a member that is such a structure)
13870     //   shall not be a member of a structure or an element of an
13871     //   array.
13872     if (FDTy->isFunctionType()) {
13873       // Field declared as a function.
13874       Diag(FD->getLocation(), diag::err_field_declared_as_function)
13875         << FD->getDeclName();
13876       FD->setInvalidDecl();
13877       EnclosingDecl->setInvalidDecl();
13878       continue;
13879     } else if (FDTy->isIncompleteArrayType() && Record &&
13880                ((i + 1 == Fields.end() && !Record->isUnion()) ||
13881                 ((getLangOpts().MicrosoftExt ||
13882                   getLangOpts().CPlusPlus) &&
13883                  (i + 1 == Fields.end() || Record->isUnion())))) {
13884       // Flexible array member.
13885       // Microsoft and g++ is more permissive regarding flexible array.
13886       // It will accept flexible array in union and also
13887       // as the sole element of a struct/class.
13888       unsigned DiagID = 0;
13889       if (Record->isUnion())
13890         DiagID = getLangOpts().MicrosoftExt
13891                      ? diag::ext_flexible_array_union_ms
13892                      : getLangOpts().CPlusPlus
13893                            ? diag::ext_flexible_array_union_gnu
13894                            : diag::err_flexible_array_union;
13895       else if (Fields.size() == 1)
13896         DiagID = getLangOpts().MicrosoftExt
13897                      ? diag::ext_flexible_array_empty_aggregate_ms
13898                      : getLangOpts().CPlusPlus
13899                            ? diag::ext_flexible_array_empty_aggregate_gnu
13900                            : NumNamedMembers < 1
13901                                  ? diag::err_flexible_array_empty_aggregate
13902                                  : 0;
13903 
13904       if (DiagID)
13905         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13906                                         << Record->getTagKind();
13907       // While the layout of types that contain virtual bases is not specified
13908       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13909       // virtual bases after the derived members.  This would make a flexible
13910       // array member declared at the end of an object not adjacent to the end
13911       // of the type.
13912       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13913         if (RD->getNumVBases() != 0)
13914           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13915             << FD->getDeclName() << Record->getTagKind();
13916       if (!getLangOpts().C99)
13917         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13918           << FD->getDeclName() << Record->getTagKind();
13919 
13920       // If the element type has a non-trivial destructor, we would not
13921       // implicitly destroy the elements, so disallow it for now.
13922       //
13923       // FIXME: GCC allows this. We should probably either implicitly delete
13924       // the destructor of the containing class, or just allow this.
13925       QualType BaseElem = Context.getBaseElementType(FD->getType());
13926       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13927         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13928           << FD->getDeclName() << FD->getType();
13929         FD->setInvalidDecl();
13930         EnclosingDecl->setInvalidDecl();
13931         continue;
13932       }
13933       // Okay, we have a legal flexible array member at the end of the struct.
13934       Record->setHasFlexibleArrayMember(true);
13935     } else if (!FDTy->isDependentType() &&
13936                RequireCompleteType(FD->getLocation(), FD->getType(),
13937                                    diag::err_field_incomplete)) {
13938       // Incomplete type
13939       FD->setInvalidDecl();
13940       EnclosingDecl->setInvalidDecl();
13941       continue;
13942     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13943       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13944         // A type which contains a flexible array member is considered to be a
13945         // flexible array member.
13946         Record->setHasFlexibleArrayMember(true);
13947         if (!Record->isUnion()) {
13948           // If this is a struct/class and this is not the last element, reject
13949           // it.  Note that GCC supports variable sized arrays in the middle of
13950           // structures.
13951           if (i + 1 != Fields.end())
13952             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13953               << FD->getDeclName() << FD->getType();
13954           else {
13955             // We support flexible arrays at the end of structs in
13956             // other structs as an extension.
13957             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13958               << FD->getDeclName();
13959           }
13960         }
13961       }
13962       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13963           RequireNonAbstractType(FD->getLocation(), FD->getType(),
13964                                  diag::err_abstract_type_in_decl,
13965                                  AbstractIvarType)) {
13966         // Ivars can not have abstract class types
13967         FD->setInvalidDecl();
13968       }
13969       if (Record && FDTTy->getDecl()->hasObjectMember())
13970         Record->setHasObjectMember(true);
13971       if (Record && FDTTy->getDecl()->hasVolatileMember())
13972         Record->setHasVolatileMember(true);
13973     } else if (FDTy->isObjCObjectType()) {
13974       /// A field cannot be an Objective-c object
13975       Diag(FD->getLocation(), diag::err_statically_allocated_object)
13976         << FixItHint::CreateInsertion(FD->getLocation(), "*");
13977       QualType T = Context.getObjCObjectPointerType(FD->getType());
13978       FD->setType(T);
13979     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13980                (!getLangOpts().CPlusPlus || Record->isUnion())) {
13981       // It's an error in ARC if a field has lifetime.
13982       // We don't want to report this in a system header, though,
13983       // so we just make the field unavailable.
13984       // FIXME: that's really not sufficient; we need to make the type
13985       // itself invalid to, say, initialize or copy.
13986       QualType T = FD->getType();
13987       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
13988       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13989         SourceLocation loc = FD->getLocation();
13990         if (getSourceManager().isInSystemHeader(loc)) {
13991           if (!FD->hasAttr<UnavailableAttr>()) {
13992             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13993                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
13994           }
13995         } else {
13996           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
13997             << T->isBlockPointerType() << Record->getTagKind();
13998         }
13999         ARCErrReported = true;
14000       }
14001     } else if (getLangOpts().ObjC1 &&
14002                getLangOpts().getGC() != LangOptions::NonGC &&
14003                Record && !Record->hasObjectMember()) {
14004       if (FD->getType()->isObjCObjectPointerType() ||
14005           FD->getType().isObjCGCStrong())
14006         Record->setHasObjectMember(true);
14007       else if (Context.getAsArrayType(FD->getType())) {
14008         QualType BaseType = Context.getBaseElementType(FD->getType());
14009         if (BaseType->isRecordType() &&
14010             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14011           Record->setHasObjectMember(true);
14012         else if (BaseType->isObjCObjectPointerType() ||
14013                  BaseType.isObjCGCStrong())
14014                Record->setHasObjectMember(true);
14015       }
14016     }
14017     if (Record && FD->getType().isVolatileQualified())
14018       Record->setHasVolatileMember(true);
14019     // Keep track of the number of named members.
14020     if (FD->getIdentifier())
14021       ++NumNamedMembers;
14022   }
14023 
14024   // Okay, we successfully defined 'Record'.
14025   if (Record) {
14026     bool Completed = false;
14027     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14028       if (!CXXRecord->isInvalidDecl()) {
14029         // Set access bits correctly on the directly-declared conversions.
14030         for (CXXRecordDecl::conversion_iterator
14031                I = CXXRecord->conversion_begin(),
14032                E = CXXRecord->conversion_end(); I != E; ++I)
14033           I.setAccess((*I)->getAccess());
14034       }
14035 
14036       if (!CXXRecord->isDependentType()) {
14037         if (CXXRecord->hasUserDeclaredDestructor()) {
14038           // Adjust user-defined destructor exception spec.
14039           if (getLangOpts().CPlusPlus11)
14040             AdjustDestructorExceptionSpec(CXXRecord,
14041                                           CXXRecord->getDestructor());
14042         }
14043 
14044         if (!CXXRecord->isInvalidDecl()) {
14045           // Add any implicitly-declared members to this class.
14046           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14047 
14048           // If we have virtual base classes, we may end up finding multiple
14049           // final overriders for a given virtual function. Check for this
14050           // problem now.
14051           if (CXXRecord->getNumVBases()) {
14052             CXXFinalOverriderMap FinalOverriders;
14053             CXXRecord->getFinalOverriders(FinalOverriders);
14054 
14055             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14056                                              MEnd = FinalOverriders.end();
14057                  M != MEnd; ++M) {
14058               for (OverridingMethods::iterator SO = M->second.begin(),
14059                                             SOEnd = M->second.end();
14060                    SO != SOEnd; ++SO) {
14061                 assert(SO->second.size() > 0 &&
14062                        "Virtual function without overridding functions?");
14063                 if (SO->second.size() == 1)
14064                   continue;
14065 
14066                 // C++ [class.virtual]p2:
14067                 //   In a derived class, if a virtual member function of a base
14068                 //   class subobject has more than one final overrider the
14069                 //   program is ill-formed.
14070                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14071                   << (const NamedDecl *)M->first << Record;
14072                 Diag(M->first->getLocation(),
14073                      diag::note_overridden_virtual_function);
14074                 for (OverridingMethods::overriding_iterator
14075                           OM = SO->second.begin(),
14076                        OMEnd = SO->second.end();
14077                      OM != OMEnd; ++OM)
14078                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14079                     << (const NamedDecl *)M->first << OM->Method->getParent();
14080 
14081                 Record->setInvalidDecl();
14082               }
14083             }
14084             CXXRecord->completeDefinition(&FinalOverriders);
14085             Completed = true;
14086           }
14087         }
14088       }
14089     }
14090 
14091     if (!Completed)
14092       Record->completeDefinition();
14093 
14094     if (Record->hasAttrs()) {
14095       CheckAlignasUnderalignment(Record);
14096 
14097       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14098         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14099                                            IA->getRange(), IA->getBestCase(),
14100                                            IA->getSemanticSpelling());
14101     }
14102 
14103     // Check if the structure/union declaration is a type that can have zero
14104     // size in C. For C this is a language extension, for C++ it may cause
14105     // compatibility problems.
14106     bool CheckForZeroSize;
14107     if (!getLangOpts().CPlusPlus) {
14108       CheckForZeroSize = true;
14109     } else {
14110       // For C++ filter out types that cannot be referenced in C code.
14111       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14112       CheckForZeroSize =
14113           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14114           !CXXRecord->isDependentType() &&
14115           CXXRecord->isCLike();
14116     }
14117     if (CheckForZeroSize) {
14118       bool ZeroSize = true;
14119       bool IsEmpty = true;
14120       unsigned NonBitFields = 0;
14121       for (RecordDecl::field_iterator I = Record->field_begin(),
14122                                       E = Record->field_end();
14123            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14124         IsEmpty = false;
14125         if (I->isUnnamedBitfield()) {
14126           if (I->getBitWidthValue(Context) > 0)
14127             ZeroSize = false;
14128         } else {
14129           ++NonBitFields;
14130           QualType FieldType = I->getType();
14131           if (FieldType->isIncompleteType() ||
14132               !Context.getTypeSizeInChars(FieldType).isZero())
14133             ZeroSize = false;
14134         }
14135       }
14136 
14137       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14138       // allowed in C++, but warn if its declaration is inside
14139       // extern "C" block.
14140       if (ZeroSize) {
14141         Diag(RecLoc, getLangOpts().CPlusPlus ?
14142                          diag::warn_zero_size_struct_union_in_extern_c :
14143                          diag::warn_zero_size_struct_union_compat)
14144           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14145       }
14146 
14147       // Structs without named members are extension in C (C99 6.7.2.1p7),
14148       // but are accepted by GCC.
14149       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14150         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14151                                diag::ext_no_named_members_in_struct_union)
14152           << Record->isUnion();
14153       }
14154     }
14155   } else {
14156     ObjCIvarDecl **ClsFields =
14157       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14158     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14159       ID->setEndOfDefinitionLoc(RBrac);
14160       // Add ivar's to class's DeclContext.
14161       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14162         ClsFields[i]->setLexicalDeclContext(ID);
14163         ID->addDecl(ClsFields[i]);
14164       }
14165       // Must enforce the rule that ivars in the base classes may not be
14166       // duplicates.
14167       if (ID->getSuperClass())
14168         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14169     } else if (ObjCImplementationDecl *IMPDecl =
14170                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14171       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14172       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14173         // Ivar declared in @implementation never belongs to the implementation.
14174         // Only it is in implementation's lexical context.
14175         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14176       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14177       IMPDecl->setIvarLBraceLoc(LBrac);
14178       IMPDecl->setIvarRBraceLoc(RBrac);
14179     } else if (ObjCCategoryDecl *CDecl =
14180                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14181       // case of ivars in class extension; all other cases have been
14182       // reported as errors elsewhere.
14183       // FIXME. Class extension does not have a LocEnd field.
14184       // CDecl->setLocEnd(RBrac);
14185       // Add ivar's to class extension's DeclContext.
14186       // Diagnose redeclaration of private ivars.
14187       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14188       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14189         if (IDecl) {
14190           if (const ObjCIvarDecl *ClsIvar =
14191               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14192             Diag(ClsFields[i]->getLocation(),
14193                  diag::err_duplicate_ivar_declaration);
14194             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14195             continue;
14196           }
14197           for (const auto *Ext : IDecl->known_extensions()) {
14198             if (const ObjCIvarDecl *ClsExtIvar
14199                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14200               Diag(ClsFields[i]->getLocation(),
14201                    diag::err_duplicate_ivar_declaration);
14202               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14203               continue;
14204             }
14205           }
14206         }
14207         ClsFields[i]->setLexicalDeclContext(CDecl);
14208         CDecl->addDecl(ClsFields[i]);
14209       }
14210       CDecl->setIvarLBraceLoc(LBrac);
14211       CDecl->setIvarRBraceLoc(RBrac);
14212     }
14213   }
14214 
14215   if (Attr)
14216     ProcessDeclAttributeList(S, Record, Attr);
14217 }
14218 
14219 /// \brief Determine whether the given integral value is representable within
14220 /// the given type T.
14221 static bool isRepresentableIntegerValue(ASTContext &Context,
14222                                         llvm::APSInt &Value,
14223                                         QualType T) {
14224   assert(T->isIntegralType(Context) && "Integral type required!");
14225   unsigned BitWidth = Context.getIntWidth(T);
14226 
14227   if (Value.isUnsigned() || Value.isNonNegative()) {
14228     if (T->isSignedIntegerOrEnumerationType())
14229       --BitWidth;
14230     return Value.getActiveBits() <= BitWidth;
14231   }
14232   return Value.getMinSignedBits() <= BitWidth;
14233 }
14234 
14235 // \brief Given an integral type, return the next larger integral type
14236 // (or a NULL type of no such type exists).
14237 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14238   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14239   // enum checking below.
14240   assert(T->isIntegralType(Context) && "Integral type required!");
14241   const unsigned NumTypes = 4;
14242   QualType SignedIntegralTypes[NumTypes] = {
14243     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14244   };
14245   QualType UnsignedIntegralTypes[NumTypes] = {
14246     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14247     Context.UnsignedLongLongTy
14248   };
14249 
14250   unsigned BitWidth = Context.getTypeSize(T);
14251   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14252                                                         : UnsignedIntegralTypes;
14253   for (unsigned I = 0; I != NumTypes; ++I)
14254     if (Context.getTypeSize(Types[I]) > BitWidth)
14255       return Types[I];
14256 
14257   return QualType();
14258 }
14259 
14260 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14261                                           EnumConstantDecl *LastEnumConst,
14262                                           SourceLocation IdLoc,
14263                                           IdentifierInfo *Id,
14264                                           Expr *Val) {
14265   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14266   llvm::APSInt EnumVal(IntWidth);
14267   QualType EltTy;
14268 
14269   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14270     Val = nullptr;
14271 
14272   if (Val)
14273     Val = DefaultLvalueConversion(Val).get();
14274 
14275   if (Val) {
14276     if (Enum->isDependentType() || Val->isTypeDependent())
14277       EltTy = Context.DependentTy;
14278     else {
14279       SourceLocation ExpLoc;
14280       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14281           !getLangOpts().MSVCCompat) {
14282         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14283         // constant-expression in the enumerator-definition shall be a converted
14284         // constant expression of the underlying type.
14285         EltTy = Enum->getIntegerType();
14286         ExprResult Converted =
14287           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14288                                            CCEK_Enumerator);
14289         if (Converted.isInvalid())
14290           Val = nullptr;
14291         else
14292           Val = Converted.get();
14293       } else if (!Val->isValueDependent() &&
14294                  !(Val = VerifyIntegerConstantExpression(Val,
14295                                                          &EnumVal).get())) {
14296         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14297       } else {
14298         if (Enum->isFixed()) {
14299           EltTy = Enum->getIntegerType();
14300 
14301           // In Obj-C and Microsoft mode, require the enumeration value to be
14302           // representable in the underlying type of the enumeration. In C++11,
14303           // we perform a non-narrowing conversion as part of converted constant
14304           // expression checking.
14305           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14306             if (getLangOpts().MSVCCompat) {
14307               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14308               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14309             } else
14310               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14311           } else
14312             Val = ImpCastExprToType(Val, EltTy,
14313                                     EltTy->isBooleanType() ?
14314                                     CK_IntegralToBoolean : CK_IntegralCast)
14315                     .get();
14316         } else if (getLangOpts().CPlusPlus) {
14317           // C++11 [dcl.enum]p5:
14318           //   If the underlying type is not fixed, the type of each enumerator
14319           //   is the type of its initializing value:
14320           //     - If an initializer is specified for an enumerator, the
14321           //       initializing value has the same type as the expression.
14322           EltTy = Val->getType();
14323         } else {
14324           // C99 6.7.2.2p2:
14325           //   The expression that defines the value of an enumeration constant
14326           //   shall be an integer constant expression that has a value
14327           //   representable as an int.
14328 
14329           // Complain if the value is not representable in an int.
14330           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14331             Diag(IdLoc, diag::ext_enum_value_not_int)
14332               << EnumVal.toString(10) << Val->getSourceRange()
14333               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14334           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14335             // Force the type of the expression to 'int'.
14336             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14337           }
14338           EltTy = Val->getType();
14339         }
14340       }
14341     }
14342   }
14343 
14344   if (!Val) {
14345     if (Enum->isDependentType())
14346       EltTy = Context.DependentTy;
14347     else if (!LastEnumConst) {
14348       // C++0x [dcl.enum]p5:
14349       //   If the underlying type is not fixed, the type of each enumerator
14350       //   is the type of its initializing value:
14351       //     - If no initializer is specified for the first enumerator, the
14352       //       initializing value has an unspecified integral type.
14353       //
14354       // GCC uses 'int' for its unspecified integral type, as does
14355       // C99 6.7.2.2p3.
14356       if (Enum->isFixed()) {
14357         EltTy = Enum->getIntegerType();
14358       }
14359       else {
14360         EltTy = Context.IntTy;
14361       }
14362     } else {
14363       // Assign the last value + 1.
14364       EnumVal = LastEnumConst->getInitVal();
14365       ++EnumVal;
14366       EltTy = LastEnumConst->getType();
14367 
14368       // Check for overflow on increment.
14369       if (EnumVal < LastEnumConst->getInitVal()) {
14370         // C++0x [dcl.enum]p5:
14371         //   If the underlying type is not fixed, the type of each enumerator
14372         //   is the type of its initializing value:
14373         //
14374         //     - Otherwise the type of the initializing value is the same as
14375         //       the type of the initializing value of the preceding enumerator
14376         //       unless the incremented value is not representable in that type,
14377         //       in which case the type is an unspecified integral type
14378         //       sufficient to contain the incremented value. If no such type
14379         //       exists, the program is ill-formed.
14380         QualType T = getNextLargerIntegralType(Context, EltTy);
14381         if (T.isNull() || Enum->isFixed()) {
14382           // There is no integral type larger enough to represent this
14383           // value. Complain, then allow the value to wrap around.
14384           EnumVal = LastEnumConst->getInitVal();
14385           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14386           ++EnumVal;
14387           if (Enum->isFixed())
14388             // When the underlying type is fixed, this is ill-formed.
14389             Diag(IdLoc, diag::err_enumerator_wrapped)
14390               << EnumVal.toString(10)
14391               << EltTy;
14392           else
14393             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14394               << EnumVal.toString(10);
14395         } else {
14396           EltTy = T;
14397         }
14398 
14399         // Retrieve the last enumerator's value, extent that type to the
14400         // type that is supposed to be large enough to represent the incremented
14401         // value, then increment.
14402         EnumVal = LastEnumConst->getInitVal();
14403         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14404         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14405         ++EnumVal;
14406 
14407         // If we're not in C++, diagnose the overflow of enumerator values,
14408         // which in C99 means that the enumerator value is not representable in
14409         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14410         // permits enumerator values that are representable in some larger
14411         // integral type.
14412         if (!getLangOpts().CPlusPlus && !T.isNull())
14413           Diag(IdLoc, diag::warn_enum_value_overflow);
14414       } else if (!getLangOpts().CPlusPlus &&
14415                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14416         // Enforce C99 6.7.2.2p2 even when we compute the next value.
14417         Diag(IdLoc, diag::ext_enum_value_not_int)
14418           << EnumVal.toString(10) << 1;
14419       }
14420     }
14421   }
14422 
14423   if (!EltTy->isDependentType()) {
14424     // Make the enumerator value match the signedness and size of the
14425     // enumerator's type.
14426     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14427     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14428   }
14429 
14430   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14431                                   Val, EnumVal);
14432 }
14433 
14434 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14435                                                 SourceLocation IILoc) {
14436   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14437       !getLangOpts().CPlusPlus)
14438     return SkipBodyInfo();
14439 
14440   // We have an anonymous enum definition. Look up the first enumerator to
14441   // determine if we should merge the definition with an existing one and
14442   // skip the body.
14443   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14444                                          ForRedeclaration);
14445   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14446   if (!PrevECD)
14447     return SkipBodyInfo();
14448 
14449   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14450   NamedDecl *Hidden;
14451   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14452     SkipBodyInfo Skip;
14453     Skip.Previous = Hidden;
14454     return Skip;
14455   }
14456 
14457   return SkipBodyInfo();
14458 }
14459 
14460 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14461                               SourceLocation IdLoc, IdentifierInfo *Id,
14462                               AttributeList *Attr,
14463                               SourceLocation EqualLoc, Expr *Val) {
14464   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14465   EnumConstantDecl *LastEnumConst =
14466     cast_or_null<EnumConstantDecl>(lastEnumConst);
14467 
14468   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14469   // we find one that is.
14470   S = getNonFieldDeclScope(S);
14471 
14472   // Verify that there isn't already something declared with this name in this
14473   // scope.
14474   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14475                                          ForRedeclaration);
14476   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14477     // Maybe we will complain about the shadowed template parameter.
14478     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14479     // Just pretend that we didn't see the previous declaration.
14480     PrevDecl = nullptr;
14481   }
14482 
14483   // C++ [class.mem]p15:
14484   // If T is the name of a class, then each of the following shall have a name
14485   // different from T:
14486   // - every enumerator of every member of class T that is an unscoped
14487   // enumerated type
14488   if (!TheEnumDecl->isScoped())
14489     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14490                             DeclarationNameInfo(Id, IdLoc));
14491 
14492   EnumConstantDecl *New =
14493     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14494   if (!New)
14495     return nullptr;
14496 
14497   if (PrevDecl) {
14498     // When in C++, we may get a TagDecl with the same name; in this case the
14499     // enum constant will 'hide' the tag.
14500     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14501            "Received TagDecl when not in C++!");
14502     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14503         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14504       if (isa<EnumConstantDecl>(PrevDecl))
14505         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14506       else
14507         Diag(IdLoc, diag::err_redefinition) << Id;
14508       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14509       return nullptr;
14510     }
14511   }
14512 
14513   // Process attributes.
14514   if (Attr) ProcessDeclAttributeList(S, New, Attr);
14515 
14516   // Register this decl in the current scope stack.
14517   New->setAccess(TheEnumDecl->getAccess());
14518   PushOnScopeChains(New, S);
14519 
14520   ActOnDocumentableDecl(New);
14521 
14522   return New;
14523 }
14524 
14525 // Returns true when the enum initial expression does not trigger the
14526 // duplicate enum warning.  A few common cases are exempted as follows:
14527 // Element2 = Element1
14528 // Element2 = Element1 + 1
14529 // Element2 = Element1 - 1
14530 // Where Element2 and Element1 are from the same enum.
14531 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14532   Expr *InitExpr = ECD->getInitExpr();
14533   if (!InitExpr)
14534     return true;
14535   InitExpr = InitExpr->IgnoreImpCasts();
14536 
14537   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14538     if (!BO->isAdditiveOp())
14539       return true;
14540     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14541     if (!IL)
14542       return true;
14543     if (IL->getValue() != 1)
14544       return true;
14545 
14546     InitExpr = BO->getLHS();
14547   }
14548 
14549   // This checks if the elements are from the same enum.
14550   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14551   if (!DRE)
14552     return true;
14553 
14554   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14555   if (!EnumConstant)
14556     return true;
14557 
14558   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14559       Enum)
14560     return true;
14561 
14562   return false;
14563 }
14564 
14565 namespace {
14566 struct DupKey {
14567   int64_t val;
14568   bool isTombstoneOrEmptyKey;
14569   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14570     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14571 };
14572 
14573 static DupKey GetDupKey(const llvm::APSInt& Val) {
14574   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14575                 false);
14576 }
14577 
14578 struct DenseMapInfoDupKey {
14579   static DupKey getEmptyKey() { return DupKey(0, true); }
14580   static DupKey getTombstoneKey() { return DupKey(1, true); }
14581   static unsigned getHashValue(const DupKey Key) {
14582     return (unsigned)(Key.val * 37);
14583   }
14584   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14585     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14586            LHS.val == RHS.val;
14587   }
14588 };
14589 } // end anonymous namespace
14590 
14591 // Emits a warning when an element is implicitly set a value that
14592 // a previous element has already been set to.
14593 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14594                                         EnumDecl *Enum,
14595                                         QualType EnumType) {
14596   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14597     return;
14598   // Avoid anonymous enums
14599   if (!Enum->getIdentifier())
14600     return;
14601 
14602   // Only check for small enums.
14603   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14604     return;
14605 
14606   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14607   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14608 
14609   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14610   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14611           ValueToVectorMap;
14612 
14613   DuplicatesVector DupVector;
14614   ValueToVectorMap EnumMap;
14615 
14616   // Populate the EnumMap with all values represented by enum constants without
14617   // an initialier.
14618   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14619     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14620 
14621     // Null EnumConstantDecl means a previous diagnostic has been emitted for
14622     // this constant.  Skip this enum since it may be ill-formed.
14623     if (!ECD) {
14624       return;
14625     }
14626 
14627     if (ECD->getInitExpr())
14628       continue;
14629 
14630     DupKey Key = GetDupKey(ECD->getInitVal());
14631     DeclOrVector &Entry = EnumMap[Key];
14632 
14633     // First time encountering this value.
14634     if (Entry.isNull())
14635       Entry = ECD;
14636   }
14637 
14638   // Create vectors for any values that has duplicates.
14639   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14640     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14641     if (!ValidDuplicateEnum(ECD, Enum))
14642       continue;
14643 
14644     DupKey Key = GetDupKey(ECD->getInitVal());
14645 
14646     DeclOrVector& Entry = EnumMap[Key];
14647     if (Entry.isNull())
14648       continue;
14649 
14650     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14651       // Ensure constants are different.
14652       if (D == ECD)
14653         continue;
14654 
14655       // Create new vector and push values onto it.
14656       ECDVector *Vec = new ECDVector();
14657       Vec->push_back(D);
14658       Vec->push_back(ECD);
14659 
14660       // Update entry to point to the duplicates vector.
14661       Entry = Vec;
14662 
14663       // Store the vector somewhere we can consult later for quick emission of
14664       // diagnostics.
14665       DupVector.push_back(Vec);
14666       continue;
14667     }
14668 
14669     ECDVector *Vec = Entry.get<ECDVector*>();
14670     // Make sure constants are not added more than once.
14671     if (*Vec->begin() == ECD)
14672       continue;
14673 
14674     Vec->push_back(ECD);
14675   }
14676 
14677   // Emit diagnostics.
14678   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14679                                   DupVectorEnd = DupVector.end();
14680        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14681     ECDVector *Vec = *DupVectorIter;
14682     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14683 
14684     // Emit warning for one enum constant.
14685     ECDVector::iterator I = Vec->begin();
14686     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14687       << (*I)->getName() << (*I)->getInitVal().toString(10)
14688       << (*I)->getSourceRange();
14689     ++I;
14690 
14691     // Emit one note for each of the remaining enum constants with
14692     // the same value.
14693     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14694       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14695         << (*I)->getName() << (*I)->getInitVal().toString(10)
14696         << (*I)->getSourceRange();
14697     delete Vec;
14698   }
14699 }
14700 
14701 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14702                              bool AllowMask) const {
14703   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14704   assert(ED->isCompleteDefinition() && "expected enum definition");
14705 
14706   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14707   llvm::APInt &FlagBits = R.first->second;
14708 
14709   if (R.second) {
14710     for (auto *E : ED->enumerators()) {
14711       const auto &EVal = E->getInitVal();
14712       // Only single-bit enumerators introduce new flag values.
14713       if (EVal.isPowerOf2())
14714         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14715     }
14716   }
14717 
14718   // A value is in a flag enum if either its bits are a subset of the enum's
14719   // flag bits (the first condition) or we are allowing masks and the same is
14720   // true of its complement (the second condition). When masks are allowed, we
14721   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14722   //
14723   // While it's true that any value could be used as a mask, the assumption is
14724   // that a mask will have all of the insignificant bits set. Anything else is
14725   // likely a logic error.
14726   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14727   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14728 }
14729 
14730 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14731                          SourceLocation RBraceLoc, Decl *EnumDeclX,
14732                          ArrayRef<Decl *> Elements,
14733                          Scope *S, AttributeList *Attr) {
14734   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14735   QualType EnumType = Context.getTypeDeclType(Enum);
14736 
14737   if (Attr)
14738     ProcessDeclAttributeList(S, Enum, Attr);
14739 
14740   if (Enum->isDependentType()) {
14741     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14742       EnumConstantDecl *ECD =
14743         cast_or_null<EnumConstantDecl>(Elements[i]);
14744       if (!ECD) continue;
14745 
14746       ECD->setType(EnumType);
14747     }
14748 
14749     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14750     return;
14751   }
14752 
14753   // TODO: If the result value doesn't fit in an int, it must be a long or long
14754   // long value.  ISO C does not support this, but GCC does as an extension,
14755   // emit a warning.
14756   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14757   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14758   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14759 
14760   // Verify that all the values are okay, compute the size of the values, and
14761   // reverse the list.
14762   unsigned NumNegativeBits = 0;
14763   unsigned NumPositiveBits = 0;
14764 
14765   // Keep track of whether all elements have type int.
14766   bool AllElementsInt = true;
14767 
14768   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14769     EnumConstantDecl *ECD =
14770       cast_or_null<EnumConstantDecl>(Elements[i]);
14771     if (!ECD) continue;  // Already issued a diagnostic.
14772 
14773     const llvm::APSInt &InitVal = ECD->getInitVal();
14774 
14775     // Keep track of the size of positive and negative values.
14776     if (InitVal.isUnsigned() || InitVal.isNonNegative())
14777       NumPositiveBits = std::max(NumPositiveBits,
14778                                  (unsigned)InitVal.getActiveBits());
14779     else
14780       NumNegativeBits = std::max(NumNegativeBits,
14781                                  (unsigned)InitVal.getMinSignedBits());
14782 
14783     // Keep track of whether every enum element has type int (very commmon).
14784     if (AllElementsInt)
14785       AllElementsInt = ECD->getType() == Context.IntTy;
14786   }
14787 
14788   // Figure out the type that should be used for this enum.
14789   QualType BestType;
14790   unsigned BestWidth;
14791 
14792   // C++0x N3000 [conv.prom]p3:
14793   //   An rvalue of an unscoped enumeration type whose underlying
14794   //   type is not fixed can be converted to an rvalue of the first
14795   //   of the following types that can represent all the values of
14796   //   the enumeration: int, unsigned int, long int, unsigned long
14797   //   int, long long int, or unsigned long long int.
14798   // C99 6.4.4.3p2:
14799   //   An identifier declared as an enumeration constant has type int.
14800   // The C99 rule is modified by a gcc extension
14801   QualType BestPromotionType;
14802 
14803   bool Packed = Enum->hasAttr<PackedAttr>();
14804   // -fshort-enums is the equivalent to specifying the packed attribute on all
14805   // enum definitions.
14806   if (LangOpts.ShortEnums)
14807     Packed = true;
14808 
14809   if (Enum->isFixed()) {
14810     BestType = Enum->getIntegerType();
14811     if (BestType->isPromotableIntegerType())
14812       BestPromotionType = Context.getPromotedIntegerType(BestType);
14813     else
14814       BestPromotionType = BestType;
14815 
14816     BestWidth = Context.getIntWidth(BestType);
14817   }
14818   else if (NumNegativeBits) {
14819     // If there is a negative value, figure out the smallest integer type (of
14820     // int/long/longlong) that fits.
14821     // If it's packed, check also if it fits a char or a short.
14822     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14823       BestType = Context.SignedCharTy;
14824       BestWidth = CharWidth;
14825     } else if (Packed && NumNegativeBits <= ShortWidth &&
14826                NumPositiveBits < ShortWidth) {
14827       BestType = Context.ShortTy;
14828       BestWidth = ShortWidth;
14829     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14830       BestType = Context.IntTy;
14831       BestWidth = IntWidth;
14832     } else {
14833       BestWidth = Context.getTargetInfo().getLongWidth();
14834 
14835       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14836         BestType = Context.LongTy;
14837       } else {
14838         BestWidth = Context.getTargetInfo().getLongLongWidth();
14839 
14840         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14841           Diag(Enum->getLocation(), diag::ext_enum_too_large);
14842         BestType = Context.LongLongTy;
14843       }
14844     }
14845     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14846   } else {
14847     // If there is no negative value, figure out the smallest type that fits
14848     // all of the enumerator values.
14849     // If it's packed, check also if it fits a char or a short.
14850     if (Packed && NumPositiveBits <= CharWidth) {
14851       BestType = Context.UnsignedCharTy;
14852       BestPromotionType = Context.IntTy;
14853       BestWidth = CharWidth;
14854     } else if (Packed && NumPositiveBits <= ShortWidth) {
14855       BestType = Context.UnsignedShortTy;
14856       BestPromotionType = Context.IntTy;
14857       BestWidth = ShortWidth;
14858     } else if (NumPositiveBits <= IntWidth) {
14859       BestType = Context.UnsignedIntTy;
14860       BestWidth = IntWidth;
14861       BestPromotionType
14862         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14863                            ? Context.UnsignedIntTy : Context.IntTy;
14864     } else if (NumPositiveBits <=
14865                (BestWidth = Context.getTargetInfo().getLongWidth())) {
14866       BestType = Context.UnsignedLongTy;
14867       BestPromotionType
14868         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14869                            ? Context.UnsignedLongTy : Context.LongTy;
14870     } else {
14871       BestWidth = Context.getTargetInfo().getLongLongWidth();
14872       assert(NumPositiveBits <= BestWidth &&
14873              "How could an initializer get larger than ULL?");
14874       BestType = Context.UnsignedLongLongTy;
14875       BestPromotionType
14876         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14877                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
14878     }
14879   }
14880 
14881   // Loop over all of the enumerator constants, changing their types to match
14882   // the type of the enum if needed.
14883   for (auto *D : Elements) {
14884     auto *ECD = cast_or_null<EnumConstantDecl>(D);
14885     if (!ECD) continue;  // Already issued a diagnostic.
14886 
14887     // Standard C says the enumerators have int type, but we allow, as an
14888     // extension, the enumerators to be larger than int size.  If each
14889     // enumerator value fits in an int, type it as an int, otherwise type it the
14890     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
14891     // that X has type 'int', not 'unsigned'.
14892 
14893     // Determine whether the value fits into an int.
14894     llvm::APSInt InitVal = ECD->getInitVal();
14895 
14896     // If it fits into an integer type, force it.  Otherwise force it to match
14897     // the enum decl type.
14898     QualType NewTy;
14899     unsigned NewWidth;
14900     bool NewSign;
14901     if (!getLangOpts().CPlusPlus &&
14902         !Enum->isFixed() &&
14903         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14904       NewTy = Context.IntTy;
14905       NewWidth = IntWidth;
14906       NewSign = true;
14907     } else if (ECD->getType() == BestType) {
14908       // Already the right type!
14909       if (getLangOpts().CPlusPlus)
14910         // C++ [dcl.enum]p4: Following the closing brace of an
14911         // enum-specifier, each enumerator has the type of its
14912         // enumeration.
14913         ECD->setType(EnumType);
14914       continue;
14915     } else {
14916       NewTy = BestType;
14917       NewWidth = BestWidth;
14918       NewSign = BestType->isSignedIntegerOrEnumerationType();
14919     }
14920 
14921     // Adjust the APSInt value.
14922     InitVal = InitVal.extOrTrunc(NewWidth);
14923     InitVal.setIsSigned(NewSign);
14924     ECD->setInitVal(InitVal);
14925 
14926     // Adjust the Expr initializer and type.
14927     if (ECD->getInitExpr() &&
14928         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14929       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14930                                                 CK_IntegralCast,
14931                                                 ECD->getInitExpr(),
14932                                                 /*base paths*/ nullptr,
14933                                                 VK_RValue));
14934     if (getLangOpts().CPlusPlus)
14935       // C++ [dcl.enum]p4: Following the closing brace of an
14936       // enum-specifier, each enumerator has the type of its
14937       // enumeration.
14938       ECD->setType(EnumType);
14939     else
14940       ECD->setType(NewTy);
14941   }
14942 
14943   Enum->completeDefinition(BestType, BestPromotionType,
14944                            NumPositiveBits, NumNegativeBits);
14945 
14946   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14947 
14948   if (Enum->hasAttr<FlagEnumAttr>()) {
14949     for (Decl *D : Elements) {
14950       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14951       if (!ECD) continue;  // Already issued a diagnostic.
14952 
14953       llvm::APSInt InitVal = ECD->getInitVal();
14954       if (InitVal != 0 && !InitVal.isPowerOf2() &&
14955           !IsValueInFlagEnum(Enum, InitVal, true))
14956         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14957           << ECD << Enum;
14958     }
14959   }
14960 
14961   // Now that the enum type is defined, ensure it's not been underaligned.
14962   if (Enum->hasAttrs())
14963     CheckAlignasUnderalignment(Enum);
14964 }
14965 
14966 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
14967                                   SourceLocation StartLoc,
14968                                   SourceLocation EndLoc) {
14969   StringLiteral *AsmString = cast<StringLiteral>(expr);
14970 
14971   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
14972                                                    AsmString, StartLoc,
14973                                                    EndLoc);
14974   CurContext->addDecl(New);
14975   return New;
14976 }
14977 
14978 static void checkModuleImportContext(Sema &S, Module *M,
14979                                      SourceLocation ImportLoc, DeclContext *DC,
14980                                      bool FromInclude = false) {
14981   SourceLocation ExternCLoc;
14982 
14983   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14984     switch (LSD->getLanguage()) {
14985     case LinkageSpecDecl::lang_c:
14986       if (ExternCLoc.isInvalid())
14987         ExternCLoc = LSD->getLocStart();
14988       break;
14989     case LinkageSpecDecl::lang_cxx:
14990       break;
14991     }
14992     DC = LSD->getParent();
14993   }
14994 
14995   while (isa<LinkageSpecDecl>(DC))
14996     DC = DC->getParent();
14997 
14998   if (!isa<TranslationUnitDecl>(DC)) {
14999     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15000                           ? diag::ext_module_import_not_at_top_level_noop
15001                           : diag::err_module_import_not_at_top_level_fatal)
15002         << M->getFullModuleName() << DC;
15003     S.Diag(cast<Decl>(DC)->getLocStart(),
15004            diag::note_module_import_not_at_top_level) << DC;
15005   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15006     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15007       << M->getFullModuleName();
15008     S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
15009   }
15010 }
15011 
15012 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
15013   return checkModuleImportContext(*this, M, ImportLoc, CurContext);
15014 }
15015 
15016 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
15017                                    SourceLocation ImportLoc,
15018                                    ModuleIdPath Path) {
15019   Module *Mod =
15020       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15021                                    /*IsIncludeDirective=*/false);
15022   if (!Mod)
15023     return true;
15024 
15025   VisibleModules.setVisible(Mod, ImportLoc);
15026 
15027   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15028 
15029   // FIXME: we should support importing a submodule within a different submodule
15030   // of the same top-level module. Until we do, make it an error rather than
15031   // silently ignoring the import.
15032   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
15033     Diag(ImportLoc, getLangOpts().CompilingModule
15034                         ? diag::err_module_self_import
15035                         : diag::err_module_import_in_implementation)
15036         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15037 
15038   SmallVector<SourceLocation, 2> IdentifierLocs;
15039   Module *ModCheck = Mod;
15040   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15041     // If we've run out of module parents, just drop the remaining identifiers.
15042     // We need the length to be consistent.
15043     if (!ModCheck)
15044       break;
15045     ModCheck = ModCheck->Parent;
15046 
15047     IdentifierLocs.push_back(Path[I].second);
15048   }
15049 
15050   ImportDecl *Import = ImportDecl::Create(Context,
15051                                           Context.getTranslationUnitDecl(),
15052                                           AtLoc.isValid()? AtLoc : ImportLoc,
15053                                           Mod, IdentifierLocs);
15054   Context.getTranslationUnitDecl()->addDecl(Import);
15055   return Import;
15056 }
15057 
15058 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15059   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15060 
15061   // Determine whether we're in the #include buffer for a module. The #includes
15062   // in that buffer do not qualify as module imports; they're just an
15063   // implementation detail of us building the module.
15064   //
15065   // FIXME: Should we even get ActOnModuleInclude calls for those?
15066   bool IsInModuleIncludes =
15067       TUKind == TU_Module &&
15068       getSourceManager().isWrittenInMainFile(DirectiveLoc);
15069 
15070   // Similarly, if we're in the implementation of a module, don't
15071   // synthesize an illegal module import. FIXME: Why not?
15072   bool ShouldAddImport =
15073       !IsInModuleIncludes &&
15074       (getLangOpts().CompilingModule ||
15075        getLangOpts().CurrentModule.empty() ||
15076        getLangOpts().CurrentModule != Mod->getTopLevelModuleName());
15077 
15078   // If this module import was due to an inclusion directive, create an
15079   // implicit import declaration to capture it in the AST.
15080   if (ShouldAddImport) {
15081     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15082     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15083                                                      DirectiveLoc, Mod,
15084                                                      DirectiveLoc);
15085     TU->addDecl(ImportD);
15086     Consumer.HandleImplicitImportDecl(ImportD);
15087   }
15088 
15089   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15090   VisibleModules.setVisible(Mod, DirectiveLoc);
15091 }
15092 
15093 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15094   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15095 
15096   if (getLangOpts().ModulesLocalVisibility)
15097     VisibleModulesStack.push_back(std::move(VisibleModules));
15098   VisibleModules.setVisible(Mod, DirectiveLoc);
15099 }
15100 
15101 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
15102   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15103 
15104   if (getLangOpts().ModulesLocalVisibility) {
15105     VisibleModules = std::move(VisibleModulesStack.back());
15106     VisibleModulesStack.pop_back();
15107     VisibleModules.setVisible(Mod, DirectiveLoc);
15108     // Leaving a module hides namespace names, so our visible namespace cache
15109     // is now out of date.
15110     VisibleNamespaceCache.clear();
15111   }
15112 }
15113 
15114 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15115                                                       Module *Mod) {
15116   // Bail if we're not allowed to implicitly import a module here.
15117   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15118     return;
15119 
15120   // Create the implicit import declaration.
15121   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15122   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15123                                                    Loc, Mod, Loc);
15124   TU->addDecl(ImportD);
15125   Consumer.HandleImplicitImportDecl(ImportD);
15126 
15127   // Make the module visible.
15128   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15129   VisibleModules.setVisible(Mod, Loc);
15130 }
15131 
15132 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15133                                       IdentifierInfo* AliasName,
15134                                       SourceLocation PragmaLoc,
15135                                       SourceLocation NameLoc,
15136                                       SourceLocation AliasNameLoc) {
15137   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15138                                          LookupOrdinaryName);
15139   AsmLabelAttr *Attr =
15140       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15141 
15142   // If a declaration that:
15143   // 1) declares a function or a variable
15144   // 2) has external linkage
15145   // already exists, add a label attribute to it.
15146   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15147     if (isDeclExternC(PrevDecl))
15148       PrevDecl->addAttr(Attr);
15149     else
15150       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15151           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15152   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15153   } else
15154     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15155 }
15156 
15157 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15158                              SourceLocation PragmaLoc,
15159                              SourceLocation NameLoc) {
15160   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15161 
15162   if (PrevDecl) {
15163     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15164   } else {
15165     (void)WeakUndeclaredIdentifiers.insert(
15166       std::pair<IdentifierInfo*,WeakInfo>
15167         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15168   }
15169 }
15170 
15171 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15172                                 IdentifierInfo* AliasName,
15173                                 SourceLocation PragmaLoc,
15174                                 SourceLocation NameLoc,
15175                                 SourceLocation AliasNameLoc) {
15176   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15177                                     LookupOrdinaryName);
15178   WeakInfo W = WeakInfo(Name, NameLoc);
15179 
15180   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15181     if (!PrevDecl->hasAttr<AliasAttr>())
15182       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15183         DeclApplyPragmaWeak(TUScope, ND, W);
15184   } else {
15185     (void)WeakUndeclaredIdentifiers.insert(
15186       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15187   }
15188 }
15189 
15190 Decl *Sema::getObjCDeclContext() const {
15191   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15192 }
15193 
15194 AvailabilityResult Sema::getCurContextAvailability() const {
15195   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
15196   if (!D)
15197     return AR_Available;
15198 
15199   // If we are within an Objective-C method, we should consult
15200   // both the availability of the method as well as the
15201   // enclosing class.  If the class is (say) deprecated,
15202   // the entire method is considered deprecated from the
15203   // purpose of checking if the current context is deprecated.
15204   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
15205     AvailabilityResult R = MD->getAvailability();
15206     if (R != AR_Available)
15207       return R;
15208     D = MD->getClassInterface();
15209   }
15210   // If we are within an Objective-c @implementation, it
15211   // gets the same availability context as the @interface.
15212   else if (const ObjCImplementationDecl *ID =
15213             dyn_cast<ObjCImplementationDecl>(D)) {
15214     D = ID->getClassInterface();
15215   }
15216   // Recover from user error.
15217   return D ? D->getAvailability() : AR_Available;
15218 }
15219