]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp
Merge ^/head r317281 through r317502.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaDecl.cpp
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 "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.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         AllowTemplates(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 = AllowTemplates && getAsTypeTemplateDecl(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 AllowTemplates;
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                              bool IsClassTemplateDeductionContext,
256                              IdentifierInfo **CorrectedII) {
257   // FIXME: Consider allowing this outside C++1z mode as an extension.
258   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
259                               getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
260                               !isClassName && !HasTrailingDot;
261
262   // Determine where we will perform name lookup.
263   DeclContext *LookupCtx = nullptr;
264   if (ObjectTypePtr) {
265     QualType ObjectType = ObjectTypePtr.get();
266     if (ObjectType->isRecordType())
267       LookupCtx = computeDeclContext(ObjectType);
268   } else if (SS && SS->isNotEmpty()) {
269     LookupCtx = computeDeclContext(*SS, false);
270
271     if (!LookupCtx) {
272       if (isDependentScopeSpecifier(*SS)) {
273         // C++ [temp.res]p3:
274         //   A qualified-id that refers to a type and in which the
275         //   nested-name-specifier depends on a template-parameter (14.6.2)
276         //   shall be prefixed by the keyword typename to indicate that the
277         //   qualified-id denotes a type, forming an
278         //   elaborated-type-specifier (7.1.5.3).
279         //
280         // We therefore do not perform any name lookup if the result would
281         // refer to a member of an unknown specialization.
282         if (!isClassName && !IsCtorOrDtorName)
283           return nullptr;
284
285         // We know from the grammar that this name refers to a type,
286         // so build a dependent node to describe the type.
287         if (WantNontrivialTypeSourceInfo)
288           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
289
290         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
291         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
292                                        II, NameLoc);
293         return ParsedType::make(T);
294       }
295
296       return nullptr;
297     }
298
299     if (!LookupCtx->isDependentContext() &&
300         RequireCompleteDeclContext(*SS, LookupCtx))
301       return nullptr;
302   }
303
304   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
305   // lookup for class-names.
306   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
307                                       LookupOrdinaryName;
308   LookupResult Result(*this, &II, NameLoc, Kind);
309   if (LookupCtx) {
310     // Perform "qualified" name lookup into the declaration context we
311     // computed, which is either the type of the base of a member access
312     // expression or the declaration context associated with a prior
313     // nested-name-specifier.
314     LookupQualifiedName(Result, LookupCtx);
315
316     if (ObjectTypePtr && Result.empty()) {
317       // C++ [basic.lookup.classref]p3:
318       //   If the unqualified-id is ~type-name, the type-name is looked up
319       //   in the context of the entire postfix-expression. If the type T of
320       //   the object expression is of a class type C, the type-name is also
321       //   looked up in the scope of class C. At least one of the lookups shall
322       //   find a name that refers to (possibly cv-qualified) T.
323       LookupName(Result, S);
324     }
325   } else {
326     // Perform unqualified name lookup.
327     LookupName(Result, S);
328
329     // For unqualified lookup in a class template in MSVC mode, look into
330     // dependent base classes where the primary class template is known.
331     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
332       if (ParsedType TypeInBase =
333               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
334         return TypeInBase;
335     }
336   }
337
338   NamedDecl *IIDecl = nullptr;
339   switch (Result.getResultKind()) {
340   case LookupResult::NotFound:
341   case LookupResult::NotFoundInCurrentInstantiation:
342     if (CorrectedII) {
343       TypoCorrection Correction =
344           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
345                       llvm::make_unique<TypeNameValidatorCCC>(
346                           true, isClassName, AllowDeducedTemplate),
347                       CTK_ErrorRecovery);
348       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
349       TemplateTy Template;
350       bool MemberOfUnknownSpecialization;
351       UnqualifiedId TemplateName;
352       TemplateName.setIdentifier(NewII, NameLoc);
353       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
354       CXXScopeSpec NewSS, *NewSSPtr = SS;
355       if (SS && NNS) {
356         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
357         NewSSPtr = &NewSS;
358       }
359       if (Correction && (NNS || NewII != &II) &&
360           // Ignore a correction to a template type as the to-be-corrected
361           // identifier is not a template (typo correction for template names
362           // is handled elsewhere).
363           !(getLangOpts().CPlusPlus && NewSSPtr &&
364             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
365                            Template, MemberOfUnknownSpecialization))) {
366         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
367                                     isClassName, HasTrailingDot, ObjectTypePtr,
368                                     IsCtorOrDtorName,
369                                     WantNontrivialTypeSourceInfo,
370                                     IsClassTemplateDeductionContext);
371         if (Ty) {
372           diagnoseTypo(Correction,
373                        PDiag(diag::err_unknown_type_or_class_name_suggest)
374                          << Result.getLookupName() << isClassName);
375           if (SS && NNS)
376             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
377           *CorrectedII = NewII;
378           return Ty;
379         }
380       }
381     }
382     // If typo correction failed or was not performed, fall through
383   case LookupResult::FoundOverloaded:
384   case LookupResult::FoundUnresolvedValue:
385     Result.suppressDiagnostics();
386     return nullptr;
387
388   case LookupResult::Ambiguous:
389     // Recover from type-hiding ambiguities by hiding the type.  We'll
390     // do the lookup again when looking for an object, and we can
391     // diagnose the error then.  If we don't do this, then the error
392     // about hiding the type will be immediately followed by an error
393     // that only makes sense if the identifier was treated like a type.
394     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
395       Result.suppressDiagnostics();
396       return nullptr;
397     }
398
399     // Look to see if we have a type anywhere in the list of results.
400     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
401          Res != ResEnd; ++Res) {
402       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
403           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
404         if (!IIDecl ||
405             (*Res)->getLocation().getRawEncoding() <
406               IIDecl->getLocation().getRawEncoding())
407           IIDecl = *Res;
408       }
409     }
410
411     if (!IIDecl) {
412       // None of the entities we found is a type, so there is no way
413       // to even assume that the result is a type. In this case, don't
414       // complain about the ambiguity. The parser will either try to
415       // perform this lookup again (e.g., as an object name), which
416       // will produce the ambiguity, or will complain that it expected
417       // a type name.
418       Result.suppressDiagnostics();
419       return nullptr;
420     }
421
422     // We found a type within the ambiguous lookup; diagnose the
423     // ambiguity and then return that type. This might be the right
424     // answer, or it might not be, but it suppresses any attempt to
425     // perform the name lookup again.
426     break;
427
428   case LookupResult::Found:
429     IIDecl = Result.getFoundDecl();
430     break;
431   }
432
433   assert(IIDecl && "Didn't find decl");
434
435   QualType T;
436   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
437     // C++ [class.qual]p2: A lookup that would find the injected-class-name
438     // instead names the constructors of the class, except when naming a class.
439     // This is ill-formed when we're not actually forming a ctor or dtor name.
440     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
441     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
442     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
443         FoundRD->isInjectedClassName() &&
444         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
445       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
446           << &II << /*Type*/1;
447
448     DiagnoseUseOfDecl(IIDecl, NameLoc);
449
450     T = Context.getTypeDeclType(TD);
451     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
452   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
453     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
454     if (!HasTrailingDot)
455       T = Context.getObjCInterfaceType(IDecl);
456   } else if (AllowDeducedTemplate) {
457     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
458       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
459                                                        QualType(), false);
460   }
461
462   if (T.isNull()) {
463     // If it's not plausibly a type, suppress diagnostics.
464     Result.suppressDiagnostics();
465     return nullptr;
466   }
467
468   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
469   // constructor or destructor name (in such a case, the scope specifier
470   // will be attached to the enclosing Expr or Decl node).
471   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
472       !isa<ObjCInterfaceDecl>(IIDecl)) {
473     if (WantNontrivialTypeSourceInfo) {
474       // Construct a type with type-source information.
475       TypeLocBuilder Builder;
476       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
477
478       T = getElaboratedType(ETK_None, *SS, T);
479       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
480       ElabTL.setElaboratedKeywordLoc(SourceLocation());
481       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
482       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
483     } else {
484       T = getElaboratedType(ETK_None, *SS, T);
485     }
486   }
487
488   return ParsedType::make(T);
489 }
490
491 // Builds a fake NNS for the given decl context.
492 static NestedNameSpecifier *
493 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
494   for (;; DC = DC->getLookupParent()) {
495     DC = DC->getPrimaryContext();
496     auto *ND = dyn_cast<NamespaceDecl>(DC);
497     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
498       return NestedNameSpecifier::Create(Context, nullptr, ND);
499     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
500       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
501                                          RD->getTypeForDecl());
502     else if (isa<TranslationUnitDecl>(DC))
503       return NestedNameSpecifier::GlobalSpecifier(Context);
504   }
505   llvm_unreachable("something isn't in TU scope?");
506 }
507
508 /// Find the parent class with dependent bases of the innermost enclosing method
509 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
510 /// up allowing unqualified dependent type names at class-level, which MSVC
511 /// correctly rejects.
512 static const CXXRecordDecl *
513 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
514   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
515     DC = DC->getPrimaryContext();
516     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
517       if (MD->getParent()->hasAnyDependentBases())
518         return MD->getParent();
519   }
520   return nullptr;
521 }
522
523 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
524                                           SourceLocation NameLoc,
525                                           bool IsTemplateTypeArg) {
526   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
527
528   NestedNameSpecifier *NNS = nullptr;
529   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
530     // If we weren't able to parse a default template argument, delay lookup
531     // until instantiation time by making a non-dependent DependentTypeName. We
532     // pretend we saw a NestedNameSpecifier referring to the current scope, and
533     // lookup is retried.
534     // FIXME: This hurts our diagnostic quality, since we get errors like "no
535     // type named 'Foo' in 'current_namespace'" when the user didn't write any
536     // name specifiers.
537     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
538     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
539   } else if (const CXXRecordDecl *RD =
540                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
541     // Build a DependentNameType that will perform lookup into RD at
542     // instantiation time.
543     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
544                                       RD->getTypeForDecl());
545
546     // Diagnose that this identifier was undeclared, and retry the lookup during
547     // template instantiation.
548     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
549                                                                       << RD;
550   } else {
551     // This is not a situation that we should recover from.
552     return ParsedType();
553   }
554
555   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
556
557   // Build type location information.  We synthesized the qualifier, so we have
558   // to build a fake NestedNameSpecifierLoc.
559   NestedNameSpecifierLocBuilder NNSLocBuilder;
560   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
561   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
562
563   TypeLocBuilder Builder;
564   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
565   DepTL.setNameLoc(NameLoc);
566   DepTL.setElaboratedKeywordLoc(SourceLocation());
567   DepTL.setQualifierLoc(QualifierLoc);
568   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
569 }
570
571 /// isTagName() - This method is called *for error recovery purposes only*
572 /// to determine if the specified name is a valid tag name ("struct foo").  If
573 /// so, this returns the TST for the tag corresponding to it (TST_enum,
574 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
575 /// cases in C where the user forgot to specify the tag.
576 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
577   // Do a tag name lookup in this scope.
578   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
579   LookupName(R, S, false);
580   R.suppressDiagnostics();
581   if (R.getResultKind() == LookupResult::Found)
582     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
583       switch (TD->getTagKind()) {
584       case TTK_Struct: return DeclSpec::TST_struct;
585       case TTK_Interface: return DeclSpec::TST_interface;
586       case TTK_Union:  return DeclSpec::TST_union;
587       case TTK_Class:  return DeclSpec::TST_class;
588       case TTK_Enum:   return DeclSpec::TST_enum;
589       }
590     }
591
592   return DeclSpec::TST_unspecified;
593 }
594
595 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
596 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
597 /// then downgrade the missing typename error to a warning.
598 /// This is needed for MSVC compatibility; Example:
599 /// @code
600 /// template<class T> class A {
601 /// public:
602 ///   typedef int TYPE;
603 /// };
604 /// template<class T> class B : public A<T> {
605 /// public:
606 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
607 /// };
608 /// @endcode
609 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
610   if (CurContext->isRecord()) {
611     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
612       return true;
613
614     const Type *Ty = SS->getScopeRep()->getAsType();
615
616     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
617     for (const auto &Base : RD->bases())
618       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
619         return true;
620     return S->isFunctionPrototypeScope();
621   }
622   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
623 }
624
625 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
626                                    SourceLocation IILoc,
627                                    Scope *S,
628                                    CXXScopeSpec *SS,
629                                    ParsedType &SuggestedType,
630                                    bool AllowClassTemplates) {
631   // Don't report typename errors for editor placeholders.
632   if (II->isEditorPlaceholder())
633     return;
634   // We don't have anything to suggest (yet).
635   SuggestedType = nullptr;
636
637   // There may have been a typo in the name of the type. Look up typo
638   // results, in case we have something that we can suggest.
639   if (TypoCorrection Corrected =
640           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
641                       llvm::make_unique<TypeNameValidatorCCC>(
642                           false, false, AllowClassTemplates),
643                       CTK_ErrorRecovery)) {
644     if (Corrected.isKeyword()) {
645       // We corrected to a keyword.
646       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
647       II = Corrected.getCorrectionAsIdentifierInfo();
648     } else {
649       // We found a similarly-named type or interface; suggest that.
650       if (!SS || !SS->isSet()) {
651         diagnoseTypo(Corrected,
652                      PDiag(diag::err_unknown_typename_suggest) << II);
653       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
654         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
655         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
656                                 II->getName().equals(CorrectedStr);
657         diagnoseTypo(Corrected,
658                      PDiag(diag::err_unknown_nested_typename_suggest)
659                        << II << DC << DroppedSpecifier << SS->getRange());
660       } else {
661         llvm_unreachable("could not have corrected a typo here");
662       }
663
664       CXXScopeSpec tmpSS;
665       if (Corrected.getCorrectionSpecifier())
666         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
667                           SourceRange(IILoc));
668       // FIXME: Support class template argument deduction here.
669       SuggestedType =
670           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
671                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
672                       /*IsCtorOrDtorName=*/false,
673                       /*NonTrivialTypeSourceInfo=*/true);
674     }
675     return;
676   }
677
678   if (getLangOpts().CPlusPlus) {
679     // See if II is a class template that the user forgot to pass arguments to.
680     UnqualifiedId Name;
681     Name.setIdentifier(II, IILoc);
682     CXXScopeSpec EmptySS;
683     TemplateTy TemplateResult;
684     bool MemberOfUnknownSpecialization;
685     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
686                        Name, nullptr, true, TemplateResult,
687                        MemberOfUnknownSpecialization) == TNK_Type_template) {
688       TemplateName TplName = TemplateResult.get();
689       Diag(IILoc, diag::err_template_missing_args)
690         << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
691       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
692         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
693           << TplDecl->getTemplateParameters()->getSourceRange();
694       }
695       return;
696     }
697   }
698
699   // FIXME: Should we move the logic that tries to recover from a missing tag
700   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
701
702   if (!SS || (!SS->isSet() && !SS->isInvalid()))
703     Diag(IILoc, diag::err_unknown_typename) << II;
704   else if (DeclContext *DC = computeDeclContext(*SS, false))
705     Diag(IILoc, diag::err_typename_nested_not_found)
706       << II << DC << SS->getRange();
707   else if (isDependentScopeSpecifier(*SS)) {
708     unsigned DiagID = diag::err_typename_missing;
709     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
710       DiagID = diag::ext_typename_missing;
711
712     Diag(SS->getRange().getBegin(), DiagID)
713       << SS->getScopeRep() << II->getName()
714       << SourceRange(SS->getRange().getBegin(), IILoc)
715       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
716     SuggestedType = ActOnTypenameType(S, SourceLocation(),
717                                       *SS, *II, IILoc).get();
718   } else {
719     assert(SS && SS->isInvalid() &&
720            "Invalid scope specifier has already been diagnosed");
721   }
722 }
723
724 /// \brief Determine whether the given result set contains either a type name
725 /// or
726 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
727   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
728                        NextToken.is(tok::less);
729
730   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
731     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
732       return true;
733
734     if (CheckTemplate && isa<TemplateDecl>(*I))
735       return true;
736   }
737
738   return false;
739 }
740
741 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
742                                     Scope *S, CXXScopeSpec &SS,
743                                     IdentifierInfo *&Name,
744                                     SourceLocation NameLoc) {
745   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
746   SemaRef.LookupParsedName(R, S, &SS);
747   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
748     StringRef FixItTagName;
749     switch (Tag->getTagKind()) {
750       case TTK_Class:
751         FixItTagName = "class ";
752         break;
753
754       case TTK_Enum:
755         FixItTagName = "enum ";
756         break;
757
758       case TTK_Struct:
759         FixItTagName = "struct ";
760         break;
761
762       case TTK_Interface:
763         FixItTagName = "__interface ";
764         break;
765
766       case TTK_Union:
767         FixItTagName = "union ";
768         break;
769     }
770
771     StringRef TagName = FixItTagName.drop_back();
772     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
773       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
774       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
775
776     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
777          I != IEnd; ++I)
778       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
779         << Name << TagName;
780
781     // Replace lookup results with just the tag decl.
782     Result.clear(Sema::LookupTagName);
783     SemaRef.LookupParsedName(Result, S, &SS);
784     return true;
785   }
786
787   return false;
788 }
789
790 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
791 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
792                                   QualType T, SourceLocation NameLoc) {
793   ASTContext &Context = S.Context;
794
795   TypeLocBuilder Builder;
796   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
797
798   T = S.getElaboratedType(ETK_None, SS, T);
799   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
800   ElabTL.setElaboratedKeywordLoc(SourceLocation());
801   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
802   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
803 }
804
805 Sema::NameClassification
806 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
807                    SourceLocation NameLoc, const Token &NextToken,
808                    bool IsAddressOfOperand,
809                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
810   DeclarationNameInfo NameInfo(Name, NameLoc);
811   ObjCMethodDecl *CurMethod = getCurMethodDecl();
812
813   if (NextToken.is(tok::coloncolon)) {
814     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
815     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
816   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
817              isCurrentClassName(*Name, S, &SS)) {
818     // Per [class.qual]p2, this names the constructors of SS, not the
819     // injected-class-name. We don't have a classification for that.
820     // There's not much point caching this result, since the parser
821     // will reject it later.
822     return NameClassification::Unknown();
823   }
824
825   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
826   LookupParsedName(Result, S, &SS, !CurMethod);
827
828   // For unqualified lookup in a class template in MSVC mode, look into
829   // dependent base classes where the primary class template is known.
830   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
831     if (ParsedType TypeInBase =
832             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
833       return TypeInBase;
834   }
835
836   // Perform lookup for Objective-C instance variables (including automatically
837   // synthesized instance variables), if we're in an Objective-C method.
838   // FIXME: This lookup really, really needs to be folded in to the normal
839   // unqualified lookup mechanism.
840   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
841     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
842     if (E.get() || E.isInvalid())
843       return E;
844   }
845
846   bool SecondTry = false;
847   bool IsFilteredTemplateName = false;
848
849 Corrected:
850   switch (Result.getResultKind()) {
851   case LookupResult::NotFound:
852     // If an unqualified-id is followed by a '(', then we have a function
853     // call.
854     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
855       // In C++, this is an ADL-only call.
856       // FIXME: Reference?
857       if (getLangOpts().CPlusPlus)
858         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
859
860       // C90 6.3.2.2:
861       //   If the expression that precedes the parenthesized argument list in a
862       //   function call consists solely of an identifier, and if no
863       //   declaration is visible for this identifier, the identifier is
864       //   implicitly declared exactly as if, in the innermost block containing
865       //   the function call, the declaration
866       //
867       //     extern int identifier ();
868       //
869       //   appeared.
870       //
871       // We also allow this in C99 as an extension.
872       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
873         Result.addDecl(D);
874         Result.resolveKind();
875         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
876       }
877     }
878
879     // In C, we first see whether there is a tag type by the same name, in
880     // which case it's likely that the user just forgot to write "enum",
881     // "struct", or "union".
882     if (!getLangOpts().CPlusPlus && !SecondTry &&
883         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
884       break;
885     }
886
887     // Perform typo correction to determine if there is another name that is
888     // close to this name.
889     if (!SecondTry && CCC) {
890       SecondTry = true;
891       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
892                                                  Result.getLookupKind(), S,
893                                                  &SS, std::move(CCC),
894                                                  CTK_ErrorRecovery)) {
895         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
896         unsigned QualifiedDiag = diag::err_no_member_suggest;
897
898         NamedDecl *FirstDecl = Corrected.getFoundDecl();
899         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
900         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
901             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
902           UnqualifiedDiag = diag::err_no_template_suggest;
903           QualifiedDiag = diag::err_no_member_template_suggest;
904         } else if (UnderlyingFirstDecl &&
905                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
906                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
907                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
908           UnqualifiedDiag = diag::err_unknown_typename_suggest;
909           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
910         }
911
912         if (SS.isEmpty()) {
913           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
914         } else {// FIXME: is this even reachable? Test it.
915           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
916           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
917                                   Name->getName().equals(CorrectedStr);
918           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
919                                     << Name << computeDeclContext(SS, false)
920                                     << DroppedSpecifier << SS.getRange());
921         }
922
923         // Update the name, so that the caller has the new name.
924         Name = Corrected.getCorrectionAsIdentifierInfo();
925
926         // Typo correction corrected to a keyword.
927         if (Corrected.isKeyword())
928           return Name;
929
930         // Also update the LookupResult...
931         // FIXME: This should probably go away at some point
932         Result.clear();
933         Result.setLookupName(Corrected.getCorrection());
934         if (FirstDecl)
935           Result.addDecl(FirstDecl);
936
937         // If we found an Objective-C instance variable, let
938         // LookupInObjCMethod build the appropriate expression to
939         // reference the ivar.
940         // FIXME: This is a gross hack.
941         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
942           Result.clear();
943           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
944           return E;
945         }
946
947         goto Corrected;
948       }
949     }
950
951     // We failed to correct; just fall through and let the parser deal with it.
952     Result.suppressDiagnostics();
953     return NameClassification::Unknown();
954
955   case LookupResult::NotFoundInCurrentInstantiation: {
956     // We performed name lookup into the current instantiation, and there were
957     // dependent bases, so we treat this result the same way as any other
958     // dependent nested-name-specifier.
959
960     // C++ [temp.res]p2:
961     //   A name used in a template declaration or definition and that is
962     //   dependent on a template-parameter is assumed not to name a type
963     //   unless the applicable name lookup finds a type name or the name is
964     //   qualified by the keyword typename.
965     //
966     // FIXME: If the next token is '<', we might want to ask the parser to
967     // perform some heroics to see if we actually have a
968     // template-argument-list, which would indicate a missing 'template'
969     // keyword here.
970     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
971                                       NameInfo, IsAddressOfOperand,
972                                       /*TemplateArgs=*/nullptr);
973   }
974
975   case LookupResult::Found:
976   case LookupResult::FoundOverloaded:
977   case LookupResult::FoundUnresolvedValue:
978     break;
979
980   case LookupResult::Ambiguous:
981     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
982         hasAnyAcceptableTemplateNames(Result)) {
983       // C++ [temp.local]p3:
984       //   A lookup that finds an injected-class-name (10.2) can result in an
985       //   ambiguity in certain cases (for example, if it is found in more than
986       //   one base class). If all of the injected-class-names that are found
987       //   refer to specializations of the same class template, and if the name
988       //   is followed by a template-argument-list, the reference refers to the
989       //   class template itself and not a specialization thereof, and is not
990       //   ambiguous.
991       //
992       // This filtering can make an ambiguous result into an unambiguous one,
993       // so try again after filtering out template names.
994       FilterAcceptableTemplateNames(Result);
995       if (!Result.isAmbiguous()) {
996         IsFilteredTemplateName = true;
997         break;
998       }
999     }
1000
1001     // Diagnose the ambiguity and return an error.
1002     return NameClassification::Error();
1003   }
1004
1005   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1006       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1007     // C++ [temp.names]p3:
1008     //   After name lookup (3.4) finds that a name is a template-name or that
1009     //   an operator-function-id or a literal- operator-id refers to a set of
1010     //   overloaded functions any member of which is a function template if
1011     //   this is followed by a <, the < is always taken as the delimiter of a
1012     //   template-argument-list and never as the less-than operator.
1013     if (!IsFilteredTemplateName)
1014       FilterAcceptableTemplateNames(Result);
1015
1016     if (!Result.empty()) {
1017       bool IsFunctionTemplate;
1018       bool IsVarTemplate;
1019       TemplateName Template;
1020       if (Result.end() - Result.begin() > 1) {
1021         IsFunctionTemplate = true;
1022         Template = Context.getOverloadedTemplateName(Result.begin(),
1023                                                      Result.end());
1024       } else {
1025         TemplateDecl *TD
1026           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1027         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1028         IsVarTemplate = isa<VarTemplateDecl>(TD);
1029
1030         if (SS.isSet() && !SS.isInvalid())
1031           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1032                                                     /*TemplateKeyword=*/false,
1033                                                       TD);
1034         else
1035           Template = TemplateName(TD);
1036       }
1037
1038       if (IsFunctionTemplate) {
1039         // Function templates always go through overload resolution, at which
1040         // point we'll perform the various checks (e.g., accessibility) we need
1041         // to based on which function we selected.
1042         Result.suppressDiagnostics();
1043
1044         return NameClassification::FunctionTemplate(Template);
1045       }
1046
1047       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1048                            : NameClassification::TypeTemplate(Template);
1049     }
1050   }
1051
1052   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1053   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1054     DiagnoseUseOfDecl(Type, NameLoc);
1055     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1056     QualType T = Context.getTypeDeclType(Type);
1057     if (SS.isNotEmpty())
1058       return buildNestedType(*this, SS, T, NameLoc);
1059     return ParsedType::make(T);
1060   }
1061
1062   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1063   if (!Class) {
1064     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1065     if (ObjCCompatibleAliasDecl *Alias =
1066             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1067       Class = Alias->getClassInterface();
1068   }
1069
1070   if (Class) {
1071     DiagnoseUseOfDecl(Class, NameLoc);
1072
1073     if (NextToken.is(tok::period)) {
1074       // Interface. <something> is parsed as a property reference expression.
1075       // Just return "unknown" as a fall-through for now.
1076       Result.suppressDiagnostics();
1077       return NameClassification::Unknown();
1078     }
1079
1080     QualType T = Context.getObjCInterfaceType(Class);
1081     return ParsedType::make(T);
1082   }
1083
1084   // We can have a type template here if we're classifying a template argument.
1085   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1086       !isa<VarTemplateDecl>(FirstDecl))
1087     return NameClassification::TypeTemplate(
1088         TemplateName(cast<TemplateDecl>(FirstDecl)));
1089
1090   // Check for a tag type hidden by a non-type decl in a few cases where it
1091   // seems likely a type is wanted instead of the non-type that was found.
1092   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1093   if ((NextToken.is(tok::identifier) ||
1094        (NextIsOp &&
1095         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1096       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1097     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1098     DiagnoseUseOfDecl(Type, NameLoc);
1099     QualType T = Context.getTypeDeclType(Type);
1100     if (SS.isNotEmpty())
1101       return buildNestedType(*this, SS, T, NameLoc);
1102     return ParsedType::make(T);
1103   }
1104
1105   if (FirstDecl->isCXXClassMember())
1106     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1107                                            nullptr, S);
1108
1109   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1110   return BuildDeclarationNameExpr(SS, Result, ADL);
1111 }
1112
1113 Sema::TemplateNameKindForDiagnostics
1114 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1115   auto *TD = Name.getAsTemplateDecl();
1116   if (!TD)
1117     return TemplateNameKindForDiagnostics::DependentTemplate;
1118   if (isa<ClassTemplateDecl>(TD))
1119     return TemplateNameKindForDiagnostics::ClassTemplate;
1120   if (isa<FunctionTemplateDecl>(TD))
1121     return TemplateNameKindForDiagnostics::FunctionTemplate;
1122   if (isa<VarTemplateDecl>(TD))
1123     return TemplateNameKindForDiagnostics::VarTemplate;
1124   if (isa<TypeAliasTemplateDecl>(TD))
1125     return TemplateNameKindForDiagnostics::AliasTemplate;
1126   if (isa<TemplateTemplateParmDecl>(TD))
1127     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1128   return TemplateNameKindForDiagnostics::DependentTemplate;
1129 }
1130
1131 // Determines the context to return to after temporarily entering a
1132 // context.  This depends in an unnecessarily complicated way on the
1133 // exact ordering of callbacks from the parser.
1134 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1135
1136   // Functions defined inline within classes aren't parsed until we've
1137   // finished parsing the top-level class, so the top-level class is
1138   // the context we'll need to return to.
1139   // A Lambda call operator whose parent is a class must not be treated
1140   // as an inline member function.  A Lambda can be used legally
1141   // either as an in-class member initializer or a default argument.  These
1142   // are parsed once the class has been marked complete and so the containing
1143   // context would be the nested class (when the lambda is defined in one);
1144   // If the class is not complete, then the lambda is being used in an
1145   // ill-formed fashion (such as to specify the width of a bit-field, or
1146   // in an array-bound) - in which case we still want to return the
1147   // lexically containing DC (which could be a nested class).
1148   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1149     DC = DC->getLexicalParent();
1150
1151     // A function not defined within a class will always return to its
1152     // lexical context.
1153     if (!isa<CXXRecordDecl>(DC))
1154       return DC;
1155
1156     // A C++ inline method/friend is parsed *after* the topmost class
1157     // it was declared in is fully parsed ("complete");  the topmost
1158     // class is the context we need to return to.
1159     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1160       DC = RD;
1161
1162     // Return the declaration context of the topmost class the inline method is
1163     // declared in.
1164     return DC;
1165   }
1166
1167   return DC->getLexicalParent();
1168 }
1169
1170 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1171   assert(getContainingDC(DC) == CurContext &&
1172       "The next DeclContext should be lexically contained in the current one.");
1173   CurContext = DC;
1174   S->setEntity(DC);
1175 }
1176
1177 void Sema::PopDeclContext() {
1178   assert(CurContext && "DeclContext imbalance!");
1179
1180   CurContext = getContainingDC(CurContext);
1181   assert(CurContext && "Popped translation unit!");
1182 }
1183
1184 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1185                                                                     Decl *D) {
1186   // Unlike PushDeclContext, the context to which we return is not necessarily
1187   // the containing DC of TD, because the new context will be some pre-existing
1188   // TagDecl definition instead of a fresh one.
1189   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1190   CurContext = cast<TagDecl>(D)->getDefinition();
1191   assert(CurContext && "skipping definition of undefined tag");
1192   // Start lookups from the parent of the current context; we don't want to look
1193   // into the pre-existing complete definition.
1194   S->setEntity(CurContext->getLookupParent());
1195   return Result;
1196 }
1197
1198 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1199   CurContext = static_cast<decltype(CurContext)>(Context);
1200 }
1201
1202 /// EnterDeclaratorContext - Used when we must lookup names in the context
1203 /// of a declarator's nested name specifier.
1204 ///
1205 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1206   // C++0x [basic.lookup.unqual]p13:
1207   //   A name used in the definition of a static data member of class
1208   //   X (after the qualified-id of the static member) is looked up as
1209   //   if the name was used in a member function of X.
1210   // C++0x [basic.lookup.unqual]p14:
1211   //   If a variable member of a namespace is defined outside of the
1212   //   scope of its namespace then any name used in the definition of
1213   //   the variable member (after the declarator-id) is looked up as
1214   //   if the definition of the variable member occurred in its
1215   //   namespace.
1216   // Both of these imply that we should push a scope whose context
1217   // is the semantic context of the declaration.  We can't use
1218   // PushDeclContext here because that context is not necessarily
1219   // lexically contained in the current context.  Fortunately,
1220   // the containing scope should have the appropriate information.
1221
1222   assert(!S->getEntity() && "scope already has entity");
1223
1224 #ifndef NDEBUG
1225   Scope *Ancestor = S->getParent();
1226   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1227   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1228 #endif
1229
1230   CurContext = DC;
1231   S->setEntity(DC);
1232 }
1233
1234 void Sema::ExitDeclaratorContext(Scope *S) {
1235   assert(S->getEntity() == CurContext && "Context imbalance!");
1236
1237   // Switch back to the lexical context.  The safety of this is
1238   // enforced by an assert in EnterDeclaratorContext.
1239   Scope *Ancestor = S->getParent();
1240   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1241   CurContext = Ancestor->getEntity();
1242
1243   // We don't need to do anything with the scope, which is going to
1244   // disappear.
1245 }
1246
1247 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1248   // We assume that the caller has already called
1249   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1250   FunctionDecl *FD = D->getAsFunction();
1251   if (!FD)
1252     return;
1253
1254   // Same implementation as PushDeclContext, but enters the context
1255   // from the lexical parent, rather than the top-level class.
1256   assert(CurContext == FD->getLexicalParent() &&
1257     "The next DeclContext should be lexically contained in the current one.");
1258   CurContext = FD;
1259   S->setEntity(CurContext);
1260
1261   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1262     ParmVarDecl *Param = FD->getParamDecl(P);
1263     // If the parameter has an identifier, then add it to the scope
1264     if (Param->getIdentifier()) {
1265       S->AddDecl(Param);
1266       IdResolver.AddDecl(Param);
1267     }
1268   }
1269 }
1270
1271 void Sema::ActOnExitFunctionContext() {
1272   // Same implementation as PopDeclContext, but returns to the lexical parent,
1273   // rather than the top-level class.
1274   assert(CurContext && "DeclContext imbalance!");
1275   CurContext = CurContext->getLexicalParent();
1276   assert(CurContext && "Popped translation unit!");
1277 }
1278
1279 /// \brief Determine whether we allow overloading of the function
1280 /// PrevDecl with another declaration.
1281 ///
1282 /// This routine determines whether overloading is possible, not
1283 /// whether some new function is actually an overload. It will return
1284 /// true in C++ (where we can always provide overloads) or, as an
1285 /// extension, in C when the previous function is already an
1286 /// overloaded function declaration or has the "overloadable"
1287 /// attribute.
1288 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1289                                        ASTContext &Context) {
1290   if (Context.getLangOpts().CPlusPlus)
1291     return true;
1292
1293   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1294     return true;
1295
1296   return (Previous.getResultKind() == LookupResult::Found
1297           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1298 }
1299
1300 /// Add this decl to the scope shadowed decl chains.
1301 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1302   // Move up the scope chain until we find the nearest enclosing
1303   // non-transparent context. The declaration will be introduced into this
1304   // scope.
1305   while (S->getEntity() && S->getEntity()->isTransparentContext())
1306     S = S->getParent();
1307
1308   // Add scoped declarations into their context, so that they can be
1309   // found later. Declarations without a context won't be inserted
1310   // into any context.
1311   if (AddToContext)
1312     CurContext->addDecl(D);
1313
1314   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1315   // are function-local declarations.
1316   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1317       !D->getDeclContext()->getRedeclContext()->Equals(
1318         D->getLexicalDeclContext()->getRedeclContext()) &&
1319       !D->getLexicalDeclContext()->isFunctionOrMethod())
1320     return;
1321
1322   // Template instantiations should also not be pushed into scope.
1323   if (isa<FunctionDecl>(D) &&
1324       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1325     return;
1326
1327   // If this replaces anything in the current scope,
1328   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1329                                IEnd = IdResolver.end();
1330   for (; I != IEnd; ++I) {
1331     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1332       S->RemoveDecl(*I);
1333       IdResolver.RemoveDecl(*I);
1334
1335       // Should only need to replace one decl.
1336       break;
1337     }
1338   }
1339
1340   S->AddDecl(D);
1341
1342   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1343     // Implicitly-generated labels may end up getting generated in an order that
1344     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1345     // the label at the appropriate place in the identifier chain.
1346     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1347       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1348       if (IDC == CurContext) {
1349         if (!S->isDeclScope(*I))
1350           continue;
1351       } else if (IDC->Encloses(CurContext))
1352         break;
1353     }
1354
1355     IdResolver.InsertDeclAfter(I, D);
1356   } else {
1357     IdResolver.AddDecl(D);
1358   }
1359 }
1360
1361 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1362   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1363     TUScope->AddDecl(D);
1364 }
1365
1366 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1367                          bool AllowInlineNamespace) {
1368   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1369 }
1370
1371 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1372   DeclContext *TargetDC = DC->getPrimaryContext();
1373   do {
1374     if (DeclContext *ScopeDC = S->getEntity())
1375       if (ScopeDC->getPrimaryContext() == TargetDC)
1376         return S;
1377   } while ((S = S->getParent()));
1378
1379   return nullptr;
1380 }
1381
1382 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1383                                             DeclContext*,
1384                                             ASTContext&);
1385
1386 /// Filters out lookup results that don't fall within the given scope
1387 /// as determined by isDeclInScope.
1388 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1389                                 bool ConsiderLinkage,
1390                                 bool AllowInlineNamespace) {
1391   LookupResult::Filter F = R.makeFilter();
1392   while (F.hasNext()) {
1393     NamedDecl *D = F.next();
1394
1395     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1396       continue;
1397
1398     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1399       continue;
1400
1401     F.erase();
1402   }
1403
1404   F.done();
1405 }
1406
1407 static bool isUsingDecl(NamedDecl *D) {
1408   return isa<UsingShadowDecl>(D) ||
1409          isa<UnresolvedUsingTypenameDecl>(D) ||
1410          isa<UnresolvedUsingValueDecl>(D);
1411 }
1412
1413 /// Removes using shadow declarations from the lookup results.
1414 static void RemoveUsingDecls(LookupResult &R) {
1415   LookupResult::Filter F = R.makeFilter();
1416   while (F.hasNext())
1417     if (isUsingDecl(F.next()))
1418       F.erase();
1419
1420   F.done();
1421 }
1422
1423 /// \brief Check for this common pattern:
1424 /// @code
1425 /// class S {
1426 ///   S(const S&); // DO NOT IMPLEMENT
1427 ///   void operator=(const S&); // DO NOT IMPLEMENT
1428 /// };
1429 /// @endcode
1430 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1431   // FIXME: Should check for private access too but access is set after we get
1432   // the decl here.
1433   if (D->doesThisDeclarationHaveABody())
1434     return false;
1435
1436   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1437     return CD->isCopyConstructor();
1438   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1439     return Method->isCopyAssignmentOperator();
1440   return false;
1441 }
1442
1443 // We need this to handle
1444 //
1445 // typedef struct {
1446 //   void *foo() { return 0; }
1447 // } A;
1448 //
1449 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1450 // for example. If 'A', foo will have external linkage. If we have '*A',
1451 // foo will have no linkage. Since we can't know until we get to the end
1452 // of the typedef, this function finds out if D might have non-external linkage.
1453 // Callers should verify at the end of the TU if it D has external linkage or
1454 // not.
1455 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1456   const DeclContext *DC = D->getDeclContext();
1457   while (!DC->isTranslationUnit()) {
1458     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1459       if (!RD->hasNameForLinkage())
1460         return true;
1461     }
1462     DC = DC->getParent();
1463   }
1464
1465   return !D->isExternallyVisible();
1466 }
1467
1468 // FIXME: This needs to be refactored; some other isInMainFile users want
1469 // these semantics.
1470 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1471   if (S.TUKind != TU_Complete)
1472     return false;
1473   return S.SourceMgr.isInMainFile(Loc);
1474 }
1475
1476 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1477   assert(D);
1478
1479   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1480     return false;
1481
1482   // Ignore all entities declared within templates, and out-of-line definitions
1483   // of members of class templates.
1484   if (D->getDeclContext()->isDependentContext() ||
1485       D->getLexicalDeclContext()->isDependentContext())
1486     return false;
1487
1488   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1489     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1490       return false;
1491
1492     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1493       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1494         return false;
1495     } else {
1496       // 'static inline' functions are defined in headers; don't warn.
1497       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1498         return false;
1499     }
1500
1501     if (FD->doesThisDeclarationHaveABody() &&
1502         Context.DeclMustBeEmitted(FD))
1503       return false;
1504   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1505     // Constants and utility variables are defined in headers with internal
1506     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1507     // like "inline".)
1508     if (!isMainFileLoc(*this, VD->getLocation()))
1509       return false;
1510
1511     if (Context.DeclMustBeEmitted(VD))
1512       return false;
1513
1514     if (VD->isStaticDataMember() &&
1515         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1516       return false;
1517
1518     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1519       return false;
1520   } else {
1521     return false;
1522   }
1523
1524   // Only warn for unused decls internal to the translation unit.
1525   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1526   // for inline functions defined in the main source file, for instance.
1527   return mightHaveNonExternalLinkage(D);
1528 }
1529
1530 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1531   if (!D)
1532     return;
1533
1534   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1535     const FunctionDecl *First = FD->getFirstDecl();
1536     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1537       return; // First should already be in the vector.
1538   }
1539
1540   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1541     const VarDecl *First = VD->getFirstDecl();
1542     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1543       return; // First should already be in the vector.
1544   }
1545
1546   if (ShouldWarnIfUnusedFileScopedDecl(D))
1547     UnusedFileScopedDecls.push_back(D);
1548 }
1549
1550 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1551   if (D->isInvalidDecl())
1552     return false;
1553
1554   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1555       D->hasAttr<ObjCPreciseLifetimeAttr>())
1556     return false;
1557
1558   if (isa<LabelDecl>(D))
1559     return true;
1560
1561   // Except for labels, we only care about unused decls that are local to
1562   // functions.
1563   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1564   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1565     // For dependent types, the diagnostic is deferred.
1566     WithinFunction =
1567         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1568   if (!WithinFunction)
1569     return false;
1570
1571   if (isa<TypedefNameDecl>(D))
1572     return true;
1573
1574   // White-list anything that isn't a local variable.
1575   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1576     return false;
1577
1578   // Types of valid local variables should be complete, so this should succeed.
1579   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1580
1581     // White-list anything with an __attribute__((unused)) type.
1582     const auto *Ty = VD->getType().getTypePtr();
1583
1584     // Only look at the outermost level of typedef.
1585     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1586       if (TT->getDecl()->hasAttr<UnusedAttr>())
1587         return false;
1588     }
1589
1590     // If we failed to complete the type for some reason, or if the type is
1591     // dependent, don't diagnose the variable.
1592     if (Ty->isIncompleteType() || Ty->isDependentType())
1593       return false;
1594
1595     // Look at the element type to ensure that the warning behaviour is
1596     // consistent for both scalars and arrays.
1597     Ty = Ty->getBaseElementTypeUnsafe();
1598
1599     if (const TagType *TT = Ty->getAs<TagType>()) {
1600       const TagDecl *Tag = TT->getDecl();
1601       if (Tag->hasAttr<UnusedAttr>())
1602         return false;
1603
1604       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1605         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1606           return false;
1607
1608         if (const Expr *Init = VD->getInit()) {
1609           if (const ExprWithCleanups *Cleanups =
1610                   dyn_cast<ExprWithCleanups>(Init))
1611             Init = Cleanups->getSubExpr();
1612           const CXXConstructExpr *Construct =
1613             dyn_cast<CXXConstructExpr>(Init);
1614           if (Construct && !Construct->isElidable()) {
1615             CXXConstructorDecl *CD = Construct->getConstructor();
1616             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1617               return false;
1618           }
1619         }
1620       }
1621     }
1622
1623     // TODO: __attribute__((unused)) templates?
1624   }
1625
1626   return true;
1627 }
1628
1629 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1630                                      FixItHint &Hint) {
1631   if (isa<LabelDecl>(D)) {
1632     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1633                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1634     if (AfterColon.isInvalid())
1635       return;
1636     Hint = FixItHint::CreateRemoval(CharSourceRange::
1637                                     getCharRange(D->getLocStart(), AfterColon));
1638   }
1639 }
1640
1641 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1642   if (D->getTypeForDecl()->isDependentType())
1643     return;
1644
1645   for (auto *TmpD : D->decls()) {
1646     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1647       DiagnoseUnusedDecl(T);
1648     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1649       DiagnoseUnusedNestedTypedefs(R);
1650   }
1651 }
1652
1653 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1654 /// unless they are marked attr(unused).
1655 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1656   if (!ShouldDiagnoseUnusedDecl(D))
1657     return;
1658
1659   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1660     // typedefs can be referenced later on, so the diagnostics are emitted
1661     // at end-of-translation-unit.
1662     UnusedLocalTypedefNameCandidates.insert(TD);
1663     return;
1664   }
1665
1666   FixItHint Hint;
1667   GenerateFixForUnusedDecl(D, Context, Hint);
1668
1669   unsigned DiagID;
1670   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1671     DiagID = diag::warn_unused_exception_param;
1672   else if (isa<LabelDecl>(D))
1673     DiagID = diag::warn_unused_label;
1674   else
1675     DiagID = diag::warn_unused_variable;
1676
1677   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1678 }
1679
1680 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1681   // Verify that we have no forward references left.  If so, there was a goto
1682   // or address of a label taken, but no definition of it.  Label fwd
1683   // definitions are indicated with a null substmt which is also not a resolved
1684   // MS inline assembly label name.
1685   bool Diagnose = false;
1686   if (L->isMSAsmLabel())
1687     Diagnose = !L->isResolvedMSAsmLabel();
1688   else
1689     Diagnose = L->getStmt() == nullptr;
1690   if (Diagnose)
1691     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1692 }
1693
1694 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1695   S->mergeNRVOIntoParent();
1696
1697   if (S->decl_empty()) return;
1698   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1699          "Scope shouldn't contain decls!");
1700
1701   for (auto *TmpD : S->decls()) {
1702     assert(TmpD && "This decl didn't get pushed??");
1703
1704     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1705     NamedDecl *D = cast<NamedDecl>(TmpD);
1706
1707     if (!D->getDeclName()) continue;
1708
1709     // Diagnose unused variables in this scope.
1710     if (!S->hasUnrecoverableErrorOccurred()) {
1711       DiagnoseUnusedDecl(D);
1712       if (const auto *RD = dyn_cast<RecordDecl>(D))
1713         DiagnoseUnusedNestedTypedefs(RD);
1714     }
1715
1716     // If this was a forward reference to a label, verify it was defined.
1717     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1718       CheckPoppedLabel(LD, *this);
1719
1720     // Remove this name from our lexical scope, and warn on it if we haven't
1721     // already.
1722     IdResolver.RemoveDecl(D);
1723     auto ShadowI = ShadowingDecls.find(D);
1724     if (ShadowI != ShadowingDecls.end()) {
1725       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1726         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1727             << D << FD << FD->getParent();
1728         Diag(FD->getLocation(), diag::note_previous_declaration);
1729       }
1730       ShadowingDecls.erase(ShadowI);
1731     }
1732   }
1733 }
1734
1735 /// \brief Look for an Objective-C class in the translation unit.
1736 ///
1737 /// \param Id The name of the Objective-C class we're looking for. If
1738 /// typo-correction fixes this name, the Id will be updated
1739 /// to the fixed name.
1740 ///
1741 /// \param IdLoc The location of the name in the translation unit.
1742 ///
1743 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1744 /// if there is no class with the given name.
1745 ///
1746 /// \returns The declaration of the named Objective-C class, or NULL if the
1747 /// class could not be found.
1748 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1749                                               SourceLocation IdLoc,
1750                                               bool DoTypoCorrection) {
1751   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1752   // creation from this context.
1753   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1754
1755   if (!IDecl && DoTypoCorrection) {
1756     // Perform typo correction at the given location, but only if we
1757     // find an Objective-C class name.
1758     if (TypoCorrection C = CorrectTypo(
1759             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1760             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1761             CTK_ErrorRecovery)) {
1762       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1763       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1764       Id = IDecl->getIdentifier();
1765     }
1766   }
1767   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1768   // This routine must always return a class definition, if any.
1769   if (Def && Def->getDefinition())
1770       Def = Def->getDefinition();
1771   return Def;
1772 }
1773
1774 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1775 /// from S, where a non-field would be declared. This routine copes
1776 /// with the difference between C and C++ scoping rules in structs and
1777 /// unions. For example, the following code is well-formed in C but
1778 /// ill-formed in C++:
1779 /// @code
1780 /// struct S6 {
1781 ///   enum { BAR } e;
1782 /// };
1783 ///
1784 /// void test_S6() {
1785 ///   struct S6 a;
1786 ///   a.e = BAR;
1787 /// }
1788 /// @endcode
1789 /// For the declaration of BAR, this routine will return a different
1790 /// scope. The scope S will be the scope of the unnamed enumeration
1791 /// within S6. In C++, this routine will return the scope associated
1792 /// with S6, because the enumeration's scope is a transparent
1793 /// context but structures can contain non-field names. In C, this
1794 /// routine will return the translation unit scope, since the
1795 /// enumeration's scope is a transparent context and structures cannot
1796 /// contain non-field names.
1797 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1798   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1799          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1800          (S->isClassScope() && !getLangOpts().CPlusPlus))
1801     S = S->getParent();
1802   return S;
1803 }
1804
1805 /// \brief Looks up the declaration of "struct objc_super" and
1806 /// saves it for later use in building builtin declaration of
1807 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1808 /// pre-existing declaration exists no action takes place.
1809 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1810                                         IdentifierInfo *II) {
1811   if (!II->isStr("objc_msgSendSuper"))
1812     return;
1813   ASTContext &Context = ThisSema.Context;
1814
1815   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1816                       SourceLocation(), Sema::LookupTagName);
1817   ThisSema.LookupName(Result, S);
1818   if (Result.getResultKind() == LookupResult::Found)
1819     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1820       Context.setObjCSuperType(Context.getTagDeclType(TD));
1821 }
1822
1823 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1824   switch (Error) {
1825   case ASTContext::GE_None:
1826     return "";
1827   case ASTContext::GE_Missing_stdio:
1828     return "stdio.h";
1829   case ASTContext::GE_Missing_setjmp:
1830     return "setjmp.h";
1831   case ASTContext::GE_Missing_ucontext:
1832     return "ucontext.h";
1833   }
1834   llvm_unreachable("unhandled error kind");
1835 }
1836
1837 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1838 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1839 /// if we're creating this built-in in anticipation of redeclaring the
1840 /// built-in.
1841 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1842                                      Scope *S, bool ForRedeclaration,
1843                                      SourceLocation Loc) {
1844   LookupPredefedObjCSuperType(*this, S, II);
1845
1846   ASTContext::GetBuiltinTypeError Error;
1847   QualType R = Context.GetBuiltinType(ID, Error);
1848   if (Error) {
1849     if (ForRedeclaration)
1850       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1851           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1852     return nullptr;
1853   }
1854
1855   if (!ForRedeclaration &&
1856       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1857        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1858     Diag(Loc, diag::ext_implicit_lib_function_decl)
1859         << Context.BuiltinInfo.getName(ID) << R;
1860     if (Context.BuiltinInfo.getHeaderName(ID) &&
1861         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1862       Diag(Loc, diag::note_include_header_or_declare)
1863           << Context.BuiltinInfo.getHeaderName(ID)
1864           << Context.BuiltinInfo.getName(ID);
1865   }
1866
1867   if (R.isNull())
1868     return nullptr;
1869
1870   DeclContext *Parent = Context.getTranslationUnitDecl();
1871   if (getLangOpts().CPlusPlus) {
1872     LinkageSpecDecl *CLinkageDecl =
1873         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1874                                 LinkageSpecDecl::lang_c, false);
1875     CLinkageDecl->setImplicit();
1876     Parent->addDecl(CLinkageDecl);
1877     Parent = CLinkageDecl;
1878   }
1879
1880   FunctionDecl *New = FunctionDecl::Create(Context,
1881                                            Parent,
1882                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1883                                            SC_Extern,
1884                                            false,
1885                                            R->isFunctionProtoType());
1886   New->setImplicit();
1887
1888   // Create Decl objects for each parameter, adding them to the
1889   // FunctionDecl.
1890   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1891     SmallVector<ParmVarDecl*, 16> Params;
1892     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1893       ParmVarDecl *parm =
1894           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1895                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1896                               SC_None, nullptr);
1897       parm->setScopeInfo(0, i);
1898       Params.push_back(parm);
1899     }
1900     New->setParams(Params);
1901   }
1902
1903   AddKnownFunctionAttributes(New);
1904   RegisterLocallyScopedExternCDecl(New, S);
1905
1906   // TUScope is the translation-unit scope to insert this function into.
1907   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1908   // relate Scopes to DeclContexts, and probably eliminate CurContext
1909   // entirely, but we're not there yet.
1910   DeclContext *SavedContext = CurContext;
1911   CurContext = Parent;
1912   PushOnScopeChains(New, TUScope);
1913   CurContext = SavedContext;
1914   return New;
1915 }
1916
1917 /// Typedef declarations don't have linkage, but they still denote the same
1918 /// entity if their types are the same.
1919 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1920 /// isSameEntity.
1921 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1922                                                      TypedefNameDecl *Decl,
1923                                                      LookupResult &Previous) {
1924   // This is only interesting when modules are enabled.
1925   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1926     return;
1927
1928   // Empty sets are uninteresting.
1929   if (Previous.empty())
1930     return;
1931
1932   LookupResult::Filter Filter = Previous.makeFilter();
1933   while (Filter.hasNext()) {
1934     NamedDecl *Old = Filter.next();
1935
1936     // Non-hidden declarations are never ignored.
1937     if (S.isVisible(Old))
1938       continue;
1939
1940     // Declarations of the same entity are not ignored, even if they have
1941     // different linkages.
1942     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1943       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1944                                 Decl->getUnderlyingType()))
1945         continue;
1946
1947       // If both declarations give a tag declaration a typedef name for linkage
1948       // purposes, then they declare the same entity.
1949       if (S.getLangOpts().CPlusPlus &&
1950           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1951           Decl->getAnonDeclWithTypedefName())
1952         continue;
1953     }
1954
1955     Filter.erase();
1956   }
1957
1958   Filter.done();
1959 }
1960
1961 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1962   QualType OldType;
1963   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1964     OldType = OldTypedef->getUnderlyingType();
1965   else
1966     OldType = Context.getTypeDeclType(Old);
1967   QualType NewType = New->getUnderlyingType();
1968
1969   if (NewType->isVariablyModifiedType()) {
1970     // Must not redefine a typedef with a variably-modified type.
1971     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1972     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1973       << Kind << NewType;
1974     if (Old->getLocation().isValid())
1975       Diag(Old->getLocation(), diag::note_previous_definition);
1976     New->setInvalidDecl();
1977     return true;
1978   }
1979
1980   if (OldType != NewType &&
1981       !OldType->isDependentType() &&
1982       !NewType->isDependentType() &&
1983       !Context.hasSameType(OldType, NewType)) {
1984     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1985     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1986       << Kind << NewType << OldType;
1987     if (Old->getLocation().isValid())
1988       Diag(Old->getLocation(), diag::note_previous_definition);
1989     New->setInvalidDecl();
1990     return true;
1991   }
1992   return false;
1993 }
1994
1995 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1996 /// same name and scope as a previous declaration 'Old'.  Figure out
1997 /// how to resolve this situation, merging decls or emitting
1998 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1999 ///
2000 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2001                                 LookupResult &OldDecls) {
2002   // If the new decl is known invalid already, don't bother doing any
2003   // merging checks.
2004   if (New->isInvalidDecl()) return;
2005
2006   // Allow multiple definitions for ObjC built-in typedefs.
2007   // FIXME: Verify the underlying types are equivalent!
2008   if (getLangOpts().ObjC1) {
2009     const IdentifierInfo *TypeID = New->getIdentifier();
2010     switch (TypeID->getLength()) {
2011     default: break;
2012     case 2:
2013       {
2014         if (!TypeID->isStr("id"))
2015           break;
2016         QualType T = New->getUnderlyingType();
2017         if (!T->isPointerType())
2018           break;
2019         if (!T->isVoidPointerType()) {
2020           QualType PT = T->getAs<PointerType>()->getPointeeType();
2021           if (!PT->isStructureType())
2022             break;
2023         }
2024         Context.setObjCIdRedefinitionType(T);
2025         // Install the built-in type for 'id', ignoring the current definition.
2026         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2027         return;
2028       }
2029     case 5:
2030       if (!TypeID->isStr("Class"))
2031         break;
2032       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2033       // Install the built-in type for 'Class', ignoring the current definition.
2034       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2035       return;
2036     case 3:
2037       if (!TypeID->isStr("SEL"))
2038         break;
2039       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2040       // Install the built-in type for 'SEL', ignoring the current definition.
2041       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2042       return;
2043     }
2044     // Fall through - the typedef name was not a builtin type.
2045   }
2046
2047   // Verify the old decl was also a type.
2048   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2049   if (!Old) {
2050     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2051       << New->getDeclName();
2052
2053     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2054     if (OldD->getLocation().isValid())
2055       Diag(OldD->getLocation(), diag::note_previous_definition);
2056
2057     return New->setInvalidDecl();
2058   }
2059
2060   // If the old declaration is invalid, just give up here.
2061   if (Old->isInvalidDecl())
2062     return New->setInvalidDecl();
2063
2064   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2065     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2066     auto *NewTag = New->getAnonDeclWithTypedefName();
2067     NamedDecl *Hidden = nullptr;
2068     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2069         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2070         !hasVisibleDefinition(OldTag, &Hidden)) {
2071       // There is a definition of this tag, but it is not visible. Use it
2072       // instead of our tag.
2073       New->setTypeForDecl(OldTD->getTypeForDecl());
2074       if (OldTD->isModed())
2075         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2076                                     OldTD->getUnderlyingType());
2077       else
2078         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2079
2080       // Make the old tag definition visible.
2081       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
2082
2083       // If this was an unscoped enumeration, yank all of its enumerators
2084       // out of the scope.
2085       if (isa<EnumDecl>(NewTag)) {
2086         Scope *EnumScope = getNonFieldDeclScope(S);
2087         for (auto *D : NewTag->decls()) {
2088           auto *ED = cast<EnumConstantDecl>(D);
2089           assert(EnumScope->isDeclScope(ED));
2090           EnumScope->RemoveDecl(ED);
2091           IdResolver.RemoveDecl(ED);
2092           ED->getLexicalDeclContext()->removeDecl(ED);
2093         }
2094       }
2095     }
2096   }
2097
2098   // If the typedef types are not identical, reject them in all languages and
2099   // with any extensions enabled.
2100   if (isIncompatibleTypedef(Old, New))
2101     return;
2102
2103   // The types match.  Link up the redeclaration chain and merge attributes if
2104   // the old declaration was a typedef.
2105   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2106     New->setPreviousDecl(Typedef);
2107     mergeDeclAttributes(New, Old);
2108   }
2109
2110   if (getLangOpts().MicrosoftExt)
2111     return;
2112
2113   if (getLangOpts().CPlusPlus) {
2114     // C++ [dcl.typedef]p2:
2115     //   In a given non-class scope, a typedef specifier can be used to
2116     //   redefine the name of any type declared in that scope to refer
2117     //   to the type to which it already refers.
2118     if (!isa<CXXRecordDecl>(CurContext))
2119       return;
2120
2121     // C++0x [dcl.typedef]p4:
2122     //   In a given class scope, a typedef specifier can be used to redefine
2123     //   any class-name declared in that scope that is not also a typedef-name
2124     //   to refer to the type to which it already refers.
2125     //
2126     // This wording came in via DR424, which was a correction to the
2127     // wording in DR56, which accidentally banned code like:
2128     //
2129     //   struct S {
2130     //     typedef struct A { } A;
2131     //   };
2132     //
2133     // in the C++03 standard. We implement the C++0x semantics, which
2134     // allow the above but disallow
2135     //
2136     //   struct S {
2137     //     typedef int I;
2138     //     typedef int I;
2139     //   };
2140     //
2141     // since that was the intent of DR56.
2142     if (!isa<TypedefNameDecl>(Old))
2143       return;
2144
2145     Diag(New->getLocation(), diag::err_redefinition)
2146       << New->getDeclName();
2147     Diag(Old->getLocation(), diag::note_previous_definition);
2148     return New->setInvalidDecl();
2149   }
2150
2151   // Modules always permit redefinition of typedefs, as does C11.
2152   if (getLangOpts().Modules || getLangOpts().C11)
2153     return;
2154
2155   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2156   // is normally mapped to an error, but can be controlled with
2157   // -Wtypedef-redefinition.  If either the original or the redefinition is
2158   // in a system header, don't emit this for compatibility with GCC.
2159   if (getDiagnostics().getSuppressSystemWarnings() &&
2160       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2161       (Old->isImplicit() ||
2162        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2163        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2164     return;
2165
2166   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2167     << New->getDeclName();
2168   Diag(Old->getLocation(), diag::note_previous_definition);
2169 }
2170
2171 /// DeclhasAttr - returns true if decl Declaration already has the target
2172 /// attribute.
2173 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2174   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2175   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2176   for (const auto *i : D->attrs())
2177     if (i->getKind() == A->getKind()) {
2178       if (Ann) {
2179         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2180           return true;
2181         continue;
2182       }
2183       // FIXME: Don't hardcode this check
2184       if (OA && isa<OwnershipAttr>(i))
2185         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2186       return true;
2187     }
2188
2189   return false;
2190 }
2191
2192 static bool isAttributeTargetADefinition(Decl *D) {
2193   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2194     return VD->isThisDeclarationADefinition();
2195   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2196     return TD->isCompleteDefinition() || TD->isBeingDefined();
2197   return true;
2198 }
2199
2200 /// Merge alignment attributes from \p Old to \p New, taking into account the
2201 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2202 ///
2203 /// \return \c true if any attributes were added to \p New.
2204 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2205   // Look for alignas attributes on Old, and pick out whichever attribute
2206   // specifies the strictest alignment requirement.
2207   AlignedAttr *OldAlignasAttr = nullptr;
2208   AlignedAttr *OldStrictestAlignAttr = nullptr;
2209   unsigned OldAlign = 0;
2210   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2211     // FIXME: We have no way of representing inherited dependent alignments
2212     // in a case like:
2213     //   template<int A, int B> struct alignas(A) X;
2214     //   template<int A, int B> struct alignas(B) X {};
2215     // For now, we just ignore any alignas attributes which are not on the
2216     // definition in such a case.
2217     if (I->isAlignmentDependent())
2218       return false;
2219
2220     if (I->isAlignas())
2221       OldAlignasAttr = I;
2222
2223     unsigned Align = I->getAlignment(S.Context);
2224     if (Align > OldAlign) {
2225       OldAlign = Align;
2226       OldStrictestAlignAttr = I;
2227     }
2228   }
2229
2230   // Look for alignas attributes on New.
2231   AlignedAttr *NewAlignasAttr = nullptr;
2232   unsigned NewAlign = 0;
2233   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2234     if (I->isAlignmentDependent())
2235       return false;
2236
2237     if (I->isAlignas())
2238       NewAlignasAttr = I;
2239
2240     unsigned Align = I->getAlignment(S.Context);
2241     if (Align > NewAlign)
2242       NewAlign = Align;
2243   }
2244
2245   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2246     // Both declarations have 'alignas' attributes. We require them to match.
2247     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2248     // fall short. (If two declarations both have alignas, they must both match
2249     // every definition, and so must match each other if there is a definition.)
2250
2251     // If either declaration only contains 'alignas(0)' specifiers, then it
2252     // specifies the natural alignment for the type.
2253     if (OldAlign == 0 || NewAlign == 0) {
2254       QualType Ty;
2255       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2256         Ty = VD->getType();
2257       else
2258         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2259
2260       if (OldAlign == 0)
2261         OldAlign = S.Context.getTypeAlign(Ty);
2262       if (NewAlign == 0)
2263         NewAlign = S.Context.getTypeAlign(Ty);
2264     }
2265
2266     if (OldAlign != NewAlign) {
2267       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2268         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2269         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2270       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2271     }
2272   }
2273
2274   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2275     // C++11 [dcl.align]p6:
2276     //   if any declaration of an entity has an alignment-specifier,
2277     //   every defining declaration of that entity shall specify an
2278     //   equivalent alignment.
2279     // C11 6.7.5/7:
2280     //   If the definition of an object does not have an alignment
2281     //   specifier, any other declaration of that object shall also
2282     //   have no alignment specifier.
2283     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2284       << OldAlignasAttr;
2285     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2286       << OldAlignasAttr;
2287   }
2288
2289   bool AnyAdded = false;
2290
2291   // Ensure we have an attribute representing the strictest alignment.
2292   if (OldAlign > NewAlign) {
2293     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2294     Clone->setInherited(true);
2295     New->addAttr(Clone);
2296     AnyAdded = true;
2297   }
2298
2299   // Ensure we have an alignas attribute if the old declaration had one.
2300   if (OldAlignasAttr && !NewAlignasAttr &&
2301       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2302     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2303     Clone->setInherited(true);
2304     New->addAttr(Clone);
2305     AnyAdded = true;
2306   }
2307
2308   return AnyAdded;
2309 }
2310
2311 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2312                                const InheritableAttr *Attr,
2313                                Sema::AvailabilityMergeKind AMK) {
2314   // This function copies an attribute Attr from a previous declaration to the
2315   // new declaration D if the new declaration doesn't itself have that attribute
2316   // yet or if that attribute allows duplicates.
2317   // If you're adding a new attribute that requires logic different from
2318   // "use explicit attribute on decl if present, else use attribute from
2319   // previous decl", for example if the attribute needs to be consistent
2320   // between redeclarations, you need to call a custom merge function here.
2321   InheritableAttr *NewAttr = nullptr;
2322   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2323   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2324     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2325                                       AA->isImplicit(), AA->getIntroduced(),
2326                                       AA->getDeprecated(),
2327                                       AA->getObsoleted(), AA->getUnavailable(),
2328                                       AA->getMessage(), AA->getStrict(),
2329                                       AA->getReplacement(), AMK,
2330                                       AttrSpellingListIndex);
2331   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2332     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2333                                     AttrSpellingListIndex);
2334   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2335     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2336                                         AttrSpellingListIndex);
2337   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2338     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2339                                    AttrSpellingListIndex);
2340   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2341     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2342                                    AttrSpellingListIndex);
2343   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2344     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2345                                 FA->getFormatIdx(), FA->getFirstArg(),
2346                                 AttrSpellingListIndex);
2347   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2348     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2349                                  AttrSpellingListIndex);
2350   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2351     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2352                                        AttrSpellingListIndex,
2353                                        IA->getSemanticSpelling());
2354   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2355     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2356                                       &S.Context.Idents.get(AA->getSpelling()),
2357                                       AttrSpellingListIndex);
2358   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2359            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2360             isa<CUDAGlobalAttr>(Attr))) {
2361     // CUDA target attributes are part of function signature for
2362     // overloading purposes and must not be merged.
2363     return false;
2364   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2365     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2366   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2367     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2368   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2369     NewAttr = S.mergeInternalLinkageAttr(
2370         D, InternalLinkageA->getRange(),
2371         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2372         AttrSpellingListIndex);
2373   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2374     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2375                                 &S.Context.Idents.get(CommonA->getSpelling()),
2376                                 AttrSpellingListIndex);
2377   else if (isa<AlignedAttr>(Attr))
2378     // AlignedAttrs are handled separately, because we need to handle all
2379     // such attributes on a declaration at the same time.
2380     NewAttr = nullptr;
2381   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2382            (AMK == Sema::AMK_Override ||
2383             AMK == Sema::AMK_ProtocolImplementation))
2384     NewAttr = nullptr;
2385   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2386     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2387                               UA->getGuid());
2388   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2389     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2390
2391   if (NewAttr) {
2392     NewAttr->setInherited(true);
2393     D->addAttr(NewAttr);
2394     if (isa<MSInheritanceAttr>(NewAttr))
2395       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2396     return true;
2397   }
2398
2399   return false;
2400 }
2401
2402 static const Decl *getDefinition(const Decl *D) {
2403   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2404     return TD->getDefinition();
2405   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2406     const VarDecl *Def = VD->getDefinition();
2407     if (Def)
2408       return Def;
2409     return VD->getActingDefinition();
2410   }
2411   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2412     return FD->getDefinition();
2413   return nullptr;
2414 }
2415
2416 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2417   for (const auto *Attribute : D->attrs())
2418     if (Attribute->getKind() == Kind)
2419       return true;
2420   return false;
2421 }
2422
2423 /// checkNewAttributesAfterDef - If we already have a definition, check that
2424 /// there are no new attributes in this declaration.
2425 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2426   if (!New->hasAttrs())
2427     return;
2428
2429   const Decl *Def = getDefinition(Old);
2430   if (!Def || Def == New)
2431     return;
2432
2433   AttrVec &NewAttributes = New->getAttrs();
2434   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2435     const Attr *NewAttribute = NewAttributes[I];
2436
2437     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2438       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2439         Sema::SkipBodyInfo SkipBody;
2440         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2441
2442         // If we're skipping this definition, drop the "alias" attribute.
2443         if (SkipBody.ShouldSkip) {
2444           NewAttributes.erase(NewAttributes.begin() + I);
2445           --E;
2446           continue;
2447         }
2448       } else {
2449         VarDecl *VD = cast<VarDecl>(New);
2450         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2451                                 VarDecl::TentativeDefinition
2452                             ? diag::err_alias_after_tentative
2453                             : diag::err_redefinition;
2454         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2455         S.Diag(Def->getLocation(), diag::note_previous_definition);
2456         VD->setInvalidDecl();
2457       }
2458       ++I;
2459       continue;
2460     }
2461
2462     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2463       // Tentative definitions are only interesting for the alias check above.
2464       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2465         ++I;
2466         continue;
2467       }
2468     }
2469
2470     if (hasAttribute(Def, NewAttribute->getKind())) {
2471       ++I;
2472       continue; // regular attr merging will take care of validating this.
2473     }
2474
2475     if (isa<C11NoReturnAttr>(NewAttribute)) {
2476       // C's _Noreturn is allowed to be added to a function after it is defined.
2477       ++I;
2478       continue;
2479     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2480       if (AA->isAlignas()) {
2481         // C++11 [dcl.align]p6:
2482         //   if any declaration of an entity has an alignment-specifier,
2483         //   every defining declaration of that entity shall specify an
2484         //   equivalent alignment.
2485         // C11 6.7.5/7:
2486         //   If the definition of an object does not have an alignment
2487         //   specifier, any other declaration of that object shall also
2488         //   have no alignment specifier.
2489         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2490           << AA;
2491         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2492           << AA;
2493         NewAttributes.erase(NewAttributes.begin() + I);
2494         --E;
2495         continue;
2496       }
2497     }
2498
2499     S.Diag(NewAttribute->getLocation(),
2500            diag::warn_attribute_precede_definition);
2501     S.Diag(Def->getLocation(), diag::note_previous_definition);
2502     NewAttributes.erase(NewAttributes.begin() + I);
2503     --E;
2504   }
2505 }
2506
2507 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2508 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2509                                AvailabilityMergeKind AMK) {
2510   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2511     UsedAttr *NewAttr = OldAttr->clone(Context);
2512     NewAttr->setInherited(true);
2513     New->addAttr(NewAttr);
2514   }
2515
2516   if (!Old->hasAttrs() && !New->hasAttrs())
2517     return;
2518
2519   // Attributes declared post-definition are currently ignored.
2520   checkNewAttributesAfterDef(*this, New, Old);
2521
2522   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2523     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2524       if (OldA->getLabel() != NewA->getLabel()) {
2525         // This redeclaration changes __asm__ label.
2526         Diag(New->getLocation(), diag::err_different_asm_label);
2527         Diag(OldA->getLocation(), diag::note_previous_declaration);
2528       }
2529     } else if (Old->isUsed()) {
2530       // This redeclaration adds an __asm__ label to a declaration that has
2531       // already been ODR-used.
2532       Diag(New->getLocation(), diag::err_late_asm_label_name)
2533         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2534     }
2535   }
2536
2537   // Re-declaration cannot add abi_tag's.
2538   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2539     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2540       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2541         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2542                       NewTag) == OldAbiTagAttr->tags_end()) {
2543           Diag(NewAbiTagAttr->getLocation(),
2544                diag::err_new_abi_tag_on_redeclaration)
2545               << NewTag;
2546           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2547         }
2548       }
2549     } else {
2550       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2551       Diag(Old->getLocation(), diag::note_previous_declaration);
2552     }
2553   }
2554
2555   if (!Old->hasAttrs())
2556     return;
2557
2558   bool foundAny = New->hasAttrs();
2559
2560   // Ensure that any moving of objects within the allocated map is done before
2561   // we process them.
2562   if (!foundAny) New->setAttrs(AttrVec());
2563
2564   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2565     // Ignore deprecated/unavailable/availability attributes if requested.
2566     AvailabilityMergeKind LocalAMK = AMK_None;
2567     if (isa<DeprecatedAttr>(I) ||
2568         isa<UnavailableAttr>(I) ||
2569         isa<AvailabilityAttr>(I)) {
2570       switch (AMK) {
2571       case AMK_None:
2572         continue;
2573
2574       case AMK_Redeclaration:
2575       case AMK_Override:
2576       case AMK_ProtocolImplementation:
2577         LocalAMK = AMK;
2578         break;
2579       }
2580     }
2581
2582     // Already handled.
2583     if (isa<UsedAttr>(I))
2584       continue;
2585
2586     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2587       foundAny = true;
2588   }
2589
2590   if (mergeAlignedAttrs(*this, New, Old))
2591     foundAny = true;
2592
2593   if (!foundAny) New->dropAttrs();
2594 }
2595
2596 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2597 /// to the new one.
2598 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2599                                      const ParmVarDecl *oldDecl,
2600                                      Sema &S) {
2601   // C++11 [dcl.attr.depend]p2:
2602   //   The first declaration of a function shall specify the
2603   //   carries_dependency attribute for its declarator-id if any declaration
2604   //   of the function specifies the carries_dependency attribute.
2605   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2606   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2607     S.Diag(CDA->getLocation(),
2608            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2609     // Find the first declaration of the parameter.
2610     // FIXME: Should we build redeclaration chains for function parameters?
2611     const FunctionDecl *FirstFD =
2612       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2613     const ParmVarDecl *FirstVD =
2614       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2615     S.Diag(FirstVD->getLocation(),
2616            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2617   }
2618
2619   if (!oldDecl->hasAttrs())
2620     return;
2621
2622   bool foundAny = newDecl->hasAttrs();
2623
2624   // Ensure that any moving of objects within the allocated map is
2625   // done before we process them.
2626   if (!foundAny) newDecl->setAttrs(AttrVec());
2627
2628   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2629     if (!DeclHasAttr(newDecl, I)) {
2630       InheritableAttr *newAttr =
2631         cast<InheritableParamAttr>(I->clone(S.Context));
2632       newAttr->setInherited(true);
2633       newDecl->addAttr(newAttr);
2634       foundAny = true;
2635     }
2636   }
2637
2638   if (!foundAny) newDecl->dropAttrs();
2639 }
2640
2641 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2642                                 const ParmVarDecl *OldParam,
2643                                 Sema &S) {
2644   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2645     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2646       if (*Oldnullability != *Newnullability) {
2647         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2648           << DiagNullabilityKind(
2649                *Newnullability,
2650                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2651                 != 0))
2652           << DiagNullabilityKind(
2653                *Oldnullability,
2654                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2655                 != 0));
2656         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2657       }
2658     } else {
2659       QualType NewT = NewParam->getType();
2660       NewT = S.Context.getAttributedType(
2661                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2662                          NewT, NewT);
2663       NewParam->setType(NewT);
2664     }
2665   }
2666 }
2667
2668 namespace {
2669
2670 /// Used in MergeFunctionDecl to keep track of function parameters in
2671 /// C.
2672 struct GNUCompatibleParamWarning {
2673   ParmVarDecl *OldParm;
2674   ParmVarDecl *NewParm;
2675   QualType PromotedType;
2676 };
2677
2678 } // end anonymous namespace
2679
2680 /// getSpecialMember - get the special member enum for a method.
2681 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2682   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2683     if (Ctor->isDefaultConstructor())
2684       return Sema::CXXDefaultConstructor;
2685
2686     if (Ctor->isCopyConstructor())
2687       return Sema::CXXCopyConstructor;
2688
2689     if (Ctor->isMoveConstructor())
2690       return Sema::CXXMoveConstructor;
2691   } else if (isa<CXXDestructorDecl>(MD)) {
2692     return Sema::CXXDestructor;
2693   } else if (MD->isCopyAssignmentOperator()) {
2694     return Sema::CXXCopyAssignment;
2695   } else if (MD->isMoveAssignmentOperator()) {
2696     return Sema::CXXMoveAssignment;
2697   }
2698
2699   return Sema::CXXInvalid;
2700 }
2701
2702 // Determine whether the previous declaration was a definition, implicit
2703 // declaration, or a declaration.
2704 template <typename T>
2705 static std::pair<diag::kind, SourceLocation>
2706 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2707   diag::kind PrevDiag;
2708   SourceLocation OldLocation = Old->getLocation();
2709   if (Old->isThisDeclarationADefinition())
2710     PrevDiag = diag::note_previous_definition;
2711   else if (Old->isImplicit()) {
2712     PrevDiag = diag::note_previous_implicit_declaration;
2713     if (OldLocation.isInvalid())
2714       OldLocation = New->getLocation();
2715   } else
2716     PrevDiag = diag::note_previous_declaration;
2717   return std::make_pair(PrevDiag, OldLocation);
2718 }
2719
2720 /// canRedefineFunction - checks if a function can be redefined. Currently,
2721 /// only extern inline functions can be redefined, and even then only in
2722 /// GNU89 mode.
2723 static bool canRedefineFunction(const FunctionDecl *FD,
2724                                 const LangOptions& LangOpts) {
2725   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2726           !LangOpts.CPlusPlus &&
2727           FD->isInlineSpecified() &&
2728           FD->getStorageClass() == SC_Extern);
2729 }
2730
2731 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2732   const AttributedType *AT = T->getAs<AttributedType>();
2733   while (AT && !AT->isCallingConv())
2734     AT = AT->getModifiedType()->getAs<AttributedType>();
2735   return AT;
2736 }
2737
2738 template <typename T>
2739 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2740   const DeclContext *DC = Old->getDeclContext();
2741   if (DC->isRecord())
2742     return false;
2743
2744   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2745   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2746     return true;
2747   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2748     return true;
2749   return false;
2750 }
2751
2752 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2753 static bool isExternC(VarTemplateDecl *) { return false; }
2754
2755 /// \brief Check whether a redeclaration of an entity introduced by a
2756 /// using-declaration is valid, given that we know it's not an overload
2757 /// (nor a hidden tag declaration).
2758 template<typename ExpectedDecl>
2759 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2760                                    ExpectedDecl *New) {
2761   // C++11 [basic.scope.declarative]p4:
2762   //   Given a set of declarations in a single declarative region, each of
2763   //   which specifies the same unqualified name,
2764   //   -- they shall all refer to the same entity, or all refer to functions
2765   //      and function templates; or
2766   //   -- exactly one declaration shall declare a class name or enumeration
2767   //      name that is not a typedef name and the other declarations shall all
2768   //      refer to the same variable or enumerator, or all refer to functions
2769   //      and function templates; in this case the class name or enumeration
2770   //      name is hidden (3.3.10).
2771
2772   // C++11 [namespace.udecl]p14:
2773   //   If a function declaration in namespace scope or block scope has the
2774   //   same name and the same parameter-type-list as a function introduced
2775   //   by a using-declaration, and the declarations do not declare the same
2776   //   function, the program is ill-formed.
2777
2778   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2779   if (Old &&
2780       !Old->getDeclContext()->getRedeclContext()->Equals(
2781           New->getDeclContext()->getRedeclContext()) &&
2782       !(isExternC(Old) && isExternC(New)))
2783     Old = nullptr;
2784
2785   if (!Old) {
2786     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2787     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2788     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2789     return true;
2790   }
2791   return false;
2792 }
2793
2794 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2795                                             const FunctionDecl *B) {
2796   assert(A->getNumParams() == B->getNumParams());
2797
2798   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2799     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2800     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2801     if (AttrA == AttrB)
2802       return true;
2803     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2804   };
2805
2806   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2807 }
2808
2809 /// MergeFunctionDecl - We just parsed a function 'New' from
2810 /// declarator D which has the same name and scope as a previous
2811 /// declaration 'Old'.  Figure out how to resolve this situation,
2812 /// merging decls or emitting diagnostics as appropriate.
2813 ///
2814 /// In C++, New and Old must be declarations that are not
2815 /// overloaded. Use IsOverload to determine whether New and Old are
2816 /// overloaded, and to select the Old declaration that New should be
2817 /// merged with.
2818 ///
2819 /// Returns true if there was an error, false otherwise.
2820 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2821                              Scope *S, bool MergeTypeWithOld) {
2822   // Verify the old decl was also a function.
2823   FunctionDecl *Old = OldD->getAsFunction();
2824   if (!Old) {
2825     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2826       if (New->getFriendObjectKind()) {
2827         Diag(New->getLocation(), diag::err_using_decl_friend);
2828         Diag(Shadow->getTargetDecl()->getLocation(),
2829              diag::note_using_decl_target);
2830         Diag(Shadow->getUsingDecl()->getLocation(),
2831              diag::note_using_decl) << 0;
2832         return true;
2833       }
2834
2835       // Check whether the two declarations might declare the same function.
2836       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2837         return true;
2838       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2839     } else {
2840       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2841         << New->getDeclName();
2842       Diag(OldD->getLocation(), diag::note_previous_definition);
2843       return true;
2844     }
2845   }
2846
2847   // If the old declaration is invalid, just give up here.
2848   if (Old->isInvalidDecl())
2849     return true;
2850
2851   diag::kind PrevDiag;
2852   SourceLocation OldLocation;
2853   std::tie(PrevDiag, OldLocation) =
2854       getNoteDiagForInvalidRedeclaration(Old, New);
2855
2856   // Don't complain about this if we're in GNU89 mode and the old function
2857   // is an extern inline function.
2858   // Don't complain about specializations. They are not supposed to have
2859   // storage classes.
2860   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2861       New->getStorageClass() == SC_Static &&
2862       Old->hasExternalFormalLinkage() &&
2863       !New->getTemplateSpecializationInfo() &&
2864       !canRedefineFunction(Old, getLangOpts())) {
2865     if (getLangOpts().MicrosoftExt) {
2866       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2867       Diag(OldLocation, PrevDiag);
2868     } else {
2869       Diag(New->getLocation(), diag::err_static_non_static) << New;
2870       Diag(OldLocation, PrevDiag);
2871       return true;
2872     }
2873   }
2874
2875   if (New->hasAttr<InternalLinkageAttr>() &&
2876       !Old->hasAttr<InternalLinkageAttr>()) {
2877     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2878         << New->getDeclName();
2879     Diag(Old->getLocation(), diag::note_previous_definition);
2880     New->dropAttr<InternalLinkageAttr>();
2881   }
2882
2883   // If a function is first declared with a calling convention, but is later
2884   // declared or defined without one, all following decls assume the calling
2885   // convention of the first.
2886   //
2887   // It's OK if a function is first declared without a calling convention,
2888   // but is later declared or defined with the default calling convention.
2889   //
2890   // To test if either decl has an explicit calling convention, we look for
2891   // AttributedType sugar nodes on the type as written.  If they are missing or
2892   // were canonicalized away, we assume the calling convention was implicit.
2893   //
2894   // Note also that we DO NOT return at this point, because we still have
2895   // other tests to run.
2896   QualType OldQType = Context.getCanonicalType(Old->getType());
2897   QualType NewQType = Context.getCanonicalType(New->getType());
2898   const FunctionType *OldType = cast<FunctionType>(OldQType);
2899   const FunctionType *NewType = cast<FunctionType>(NewQType);
2900   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2901   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2902   bool RequiresAdjustment = false;
2903
2904   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2905     FunctionDecl *First = Old->getFirstDecl();
2906     const FunctionType *FT =
2907         First->getType().getCanonicalType()->castAs<FunctionType>();
2908     FunctionType::ExtInfo FI = FT->getExtInfo();
2909     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2910     if (!NewCCExplicit) {
2911       // Inherit the CC from the previous declaration if it was specified
2912       // there but not here.
2913       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2914       RequiresAdjustment = true;
2915     } else {
2916       // Calling conventions aren't compatible, so complain.
2917       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2918       Diag(New->getLocation(), diag::err_cconv_change)
2919         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2920         << !FirstCCExplicit
2921         << (!FirstCCExplicit ? "" :
2922             FunctionType::getNameForCallConv(FI.getCC()));
2923
2924       // Put the note on the first decl, since it is the one that matters.
2925       Diag(First->getLocation(), diag::note_previous_declaration);
2926       return true;
2927     }
2928   }
2929
2930   // FIXME: diagnose the other way around?
2931   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2932     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2933     RequiresAdjustment = true;
2934   }
2935
2936   // Merge regparm attribute.
2937   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2938       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2939     if (NewTypeInfo.getHasRegParm()) {
2940       Diag(New->getLocation(), diag::err_regparm_mismatch)
2941         << NewType->getRegParmType()
2942         << OldType->getRegParmType();
2943       Diag(OldLocation, diag::note_previous_declaration);
2944       return true;
2945     }
2946
2947     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2948     RequiresAdjustment = true;
2949   }
2950
2951   // Merge ns_returns_retained attribute.
2952   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2953     if (NewTypeInfo.getProducesResult()) {
2954       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2955       Diag(OldLocation, diag::note_previous_declaration);
2956       return true;
2957     }
2958
2959     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2960     RequiresAdjustment = true;
2961   }
2962
2963   if (RequiresAdjustment) {
2964     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2965     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2966     New->setType(QualType(AdjustedType, 0));
2967     NewQType = Context.getCanonicalType(New->getType());
2968     NewType = cast<FunctionType>(NewQType);
2969   }
2970
2971   // If this redeclaration makes the function inline, we may need to add it to
2972   // UndefinedButUsed.
2973   if (!Old->isInlined() && New->isInlined() &&
2974       !New->hasAttr<GNUInlineAttr>() &&
2975       !getLangOpts().GNUInline &&
2976       Old->isUsed(false) &&
2977       !Old->isDefined() && !New->isThisDeclarationADefinition())
2978     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2979                                            SourceLocation()));
2980
2981   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2982   // about it.
2983   if (New->hasAttr<GNUInlineAttr>() &&
2984       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2985     UndefinedButUsed.erase(Old->getCanonicalDecl());
2986   }
2987
2988   // If pass_object_size params don't match up perfectly, this isn't a valid
2989   // redeclaration.
2990   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2991       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2992     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2993         << New->getDeclName();
2994     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2995     return true;
2996   }
2997
2998   if (getLangOpts().CPlusPlus) {
2999     // C++1z [over.load]p2
3000     //   Certain function declarations cannot be overloaded:
3001     //     -- Function declarations that differ only in the return type,
3002     //        the exception specification, or both cannot be overloaded.
3003
3004     // Check the exception specifications match. This may recompute the type of
3005     // both Old and New if it resolved exception specifications, so grab the
3006     // types again after this. Because this updates the type, we do this before
3007     // any of the other checks below, which may update the "de facto" NewQType
3008     // but do not necessarily update the type of New.
3009     if (CheckEquivalentExceptionSpec(Old, New))
3010       return true;
3011     OldQType = Context.getCanonicalType(Old->getType());
3012     NewQType = Context.getCanonicalType(New->getType());
3013
3014     // Go back to the type source info to compare the declared return types,
3015     // per C++1y [dcl.type.auto]p13:
3016     //   Redeclarations or specializations of a function or function template
3017     //   with a declared return type that uses a placeholder type shall also
3018     //   use that placeholder, not a deduced type.
3019     QualType OldDeclaredReturnType =
3020         (Old->getTypeSourceInfo()
3021              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3022              : OldType)->getReturnType();
3023     QualType NewDeclaredReturnType =
3024         (New->getTypeSourceInfo()
3025              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3026              : NewType)->getReturnType();
3027     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3028         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3029           New->isLocalExternDecl())) {
3030       QualType ResQT;
3031       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3032           OldDeclaredReturnType->isObjCObjectPointerType())
3033         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3034       if (ResQT.isNull()) {
3035         if (New->isCXXClassMember() && New->isOutOfLine())
3036           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3037               << New << New->getReturnTypeSourceRange();
3038         else
3039           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3040               << New->getReturnTypeSourceRange();
3041         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3042                                     << Old->getReturnTypeSourceRange();
3043         return true;
3044       }
3045       else
3046         NewQType = ResQT;
3047     }
3048
3049     QualType OldReturnType = OldType->getReturnType();
3050     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3051     if (OldReturnType != NewReturnType) {
3052       // If this function has a deduced return type and has already been
3053       // defined, copy the deduced value from the old declaration.
3054       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3055       if (OldAT && OldAT->isDeduced()) {
3056         New->setType(
3057             SubstAutoType(New->getType(),
3058                           OldAT->isDependentType() ? Context.DependentTy
3059                                                    : OldAT->getDeducedType()));
3060         NewQType = Context.getCanonicalType(
3061             SubstAutoType(NewQType,
3062                           OldAT->isDependentType() ? Context.DependentTy
3063                                                    : OldAT->getDeducedType()));
3064       }
3065     }
3066
3067     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3068     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3069     if (OldMethod && NewMethod) {
3070       // Preserve triviality.
3071       NewMethod->setTrivial(OldMethod->isTrivial());
3072
3073       // MSVC allows explicit template specialization at class scope:
3074       // 2 CXXMethodDecls referring to the same function will be injected.
3075       // We don't want a redeclaration error.
3076       bool IsClassScopeExplicitSpecialization =
3077                               OldMethod->isFunctionTemplateSpecialization() &&
3078                               NewMethod->isFunctionTemplateSpecialization();
3079       bool isFriend = NewMethod->getFriendObjectKind();
3080
3081       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3082           !IsClassScopeExplicitSpecialization) {
3083         //    -- Member function declarations with the same name and the
3084         //       same parameter types cannot be overloaded if any of them
3085         //       is a static member function declaration.
3086         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3087           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3088           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3089           return true;
3090         }
3091
3092         // C++ [class.mem]p1:
3093         //   [...] A member shall not be declared twice in the
3094         //   member-specification, except that a nested class or member
3095         //   class template can be declared and then later defined.
3096         if (!inTemplateInstantiation()) {
3097           unsigned NewDiag;
3098           if (isa<CXXConstructorDecl>(OldMethod))
3099             NewDiag = diag::err_constructor_redeclared;
3100           else if (isa<CXXDestructorDecl>(NewMethod))
3101             NewDiag = diag::err_destructor_redeclared;
3102           else if (isa<CXXConversionDecl>(NewMethod))
3103             NewDiag = diag::err_conv_function_redeclared;
3104           else
3105             NewDiag = diag::err_member_redeclared;
3106
3107           Diag(New->getLocation(), NewDiag);
3108         } else {
3109           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3110             << New << New->getType();
3111         }
3112         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3113         return true;
3114
3115       // Complain if this is an explicit declaration of a special
3116       // member that was initially declared implicitly.
3117       //
3118       // As an exception, it's okay to befriend such methods in order
3119       // to permit the implicit constructor/destructor/operator calls.
3120       } else if (OldMethod->isImplicit()) {
3121         if (isFriend) {
3122           NewMethod->setImplicit();
3123         } else {
3124           Diag(NewMethod->getLocation(),
3125                diag::err_definition_of_implicitly_declared_member)
3126             << New << getSpecialMember(OldMethod);
3127           return true;
3128         }
3129       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3130         Diag(NewMethod->getLocation(),
3131              diag::err_definition_of_explicitly_defaulted_member)
3132           << getSpecialMember(OldMethod);
3133         return true;
3134       }
3135     }
3136
3137     // C++11 [dcl.attr.noreturn]p1:
3138     //   The first declaration of a function shall specify the noreturn
3139     //   attribute if any declaration of that function specifies the noreturn
3140     //   attribute.
3141     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3142     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3143       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3144       Diag(Old->getFirstDecl()->getLocation(),
3145            diag::note_noreturn_missing_first_decl);
3146     }
3147
3148     // C++11 [dcl.attr.depend]p2:
3149     //   The first declaration of a function shall specify the
3150     //   carries_dependency attribute for its declarator-id if any declaration
3151     //   of the function specifies the carries_dependency attribute.
3152     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3153     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3154       Diag(CDA->getLocation(),
3155            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3156       Diag(Old->getFirstDecl()->getLocation(),
3157            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3158     }
3159
3160     // (C++98 8.3.5p3):
3161     //   All declarations for a function shall agree exactly in both the
3162     //   return type and the parameter-type-list.
3163     // We also want to respect all the extended bits except noreturn.
3164
3165     // noreturn should now match unless the old type info didn't have it.
3166     QualType OldQTypeForComparison = OldQType;
3167     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3168       auto *OldType = OldQType->castAs<FunctionProtoType>();
3169       const FunctionType *OldTypeForComparison
3170         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3171       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3172       assert(OldQTypeForComparison.isCanonical());
3173     }
3174
3175     if (haveIncompatibleLanguageLinkages(Old, New)) {
3176       // As a special case, retain the language linkage from previous
3177       // declarations of a friend function as an extension.
3178       //
3179       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3180       // and is useful because there's otherwise no way to specify language
3181       // linkage within class scope.
3182       //
3183       // Check cautiously as the friend object kind isn't yet complete.
3184       if (New->getFriendObjectKind() != Decl::FOK_None) {
3185         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3186         Diag(OldLocation, PrevDiag);
3187       } else {
3188         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3189         Diag(OldLocation, PrevDiag);
3190         return true;
3191       }
3192     }
3193
3194     if (OldQTypeForComparison == NewQType)
3195       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3196
3197     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3198         New->isLocalExternDecl()) {
3199       // It's OK if we couldn't merge types for a local function declaraton
3200       // if either the old or new type is dependent. We'll merge the types
3201       // when we instantiate the function.
3202       return false;
3203     }
3204
3205     // Fall through for conflicting redeclarations and redefinitions.
3206   }
3207
3208   // C: Function types need to be compatible, not identical. This handles
3209   // duplicate function decls like "void f(int); void f(enum X);" properly.
3210   if (!getLangOpts().CPlusPlus &&
3211       Context.typesAreCompatible(OldQType, NewQType)) {
3212     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3213     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3214     const FunctionProtoType *OldProto = nullptr;
3215     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3216         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3217       // The old declaration provided a function prototype, but the
3218       // new declaration does not. Merge in the prototype.
3219       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3220       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3221       NewQType =
3222           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3223                                   OldProto->getExtProtoInfo());
3224       New->setType(NewQType);
3225       New->setHasInheritedPrototype();
3226
3227       // Synthesize parameters with the same types.
3228       SmallVector<ParmVarDecl*, 16> Params;
3229       for (const auto &ParamType : OldProto->param_types()) {
3230         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3231                                                  SourceLocation(), nullptr,
3232                                                  ParamType, /*TInfo=*/nullptr,
3233                                                  SC_None, nullptr);
3234         Param->setScopeInfo(0, Params.size());
3235         Param->setImplicit();
3236         Params.push_back(Param);
3237       }
3238
3239       New->setParams(Params);
3240     }
3241
3242     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3243   }
3244
3245   // GNU C permits a K&R definition to follow a prototype declaration
3246   // if the declared types of the parameters in the K&R definition
3247   // match the types in the prototype declaration, even when the
3248   // promoted types of the parameters from the K&R definition differ
3249   // from the types in the prototype. GCC then keeps the types from
3250   // the prototype.
3251   //
3252   // If a variadic prototype is followed by a non-variadic K&R definition,
3253   // the K&R definition becomes variadic.  This is sort of an edge case, but
3254   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3255   // C99 6.9.1p8.
3256   if (!getLangOpts().CPlusPlus &&
3257       Old->hasPrototype() && !New->hasPrototype() &&
3258       New->getType()->getAs<FunctionProtoType>() &&
3259       Old->getNumParams() == New->getNumParams()) {
3260     SmallVector<QualType, 16> ArgTypes;
3261     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3262     const FunctionProtoType *OldProto
3263       = Old->getType()->getAs<FunctionProtoType>();
3264     const FunctionProtoType *NewProto
3265       = New->getType()->getAs<FunctionProtoType>();
3266
3267     // Determine whether this is the GNU C extension.
3268     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3269                                                NewProto->getReturnType());
3270     bool LooseCompatible = !MergedReturn.isNull();
3271     for (unsigned Idx = 0, End = Old->getNumParams();
3272          LooseCompatible && Idx != End; ++Idx) {
3273       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3274       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3275       if (Context.typesAreCompatible(OldParm->getType(),
3276                                      NewProto->getParamType(Idx))) {
3277         ArgTypes.push_back(NewParm->getType());
3278       } else if (Context.typesAreCompatible(OldParm->getType(),
3279                                             NewParm->getType(),
3280                                             /*CompareUnqualified=*/true)) {
3281         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3282                                            NewProto->getParamType(Idx) };
3283         Warnings.push_back(Warn);
3284         ArgTypes.push_back(NewParm->getType());
3285       } else
3286         LooseCompatible = false;
3287     }
3288
3289     if (LooseCompatible) {
3290       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3291         Diag(Warnings[Warn].NewParm->getLocation(),
3292              diag::ext_param_promoted_not_compatible_with_prototype)
3293           << Warnings[Warn].PromotedType
3294           << Warnings[Warn].OldParm->getType();
3295         if (Warnings[Warn].OldParm->getLocation().isValid())
3296           Diag(Warnings[Warn].OldParm->getLocation(),
3297                diag::note_previous_declaration);
3298       }
3299
3300       if (MergeTypeWithOld)
3301         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3302                                              OldProto->getExtProtoInfo()));
3303       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3304     }
3305
3306     // Fall through to diagnose conflicting types.
3307   }
3308
3309   // A function that has already been declared has been redeclared or
3310   // defined with a different type; show an appropriate diagnostic.
3311
3312   // If the previous declaration was an implicitly-generated builtin
3313   // declaration, then at the very least we should use a specialized note.
3314   unsigned BuiltinID;
3315   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3316     // If it's actually a library-defined builtin function like 'malloc'
3317     // or 'printf', just warn about the incompatible redeclaration.
3318     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3319       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3320       Diag(OldLocation, diag::note_previous_builtin_declaration)
3321         << Old << Old->getType();
3322
3323       // If this is a global redeclaration, just forget hereafter
3324       // about the "builtin-ness" of the function.
3325       //
3326       // Doing this for local extern declarations is problematic.  If
3327       // the builtin declaration remains visible, a second invalid
3328       // local declaration will produce a hard error; if it doesn't
3329       // remain visible, a single bogus local redeclaration (which is
3330       // actually only a warning) could break all the downstream code.
3331       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3332         New->getIdentifier()->revertBuiltin();
3333
3334       return false;
3335     }
3336
3337     PrevDiag = diag::note_previous_builtin_declaration;
3338   }
3339
3340   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3341   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3342   return true;
3343 }
3344
3345 /// \brief Completes the merge of two function declarations that are
3346 /// known to be compatible.
3347 ///
3348 /// This routine handles the merging of attributes and other
3349 /// properties of function declarations from the old declaration to
3350 /// the new declaration, once we know that New is in fact a
3351 /// redeclaration of Old.
3352 ///
3353 /// \returns false
3354 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3355                                         Scope *S, bool MergeTypeWithOld) {
3356   // Merge the attributes
3357   mergeDeclAttributes(New, Old);
3358
3359   // Merge "pure" flag.
3360   if (Old->isPure())
3361     New->setPure();
3362
3363   // Merge "used" flag.
3364   if (Old->getMostRecentDecl()->isUsed(false))
3365     New->setIsUsed();
3366
3367   // Merge attributes from the parameters.  These can mismatch with K&R
3368   // declarations.
3369   if (New->getNumParams() == Old->getNumParams())
3370       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3371         ParmVarDecl *NewParam = New->getParamDecl(i);
3372         ParmVarDecl *OldParam = Old->getParamDecl(i);
3373         mergeParamDeclAttributes(NewParam, OldParam, *this);
3374         mergeParamDeclTypes(NewParam, OldParam, *this);
3375       }
3376
3377   if (getLangOpts().CPlusPlus)
3378     return MergeCXXFunctionDecl(New, Old, S);
3379
3380   // Merge the function types so the we get the composite types for the return
3381   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3382   // was visible.
3383   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3384   if (!Merged.isNull() && MergeTypeWithOld)
3385     New->setType(Merged);
3386
3387   return false;
3388 }
3389
3390 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3391                                 ObjCMethodDecl *oldMethod) {
3392   // Merge the attributes, including deprecated/unavailable
3393   AvailabilityMergeKind MergeKind =
3394     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3395       ? AMK_ProtocolImplementation
3396       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3397                                                        : AMK_Override;
3398
3399   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3400
3401   // Merge attributes from the parameters.
3402   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3403                                        oe = oldMethod->param_end();
3404   for (ObjCMethodDecl::param_iterator
3405          ni = newMethod->param_begin(), ne = newMethod->param_end();
3406        ni != ne && oi != oe; ++ni, ++oi)
3407     mergeParamDeclAttributes(*ni, *oi, *this);
3408
3409   CheckObjCMethodOverride(newMethod, oldMethod);
3410 }
3411
3412 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3413   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3414
3415   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3416          ? diag::err_redefinition_different_type
3417          : diag::err_redeclaration_different_type)
3418     << New->getDeclName() << New->getType() << Old->getType();
3419
3420   diag::kind PrevDiag;
3421   SourceLocation OldLocation;
3422   std::tie(PrevDiag, OldLocation)
3423     = getNoteDiagForInvalidRedeclaration(Old, New);
3424   S.Diag(OldLocation, PrevDiag);
3425   New->setInvalidDecl();
3426 }
3427
3428 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3429 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3430 /// emitting diagnostics as appropriate.
3431 ///
3432 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3433 /// to here in AddInitializerToDecl. We can't check them before the initializer
3434 /// is attached.
3435 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3436                              bool MergeTypeWithOld) {
3437   if (New->isInvalidDecl() || Old->isInvalidDecl())
3438     return;
3439
3440   QualType MergedT;
3441   if (getLangOpts().CPlusPlus) {
3442     if (New->getType()->isUndeducedType()) {
3443       // We don't know what the new type is until the initializer is attached.
3444       return;
3445     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3446       // These could still be something that needs exception specs checked.
3447       return MergeVarDeclExceptionSpecs(New, Old);
3448     }
3449     // C++ [basic.link]p10:
3450     //   [...] the types specified by all declarations referring to a given
3451     //   object or function shall be identical, except that declarations for an
3452     //   array object can specify array types that differ by the presence or
3453     //   absence of a major array bound (8.3.4).
3454     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3455       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3456       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3457
3458       // We are merging a variable declaration New into Old. If it has an array
3459       // bound, and that bound differs from Old's bound, we should diagnose the
3460       // mismatch.
3461       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3462         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3463              PrevVD = PrevVD->getPreviousDecl()) {
3464           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3465           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3466             continue;
3467
3468           if (!Context.hasSameType(NewArray, PrevVDTy))
3469             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3470         }
3471       }
3472
3473       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3474         if (Context.hasSameType(OldArray->getElementType(),
3475                                 NewArray->getElementType()))
3476           MergedT = New->getType();
3477       }
3478       // FIXME: Check visibility. New is hidden but has a complete type. If New
3479       // has no array bound, it should not inherit one from Old, if Old is not
3480       // visible.
3481       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3482         if (Context.hasSameType(OldArray->getElementType(),
3483                                 NewArray->getElementType()))
3484           MergedT = Old->getType();
3485       }
3486     }
3487     else if (New->getType()->isObjCObjectPointerType() &&
3488                Old->getType()->isObjCObjectPointerType()) {
3489       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3490                                               Old->getType());
3491     }
3492   } else {
3493     // C 6.2.7p2:
3494     //   All declarations that refer to the same object or function shall have
3495     //   compatible type.
3496     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3497   }
3498   if (MergedT.isNull()) {
3499     // It's OK if we couldn't merge types if either type is dependent, for a
3500     // block-scope variable. In other cases (static data members of class
3501     // templates, variable templates, ...), we require the types to be
3502     // equivalent.
3503     // FIXME: The C++ standard doesn't say anything about this.
3504     if ((New->getType()->isDependentType() ||
3505          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3506       // If the old type was dependent, we can't merge with it, so the new type
3507       // becomes dependent for now. We'll reproduce the original type when we
3508       // instantiate the TypeSourceInfo for the variable.
3509       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3510         New->setType(Context.DependentTy);
3511       return;
3512     }
3513     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3514   }
3515
3516   // Don't actually update the type on the new declaration if the old
3517   // declaration was an extern declaration in a different scope.
3518   if (MergeTypeWithOld)
3519     New->setType(MergedT);
3520 }
3521
3522 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3523                                   LookupResult &Previous) {
3524   // C11 6.2.7p4:
3525   //   For an identifier with internal or external linkage declared
3526   //   in a scope in which a prior declaration of that identifier is
3527   //   visible, if the prior declaration specifies internal or
3528   //   external linkage, the type of the identifier at the later
3529   //   declaration becomes the composite type.
3530   //
3531   // If the variable isn't visible, we do not merge with its type.
3532   if (Previous.isShadowed())
3533     return false;
3534
3535   if (S.getLangOpts().CPlusPlus) {
3536     // C++11 [dcl.array]p3:
3537     //   If there is a preceding declaration of the entity in the same
3538     //   scope in which the bound was specified, an omitted array bound
3539     //   is taken to be the same as in that earlier declaration.
3540     return NewVD->isPreviousDeclInSameBlockScope() ||
3541            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3542             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3543   } else {
3544     // If the old declaration was function-local, don't merge with its
3545     // type unless we're in the same function.
3546     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3547            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3548   }
3549 }
3550
3551 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3552 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3553 /// situation, merging decls or emitting diagnostics as appropriate.
3554 ///
3555 /// Tentative definition rules (C99 6.9.2p2) are checked by
3556 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3557 /// definitions here, since the initializer hasn't been attached.
3558 ///
3559 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3560   // If the new decl is already invalid, don't do any other checking.
3561   if (New->isInvalidDecl())
3562     return;
3563
3564   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3565     return;
3566
3567   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3568
3569   // Verify the old decl was also a variable or variable template.
3570   VarDecl *Old = nullptr;
3571   VarTemplateDecl *OldTemplate = nullptr;
3572   if (Previous.isSingleResult()) {
3573     if (NewTemplate) {
3574       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3575       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3576
3577       if (auto *Shadow =
3578               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3579         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3580           return New->setInvalidDecl();
3581     } else {
3582       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3583
3584       if (auto *Shadow =
3585               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3586         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3587           return New->setInvalidDecl();
3588     }
3589   }
3590   if (!Old) {
3591     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3592       << New->getDeclName();
3593     Diag(Previous.getRepresentativeDecl()->getLocation(),
3594          diag::note_previous_definition);
3595     return New->setInvalidDecl();
3596   }
3597
3598   // Ensure the template parameters are compatible.
3599   if (NewTemplate &&
3600       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3601                                       OldTemplate->getTemplateParameters(),
3602                                       /*Complain=*/true, TPL_TemplateMatch))
3603     return New->setInvalidDecl();
3604
3605   // C++ [class.mem]p1:
3606   //   A member shall not be declared twice in the member-specification [...]
3607   //
3608   // Here, we need only consider static data members.
3609   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3610     Diag(New->getLocation(), diag::err_duplicate_member)
3611       << New->getIdentifier();
3612     Diag(Old->getLocation(), diag::note_previous_declaration);
3613     New->setInvalidDecl();
3614   }
3615
3616   mergeDeclAttributes(New, Old);
3617   // Warn if an already-declared variable is made a weak_import in a subsequent
3618   // declaration
3619   if (New->hasAttr<WeakImportAttr>() &&
3620       Old->getStorageClass() == SC_None &&
3621       !Old->hasAttr<WeakImportAttr>()) {
3622     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3623     Diag(Old->getLocation(), diag::note_previous_definition);
3624     // Remove weak_import attribute on new declaration.
3625     New->dropAttr<WeakImportAttr>();
3626   }
3627
3628   if (New->hasAttr<InternalLinkageAttr>() &&
3629       !Old->hasAttr<InternalLinkageAttr>()) {
3630     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3631         << New->getDeclName();
3632     Diag(Old->getLocation(), diag::note_previous_definition);
3633     New->dropAttr<InternalLinkageAttr>();
3634   }
3635
3636   // Merge the types.
3637   VarDecl *MostRecent = Old->getMostRecentDecl();
3638   if (MostRecent != Old) {
3639     MergeVarDeclTypes(New, MostRecent,
3640                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3641     if (New->isInvalidDecl())
3642       return;
3643   }
3644
3645   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3646   if (New->isInvalidDecl())
3647     return;
3648
3649   diag::kind PrevDiag;
3650   SourceLocation OldLocation;
3651   std::tie(PrevDiag, OldLocation) =
3652       getNoteDiagForInvalidRedeclaration(Old, New);
3653
3654   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3655   if (New->getStorageClass() == SC_Static &&
3656       !New->isStaticDataMember() &&
3657       Old->hasExternalFormalLinkage()) {
3658     if (getLangOpts().MicrosoftExt) {
3659       Diag(New->getLocation(), diag::ext_static_non_static)
3660           << New->getDeclName();
3661       Diag(OldLocation, PrevDiag);
3662     } else {
3663       Diag(New->getLocation(), diag::err_static_non_static)
3664           << New->getDeclName();
3665       Diag(OldLocation, PrevDiag);
3666       return New->setInvalidDecl();
3667     }
3668   }
3669   // C99 6.2.2p4:
3670   //   For an identifier declared with the storage-class specifier
3671   //   extern in a scope in which a prior declaration of that
3672   //   identifier is visible,23) if the prior declaration specifies
3673   //   internal or external linkage, the linkage of the identifier at
3674   //   the later declaration is the same as the linkage specified at
3675   //   the prior declaration. If no prior declaration is visible, or
3676   //   if the prior declaration specifies no linkage, then the
3677   //   identifier has external linkage.
3678   if (New->hasExternalStorage() && Old->hasLinkage())
3679     /* Okay */;
3680   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3681            !New->isStaticDataMember() &&
3682            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3683     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3684     Diag(OldLocation, PrevDiag);
3685     return New->setInvalidDecl();
3686   }
3687
3688   // Check if extern is followed by non-extern and vice-versa.
3689   if (New->hasExternalStorage() &&
3690       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3691     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3692     Diag(OldLocation, PrevDiag);
3693     return New->setInvalidDecl();
3694   }
3695   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3696       !New->hasExternalStorage()) {
3697     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3698     Diag(OldLocation, PrevDiag);
3699     return New->setInvalidDecl();
3700   }
3701
3702   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3703
3704   // FIXME: The test for external storage here seems wrong? We still
3705   // need to check for mismatches.
3706   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3707       // Don't complain about out-of-line definitions of static members.
3708       !(Old->getLexicalDeclContext()->isRecord() &&
3709         !New->getLexicalDeclContext()->isRecord())) {
3710     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3711     Diag(OldLocation, PrevDiag);
3712     return New->setInvalidDecl();
3713   }
3714
3715   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3716     if (VarDecl *Def = Old->getDefinition()) {
3717       // C++1z [dcl.fcn.spec]p4:
3718       //   If the definition of a variable appears in a translation unit before
3719       //   its first declaration as inline, the program is ill-formed.
3720       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3721       Diag(Def->getLocation(), diag::note_previous_definition);
3722     }
3723   }
3724
3725   // If this redeclaration makes the function inline, we may need to add it to
3726   // UndefinedButUsed.
3727   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3728       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3729     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3730                                            SourceLocation()));
3731
3732   if (New->getTLSKind() != Old->getTLSKind()) {
3733     if (!Old->getTLSKind()) {
3734       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3735       Diag(OldLocation, PrevDiag);
3736     } else if (!New->getTLSKind()) {
3737       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3738       Diag(OldLocation, PrevDiag);
3739     } else {
3740       // Do not allow redeclaration to change the variable between requiring
3741       // static and dynamic initialization.
3742       // FIXME: GCC allows this, but uses the TLS keyword on the first
3743       // declaration to determine the kind. Do we need to be compatible here?
3744       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3745         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3746       Diag(OldLocation, PrevDiag);
3747     }
3748   }
3749
3750   // C++ doesn't have tentative definitions, so go right ahead and check here.
3751   if (getLangOpts().CPlusPlus &&
3752       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3753     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3754         Old->getCanonicalDecl()->isConstexpr()) {
3755       // This definition won't be a definition any more once it's been merged.
3756       Diag(New->getLocation(),
3757            diag::warn_deprecated_redundant_constexpr_static_def);
3758     } else if (VarDecl *Def = Old->getDefinition()) {
3759       if (checkVarDeclRedefinition(Def, New))
3760         return;
3761     }
3762   }
3763
3764   if (haveIncompatibleLanguageLinkages(Old, New)) {
3765     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3766     Diag(OldLocation, PrevDiag);
3767     New->setInvalidDecl();
3768     return;
3769   }
3770
3771   // Merge "used" flag.
3772   if (Old->getMostRecentDecl()->isUsed(false))
3773     New->setIsUsed();
3774
3775   // Keep a chain of previous declarations.
3776   New->setPreviousDecl(Old);
3777   if (NewTemplate)
3778     NewTemplate->setPreviousDecl(OldTemplate);
3779
3780   // Inherit access appropriately.
3781   New->setAccess(Old->getAccess());
3782   if (NewTemplate)
3783     NewTemplate->setAccess(New->getAccess());
3784
3785   if (Old->isInline())
3786     New->setImplicitlyInline();
3787 }
3788
3789 /// We've just determined that \p Old and \p New both appear to be definitions
3790 /// of the same variable. Either diagnose or fix the problem.
3791 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3792   if (!hasVisibleDefinition(Old) &&
3793       (New->getFormalLinkage() == InternalLinkage ||
3794        New->isInline() ||
3795        New->getDescribedVarTemplate() ||
3796        New->getNumTemplateParameterLists() ||
3797        New->getDeclContext()->isDependentContext())) {
3798     // The previous definition is hidden, and multiple definitions are
3799     // permitted (in separate TUs). Demote this to a declaration.
3800     New->demoteThisDefinitionToDeclaration();
3801
3802     // Make the canonical definition visible.
3803     if (auto *OldTD = Old->getDescribedVarTemplate())
3804       makeMergedDefinitionVisible(OldTD, New->getLocation());
3805     makeMergedDefinitionVisible(Old, New->getLocation());
3806     return false;
3807   } else {
3808     Diag(New->getLocation(), diag::err_redefinition) << New;
3809     Diag(Old->getLocation(), diag::note_previous_definition);
3810     New->setInvalidDecl();
3811     return true;
3812   }
3813 }
3814
3815 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3816 /// no declarator (e.g. "struct foo;") is parsed.
3817 Decl *
3818 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3819                                  RecordDecl *&AnonRecord) {
3820   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3821                                     AnonRecord);
3822 }
3823
3824 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3825 // disambiguate entities defined in different scopes.
3826 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3827 // compatibility.
3828 // We will pick our mangling number depending on which version of MSVC is being
3829 // targeted.
3830 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3831   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3832              ? S->getMSCurManglingNumber()
3833              : S->getMSLastManglingNumber();
3834 }
3835
3836 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3837   if (!Context.getLangOpts().CPlusPlus)
3838     return;
3839
3840   if (isa<CXXRecordDecl>(Tag->getParent())) {
3841     // If this tag is the direct child of a class, number it if
3842     // it is anonymous.
3843     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3844       return;
3845     MangleNumberingContext &MCtx =
3846         Context.getManglingNumberContext(Tag->getParent());
3847     Context.setManglingNumber(
3848         Tag, MCtx.getManglingNumber(
3849                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3850     return;
3851   }
3852
3853   // If this tag isn't a direct child of a class, number it if it is local.
3854   Decl *ManglingContextDecl;
3855   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3856           Tag->getDeclContext(), ManglingContextDecl)) {
3857     Context.setManglingNumber(
3858         Tag, MCtx->getManglingNumber(
3859                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3860   }
3861 }
3862
3863 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3864                                         TypedefNameDecl *NewTD) {
3865   if (TagFromDeclSpec->isInvalidDecl())
3866     return;
3867
3868   // Do nothing if the tag already has a name for linkage purposes.
3869   if (TagFromDeclSpec->hasNameForLinkage())
3870     return;
3871
3872   // A well-formed anonymous tag must always be a TUK_Definition.
3873   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3874
3875   // The type must match the tag exactly;  no qualifiers allowed.
3876   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3877                            Context.getTagDeclType(TagFromDeclSpec))) {
3878     if (getLangOpts().CPlusPlus)
3879       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3880     return;
3881   }
3882
3883   // If we've already computed linkage for the anonymous tag, then
3884   // adding a typedef name for the anonymous decl can change that
3885   // linkage, which might be a serious problem.  Diagnose this as
3886   // unsupported and ignore the typedef name.  TODO: we should
3887   // pursue this as a language defect and establish a formal rule
3888   // for how to handle it.
3889   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3890     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3891
3892     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3893     tagLoc = getLocForEndOfToken(tagLoc);
3894
3895     llvm::SmallString<40> textToInsert;
3896     textToInsert += ' ';
3897     textToInsert += NewTD->getIdentifier()->getName();
3898     Diag(tagLoc, diag::note_typedef_changes_linkage)
3899         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3900     return;
3901   }
3902
3903   // Otherwise, set this is the anon-decl typedef for the tag.
3904   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3905 }
3906
3907 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3908   switch (T) {
3909   case DeclSpec::TST_class:
3910     return 0;
3911   case DeclSpec::TST_struct:
3912     return 1;
3913   case DeclSpec::TST_interface:
3914     return 2;
3915   case DeclSpec::TST_union:
3916     return 3;
3917   case DeclSpec::TST_enum:
3918     return 4;
3919   default:
3920     llvm_unreachable("unexpected type specifier");
3921   }
3922 }
3923
3924 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3925 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3926 /// parameters to cope with template friend declarations.
3927 Decl *
3928 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3929                                  MultiTemplateParamsArg TemplateParams,
3930                                  bool IsExplicitInstantiation,
3931                                  RecordDecl *&AnonRecord) {
3932   Decl *TagD = nullptr;
3933   TagDecl *Tag = nullptr;
3934   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3935       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3936       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3937       DS.getTypeSpecType() == DeclSpec::TST_union ||
3938       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3939     TagD = DS.getRepAsDecl();
3940
3941     if (!TagD) // We probably had an error
3942       return nullptr;
3943
3944     // Note that the above type specs guarantee that the
3945     // type rep is a Decl, whereas in many of the others
3946     // it's a Type.
3947     if (isa<TagDecl>(TagD))
3948       Tag = cast<TagDecl>(TagD);
3949     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3950       Tag = CTD->getTemplatedDecl();
3951   }
3952
3953   if (Tag) {
3954     handleTagNumbering(Tag, S);
3955     Tag->setFreeStanding();
3956     if (Tag->isInvalidDecl())
3957       return Tag;
3958   }
3959
3960   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3961     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3962     // or incomplete types shall not be restrict-qualified."
3963     if (TypeQuals & DeclSpec::TQ_restrict)
3964       Diag(DS.getRestrictSpecLoc(),
3965            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3966            << DS.getSourceRange();
3967   }
3968
3969   if (DS.isInlineSpecified())
3970     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
3971         << getLangOpts().CPlusPlus1z;
3972
3973   if (DS.isConstexprSpecified()) {
3974     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3975     // and definitions of functions and variables.
3976     if (Tag)
3977       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3978           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3979     else
3980       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3981     // Don't emit warnings after this error.
3982     return TagD;
3983   }
3984
3985   if (DS.isConceptSpecified()) {
3986     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3987     // either a function concept and its definition or a variable concept and
3988     // its initializer.
3989     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3990     return TagD;
3991   }
3992
3993   DiagnoseFunctionSpecifiers(DS);
3994
3995   if (DS.isFriendSpecified()) {
3996     // If we're dealing with a decl but not a TagDecl, assume that
3997     // whatever routines created it handled the friendship aspect.
3998     if (TagD && !Tag)
3999       return nullptr;
4000     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4001   }
4002
4003   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4004   bool IsExplicitSpecialization =
4005     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4006   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4007       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4008       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4009     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4010     // nested-name-specifier unless it is an explicit instantiation
4011     // or an explicit specialization.
4012     //
4013     // FIXME: We allow class template partial specializations here too, per the
4014     // obvious intent of DR1819.
4015     //
4016     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4017     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4018         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4019     return nullptr;
4020   }
4021
4022   // Track whether this decl-specifier declares anything.
4023   bool DeclaresAnything = true;
4024
4025   // Handle anonymous struct definitions.
4026   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4027     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4028         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4029       if (getLangOpts().CPlusPlus ||
4030           Record->getDeclContext()->isRecord()) {
4031         // If CurContext is a DeclContext that can contain statements,
4032         // RecursiveASTVisitor won't visit the decls that
4033         // BuildAnonymousStructOrUnion() will put into CurContext.
4034         // Also store them here so that they can be part of the
4035         // DeclStmt that gets created in this case.
4036         // FIXME: Also return the IndirectFieldDecls created by
4037         // BuildAnonymousStructOr union, for the same reason?
4038         if (CurContext->isFunctionOrMethod())
4039           AnonRecord = Record;
4040         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4041                                            Context.getPrintingPolicy());
4042       }
4043
4044       DeclaresAnything = false;
4045     }
4046   }
4047
4048   // C11 6.7.2.1p2:
4049   //   A struct-declaration that does not declare an anonymous structure or
4050   //   anonymous union shall contain a struct-declarator-list.
4051   //
4052   // This rule also existed in C89 and C99; the grammar for struct-declaration
4053   // did not permit a struct-declaration without a struct-declarator-list.
4054   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4055       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4056     // Check for Microsoft C extension: anonymous struct/union member.
4057     // Handle 2 kinds of anonymous struct/union:
4058     //   struct STRUCT;
4059     //   union UNION;
4060     // and
4061     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4062     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4063     if ((Tag && Tag->getDeclName()) ||
4064         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4065       RecordDecl *Record = nullptr;
4066       if (Tag)
4067         Record = dyn_cast<RecordDecl>(Tag);
4068       else if (const RecordType *RT =
4069                    DS.getRepAsType().get()->getAsStructureType())
4070         Record = RT->getDecl();
4071       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4072         Record = UT->getDecl();
4073
4074       if (Record && getLangOpts().MicrosoftExt) {
4075         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4076           << Record->isUnion() << DS.getSourceRange();
4077         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4078       }
4079
4080       DeclaresAnything = false;
4081     }
4082   }
4083
4084   // Skip all the checks below if we have a type error.
4085   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4086       (TagD && TagD->isInvalidDecl()))
4087     return TagD;
4088
4089   if (getLangOpts().CPlusPlus &&
4090       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4091     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4092       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4093           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4094         DeclaresAnything = false;
4095
4096   if (!DS.isMissingDeclaratorOk()) {
4097     // Customize diagnostic for a typedef missing a name.
4098     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4099       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4100         << DS.getSourceRange();
4101     else
4102       DeclaresAnything = false;
4103   }
4104
4105   if (DS.isModulePrivateSpecified() &&
4106       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4107     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4108       << Tag->getTagKind()
4109       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4110
4111   ActOnDocumentableDecl(TagD);
4112
4113   // C 6.7/2:
4114   //   A declaration [...] shall declare at least a declarator [...], a tag,
4115   //   or the members of an enumeration.
4116   // C++ [dcl.dcl]p3:
4117   //   [If there are no declarators], and except for the declaration of an
4118   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4119   //   names into the program, or shall redeclare a name introduced by a
4120   //   previous declaration.
4121   if (!DeclaresAnything) {
4122     // In C, we allow this as a (popular) extension / bug. Don't bother
4123     // producing further diagnostics for redundant qualifiers after this.
4124     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4125     return TagD;
4126   }
4127
4128   // C++ [dcl.stc]p1:
4129   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4130   //   init-declarator-list of the declaration shall not be empty.
4131   // C++ [dcl.fct.spec]p1:
4132   //   If a cv-qualifier appears in a decl-specifier-seq, the
4133   //   init-declarator-list of the declaration shall not be empty.
4134   //
4135   // Spurious qualifiers here appear to be valid in C.
4136   unsigned DiagID = diag::warn_standalone_specifier;
4137   if (getLangOpts().CPlusPlus)
4138     DiagID = diag::ext_standalone_specifier;
4139
4140   // Note that a linkage-specification sets a storage class, but
4141   // 'extern "C" struct foo;' is actually valid and not theoretically
4142   // useless.
4143   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4144     if (SCS == DeclSpec::SCS_mutable)
4145       // Since mutable is not a viable storage class specifier in C, there is
4146       // no reason to treat it as an extension. Instead, diagnose as an error.
4147       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4148     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4149       Diag(DS.getStorageClassSpecLoc(), DiagID)
4150         << DeclSpec::getSpecifierName(SCS);
4151   }
4152
4153   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4154     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4155       << DeclSpec::getSpecifierName(TSCS);
4156   if (DS.getTypeQualifiers()) {
4157     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4158       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4159     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4160       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4161     // Restrict is covered above.
4162     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4163       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4164     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4165       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4166   }
4167
4168   // Warn about ignored type attributes, for example:
4169   // __attribute__((aligned)) struct A;
4170   // Attributes should be placed after tag to apply to type declaration.
4171   if (!DS.getAttributes().empty()) {
4172     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4173     if (TypeSpecType == DeclSpec::TST_class ||
4174         TypeSpecType == DeclSpec::TST_struct ||
4175         TypeSpecType == DeclSpec::TST_interface ||
4176         TypeSpecType == DeclSpec::TST_union ||
4177         TypeSpecType == DeclSpec::TST_enum) {
4178       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4179            attrs = attrs->getNext())
4180         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4181             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4182     }
4183   }
4184
4185   return TagD;
4186 }
4187
4188 /// We are trying to inject an anonymous member into the given scope;
4189 /// check if there's an existing declaration that can't be overloaded.
4190 ///
4191 /// \return true if this is a forbidden redeclaration
4192 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4193                                          Scope *S,
4194                                          DeclContext *Owner,
4195                                          DeclarationName Name,
4196                                          SourceLocation NameLoc,
4197                                          bool IsUnion) {
4198   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4199                  Sema::ForRedeclaration);
4200   if (!SemaRef.LookupName(R, S)) return false;
4201
4202   // Pick a representative declaration.
4203   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4204   assert(PrevDecl && "Expected a non-null Decl");
4205
4206   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4207     return false;
4208
4209   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4210     << IsUnion << Name;
4211   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4212
4213   return true;
4214 }
4215
4216 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4217 /// anonymous struct or union AnonRecord into the owning context Owner
4218 /// and scope S. This routine will be invoked just after we realize
4219 /// that an unnamed union or struct is actually an anonymous union or
4220 /// struct, e.g.,
4221 ///
4222 /// @code
4223 /// union {
4224 ///   int i;
4225 ///   float f;
4226 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4227 ///    // f into the surrounding scope.x
4228 /// @endcode
4229 ///
4230 /// This routine is recursive, injecting the names of nested anonymous
4231 /// structs/unions into the owning context and scope as well.
4232 static bool
4233 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4234                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4235                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4236   bool Invalid = false;
4237
4238   // Look every FieldDecl and IndirectFieldDecl with a name.
4239   for (auto *D : AnonRecord->decls()) {
4240     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4241         cast<NamedDecl>(D)->getDeclName()) {
4242       ValueDecl *VD = cast<ValueDecl>(D);
4243       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4244                                        VD->getLocation(),
4245                                        AnonRecord->isUnion())) {
4246         // C++ [class.union]p2:
4247         //   The names of the members of an anonymous union shall be
4248         //   distinct from the names of any other entity in the
4249         //   scope in which the anonymous union is declared.
4250         Invalid = true;
4251       } else {
4252         // C++ [class.union]p2:
4253         //   For the purpose of name lookup, after the anonymous union
4254         //   definition, the members of the anonymous union are
4255         //   considered to have been defined in the scope in which the
4256         //   anonymous union is declared.
4257         unsigned OldChainingSize = Chaining.size();
4258         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4259           Chaining.append(IF->chain_begin(), IF->chain_end());
4260         else
4261           Chaining.push_back(VD);
4262
4263         assert(Chaining.size() >= 2);
4264         NamedDecl **NamedChain =
4265           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4266         for (unsigned i = 0; i < Chaining.size(); i++)
4267           NamedChain[i] = Chaining[i];
4268
4269         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4270             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4271             VD->getType(), {NamedChain, Chaining.size()});
4272
4273         for (const auto *Attr : VD->attrs())
4274           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4275
4276         IndirectField->setAccess(AS);
4277         IndirectField->setImplicit();
4278         SemaRef.PushOnScopeChains(IndirectField, S);
4279
4280         // That includes picking up the appropriate access specifier.
4281         if (AS != AS_none) IndirectField->setAccess(AS);
4282
4283         Chaining.resize(OldChainingSize);
4284       }
4285     }
4286   }
4287
4288   return Invalid;
4289 }
4290
4291 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4292 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4293 /// illegal input values are mapped to SC_None.
4294 static StorageClass
4295 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4296   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4297   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4298          "Parser allowed 'typedef' as storage class VarDecl.");
4299   switch (StorageClassSpec) {
4300   case DeclSpec::SCS_unspecified:    return SC_None;
4301   case DeclSpec::SCS_extern:
4302     if (DS.isExternInLinkageSpec())
4303       return SC_None;
4304     return SC_Extern;
4305   case DeclSpec::SCS_static:         return SC_Static;
4306   case DeclSpec::SCS_auto:           return SC_Auto;
4307   case DeclSpec::SCS_register:       return SC_Register;
4308   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4309     // Illegal SCSs map to None: error reporting is up to the caller.
4310   case DeclSpec::SCS_mutable:        // Fall through.
4311   case DeclSpec::SCS_typedef:        return SC_None;
4312   }
4313   llvm_unreachable("unknown storage class specifier");
4314 }
4315
4316 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4317   assert(Record->hasInClassInitializer());
4318
4319   for (const auto *I : Record->decls()) {
4320     const auto *FD = dyn_cast<FieldDecl>(I);
4321     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4322       FD = IFD->getAnonField();
4323     if (FD && FD->hasInClassInitializer())
4324       return FD->getLocation();
4325   }
4326
4327   llvm_unreachable("couldn't find in-class initializer");
4328 }
4329
4330 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4331                                       SourceLocation DefaultInitLoc) {
4332   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4333     return;
4334
4335   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4336   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4337 }
4338
4339 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4340                                       CXXRecordDecl *AnonUnion) {
4341   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4342     return;
4343
4344   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4345 }
4346
4347 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4348 /// anonymous structure or union. Anonymous unions are a C++ feature
4349 /// (C++ [class.union]) and a C11 feature; anonymous structures
4350 /// are a C11 feature and GNU C++ extension.
4351 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4352                                         AccessSpecifier AS,
4353                                         RecordDecl *Record,
4354                                         const PrintingPolicy &Policy) {
4355   DeclContext *Owner = Record->getDeclContext();
4356
4357   // Diagnose whether this anonymous struct/union is an extension.
4358   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4359     Diag(Record->getLocation(), diag::ext_anonymous_union);
4360   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4361     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4362   else if (!Record->isUnion() && !getLangOpts().C11)
4363     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4364
4365   // C and C++ require different kinds of checks for anonymous
4366   // structs/unions.
4367   bool Invalid = false;
4368   if (getLangOpts().CPlusPlus) {
4369     const char *PrevSpec = nullptr;
4370     unsigned DiagID;
4371     if (Record->isUnion()) {
4372       // C++ [class.union]p6:
4373       //   Anonymous unions declared in a named namespace or in the
4374       //   global namespace shall be declared static.
4375       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4376           (isa<TranslationUnitDecl>(Owner) ||
4377            (isa<NamespaceDecl>(Owner) &&
4378             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4379         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4380           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4381
4382         // Recover by adding 'static'.
4383         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4384                                PrevSpec, DiagID, Policy);
4385       }
4386       // C++ [class.union]p6:
4387       //   A storage class is not allowed in a declaration of an
4388       //   anonymous union in a class scope.
4389       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4390                isa<RecordDecl>(Owner)) {
4391         Diag(DS.getStorageClassSpecLoc(),
4392              diag::err_anonymous_union_with_storage_spec)
4393           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4394
4395         // Recover by removing the storage specifier.
4396         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4397                                SourceLocation(),
4398                                PrevSpec, DiagID, Context.getPrintingPolicy());
4399       }
4400     }
4401
4402     // Ignore const/volatile/restrict qualifiers.
4403     if (DS.getTypeQualifiers()) {
4404       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4405         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4406           << Record->isUnion() << "const"
4407           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4408       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4409         Diag(DS.getVolatileSpecLoc(),
4410              diag::ext_anonymous_struct_union_qualified)
4411           << Record->isUnion() << "volatile"
4412           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4413       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4414         Diag(DS.getRestrictSpecLoc(),
4415              diag::ext_anonymous_struct_union_qualified)
4416           << Record->isUnion() << "restrict"
4417           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4418       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4419         Diag(DS.getAtomicSpecLoc(),
4420              diag::ext_anonymous_struct_union_qualified)
4421           << Record->isUnion() << "_Atomic"
4422           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4423       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4424         Diag(DS.getUnalignedSpecLoc(),
4425              diag::ext_anonymous_struct_union_qualified)
4426           << Record->isUnion() << "__unaligned"
4427           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4428
4429       DS.ClearTypeQualifiers();
4430     }
4431
4432     // C++ [class.union]p2:
4433     //   The member-specification of an anonymous union shall only
4434     //   define non-static data members. [Note: nested types and
4435     //   functions cannot be declared within an anonymous union. ]
4436     for (auto *Mem : Record->decls()) {
4437       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4438         // C++ [class.union]p3:
4439         //   An anonymous union shall not have private or protected
4440         //   members (clause 11).
4441         assert(FD->getAccess() != AS_none);
4442         if (FD->getAccess() != AS_public) {
4443           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4444             << Record->isUnion() << (FD->getAccess() == AS_protected);
4445           Invalid = true;
4446         }
4447
4448         // C++ [class.union]p1
4449         //   An object of a class with a non-trivial constructor, a non-trivial
4450         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4451         //   assignment operator cannot be a member of a union, nor can an
4452         //   array of such objects.
4453         if (CheckNontrivialField(FD))
4454           Invalid = true;
4455       } else if (Mem->isImplicit()) {
4456         // Any implicit members are fine.
4457       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4458         // This is a type that showed up in an
4459         // elaborated-type-specifier inside the anonymous struct or
4460         // union, but which actually declares a type outside of the
4461         // anonymous struct or union. It's okay.
4462       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4463         if (!MemRecord->isAnonymousStructOrUnion() &&
4464             MemRecord->getDeclName()) {
4465           // Visual C++ allows type definition in anonymous struct or union.
4466           if (getLangOpts().MicrosoftExt)
4467             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4468               << Record->isUnion();
4469           else {
4470             // This is a nested type declaration.
4471             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4472               << Record->isUnion();
4473             Invalid = true;
4474           }
4475         } else {
4476           // This is an anonymous type definition within another anonymous type.
4477           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4478           // not part of standard C++.
4479           Diag(MemRecord->getLocation(),
4480                diag::ext_anonymous_record_with_anonymous_type)
4481             << Record->isUnion();
4482         }
4483       } else if (isa<AccessSpecDecl>(Mem)) {
4484         // Any access specifier is fine.
4485       } else if (isa<StaticAssertDecl>(Mem)) {
4486         // In C++1z, static_assert declarations are also fine.
4487       } else {
4488         // We have something that isn't a non-static data
4489         // member. Complain about it.
4490         unsigned DK = diag::err_anonymous_record_bad_member;
4491         if (isa<TypeDecl>(Mem))
4492           DK = diag::err_anonymous_record_with_type;
4493         else if (isa<FunctionDecl>(Mem))
4494           DK = diag::err_anonymous_record_with_function;
4495         else if (isa<VarDecl>(Mem))
4496           DK = diag::err_anonymous_record_with_static;
4497
4498         // Visual C++ allows type definition in anonymous struct or union.
4499         if (getLangOpts().MicrosoftExt &&
4500             DK == diag::err_anonymous_record_with_type)
4501           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4502             << Record->isUnion();
4503         else {
4504           Diag(Mem->getLocation(), DK) << Record->isUnion();
4505           Invalid = true;
4506         }
4507       }
4508     }
4509
4510     // C++11 [class.union]p8 (DR1460):
4511     //   At most one variant member of a union may have a
4512     //   brace-or-equal-initializer.
4513     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4514         Owner->isRecord())
4515       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4516                                 cast<CXXRecordDecl>(Record));
4517   }
4518
4519   if (!Record->isUnion() && !Owner->isRecord()) {
4520     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4521       << getLangOpts().CPlusPlus;
4522     Invalid = true;
4523   }
4524
4525   // Mock up a declarator.
4526   Declarator Dc(DS, Declarator::MemberContext);
4527   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4528   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4529
4530   // Create a declaration for this anonymous struct/union.
4531   NamedDecl *Anon = nullptr;
4532   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4533     Anon = FieldDecl::Create(Context, OwningClass,
4534                              DS.getLocStart(),
4535                              Record->getLocation(),
4536                              /*IdentifierInfo=*/nullptr,
4537                              Context.getTypeDeclType(Record),
4538                              TInfo,
4539                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4540                              /*InitStyle=*/ICIS_NoInit);
4541     Anon->setAccess(AS);
4542     if (getLangOpts().CPlusPlus)
4543       FieldCollector->Add(cast<FieldDecl>(Anon));
4544   } else {
4545     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4546     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4547     if (SCSpec == DeclSpec::SCS_mutable) {
4548       // mutable can only appear on non-static class members, so it's always
4549       // an error here
4550       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4551       Invalid = true;
4552       SC = SC_None;
4553     }
4554
4555     Anon = VarDecl::Create(Context, Owner,
4556                            DS.getLocStart(),
4557                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4558                            Context.getTypeDeclType(Record),
4559                            TInfo, SC);
4560
4561     // Default-initialize the implicit variable. This initialization will be
4562     // trivial in almost all cases, except if a union member has an in-class
4563     // initializer:
4564     //   union { int n = 0; };
4565     ActOnUninitializedDecl(Anon);
4566   }
4567   Anon->setImplicit();
4568
4569   // Mark this as an anonymous struct/union type.
4570   Record->setAnonymousStructOrUnion(true);
4571
4572   // Add the anonymous struct/union object to the current
4573   // context. We'll be referencing this object when we refer to one of
4574   // its members.
4575   Owner->addDecl(Anon);
4576
4577   // Inject the members of the anonymous struct/union into the owning
4578   // context and into the identifier resolver chain for name lookup
4579   // purposes.
4580   SmallVector<NamedDecl*, 2> Chain;
4581   Chain.push_back(Anon);
4582
4583   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4584     Invalid = true;
4585
4586   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4587     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4588       Decl *ManglingContextDecl;
4589       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4590               NewVD->getDeclContext(), ManglingContextDecl)) {
4591         Context.setManglingNumber(
4592             NewVD, MCtx->getManglingNumber(
4593                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4594         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4595       }
4596     }
4597   }
4598
4599   if (Invalid)
4600     Anon->setInvalidDecl();
4601
4602   return Anon;
4603 }
4604
4605 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4606 /// Microsoft C anonymous structure.
4607 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4608 /// Example:
4609 ///
4610 /// struct A { int a; };
4611 /// struct B { struct A; int b; };
4612 ///
4613 /// void foo() {
4614 ///   B var;
4615 ///   var.a = 3;
4616 /// }
4617 ///
4618 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4619                                            RecordDecl *Record) {
4620   assert(Record && "expected a record!");
4621
4622   // Mock up a declarator.
4623   Declarator Dc(DS, Declarator::TypeNameContext);
4624   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4625   assert(TInfo && "couldn't build declarator info for anonymous struct");
4626
4627   auto *ParentDecl = cast<RecordDecl>(CurContext);
4628   QualType RecTy = Context.getTypeDeclType(Record);
4629
4630   // Create a declaration for this anonymous struct.
4631   NamedDecl *Anon = FieldDecl::Create(Context,
4632                              ParentDecl,
4633                              DS.getLocStart(),
4634                              DS.getLocStart(),
4635                              /*IdentifierInfo=*/nullptr,
4636                              RecTy,
4637                              TInfo,
4638                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4639                              /*InitStyle=*/ICIS_NoInit);
4640   Anon->setImplicit();
4641
4642   // Add the anonymous struct object to the current context.
4643   CurContext->addDecl(Anon);
4644
4645   // Inject the members of the anonymous struct into the current
4646   // context and into the identifier resolver chain for name lookup
4647   // purposes.
4648   SmallVector<NamedDecl*, 2> Chain;
4649   Chain.push_back(Anon);
4650
4651   RecordDecl *RecordDef = Record->getDefinition();
4652   if (RequireCompleteType(Anon->getLocation(), RecTy,
4653                           diag::err_field_incomplete) ||
4654       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4655                                           AS_none, Chain)) {
4656     Anon->setInvalidDecl();
4657     ParentDecl->setInvalidDecl();
4658   }
4659
4660   return Anon;
4661 }
4662
4663 /// GetNameForDeclarator - Determine the full declaration name for the
4664 /// given Declarator.
4665 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4666   return GetNameFromUnqualifiedId(D.getName());
4667 }
4668
4669 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4670 DeclarationNameInfo
4671 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4672   DeclarationNameInfo NameInfo;
4673   NameInfo.setLoc(Name.StartLocation);
4674
4675   switch (Name.getKind()) {
4676
4677   case UnqualifiedId::IK_ImplicitSelfParam:
4678   case UnqualifiedId::IK_Identifier:
4679     NameInfo.setName(Name.Identifier);
4680     NameInfo.setLoc(Name.StartLocation);
4681     return NameInfo;
4682
4683   case UnqualifiedId::IK_DeductionGuideName: {
4684     // C++ [temp.deduct.guide]p3:
4685     //   The simple-template-id shall name a class template specialization.
4686     //   The template-name shall be the same identifier as the template-name
4687     //   of the simple-template-id.
4688     // These together intend to imply that the template-name shall name a
4689     // class template.
4690     // FIXME: template<typename T> struct X {};
4691     //        template<typename T> using Y = X<T>;
4692     //        Y(int) -> Y<int>;
4693     //   satisfies these rules but does not name a class template.
4694     TemplateName TN = Name.TemplateName.get().get();
4695     auto *Template = TN.getAsTemplateDecl();
4696     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4697       Diag(Name.StartLocation,
4698            diag::err_deduction_guide_name_not_class_template)
4699         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4700       if (Template)
4701         Diag(Template->getLocation(), diag::note_template_decl_here);
4702       return DeclarationNameInfo();
4703     }
4704
4705     NameInfo.setName(
4706         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4707     NameInfo.setLoc(Name.StartLocation);
4708     return NameInfo;
4709   }
4710
4711   case UnqualifiedId::IK_OperatorFunctionId:
4712     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4713                                            Name.OperatorFunctionId.Operator));
4714     NameInfo.setLoc(Name.StartLocation);
4715     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4716       = Name.OperatorFunctionId.SymbolLocations[0];
4717     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4718       = Name.EndLocation.getRawEncoding();
4719     return NameInfo;
4720
4721   case UnqualifiedId::IK_LiteralOperatorId:
4722     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4723                                                            Name.Identifier));
4724     NameInfo.setLoc(Name.StartLocation);
4725     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4726     return NameInfo;
4727
4728   case UnqualifiedId::IK_ConversionFunctionId: {
4729     TypeSourceInfo *TInfo;
4730     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4731     if (Ty.isNull())
4732       return DeclarationNameInfo();
4733     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4734                                                Context.getCanonicalType(Ty)));
4735     NameInfo.setLoc(Name.StartLocation);
4736     NameInfo.setNamedTypeInfo(TInfo);
4737     return NameInfo;
4738   }
4739
4740   case UnqualifiedId::IK_ConstructorName: {
4741     TypeSourceInfo *TInfo;
4742     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4743     if (Ty.isNull())
4744       return DeclarationNameInfo();
4745     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4746                                               Context.getCanonicalType(Ty)));
4747     NameInfo.setLoc(Name.StartLocation);
4748     NameInfo.setNamedTypeInfo(TInfo);
4749     return NameInfo;
4750   }
4751
4752   case UnqualifiedId::IK_ConstructorTemplateId: {
4753     // In well-formed code, we can only have a constructor
4754     // template-id that refers to the current context, so go there
4755     // to find the actual type being constructed.
4756     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4757     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4758       return DeclarationNameInfo();
4759
4760     // Determine the type of the class being constructed.
4761     QualType CurClassType = Context.getTypeDeclType(CurClass);
4762
4763     // FIXME: Check two things: that the template-id names the same type as
4764     // CurClassType, and that the template-id does not occur when the name
4765     // was qualified.
4766
4767     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4768                                     Context.getCanonicalType(CurClassType)));
4769     NameInfo.setLoc(Name.StartLocation);
4770     // FIXME: should we retrieve TypeSourceInfo?
4771     NameInfo.setNamedTypeInfo(nullptr);
4772     return NameInfo;
4773   }
4774
4775   case UnqualifiedId::IK_DestructorName: {
4776     TypeSourceInfo *TInfo;
4777     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4778     if (Ty.isNull())
4779       return DeclarationNameInfo();
4780     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4781                                               Context.getCanonicalType(Ty)));
4782     NameInfo.setLoc(Name.StartLocation);
4783     NameInfo.setNamedTypeInfo(TInfo);
4784     return NameInfo;
4785   }
4786
4787   case UnqualifiedId::IK_TemplateId: {
4788     TemplateName TName = Name.TemplateId->Template.get();
4789     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4790     return Context.getNameForTemplate(TName, TNameLoc);
4791   }
4792
4793   } // switch (Name.getKind())
4794
4795   llvm_unreachable("Unknown name kind");
4796 }
4797
4798 static QualType getCoreType(QualType Ty) {
4799   do {
4800     if (Ty->isPointerType() || Ty->isReferenceType())
4801       Ty = Ty->getPointeeType();
4802     else if (Ty->isArrayType())
4803       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4804     else
4805       return Ty.withoutLocalFastQualifiers();
4806   } while (true);
4807 }
4808
4809 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4810 /// and Definition have "nearly" matching parameters. This heuristic is
4811 /// used to improve diagnostics in the case where an out-of-line function
4812 /// definition doesn't match any declaration within the class or namespace.
4813 /// Also sets Params to the list of indices to the parameters that differ
4814 /// between the declaration and the definition. If hasSimilarParameters
4815 /// returns true and Params is empty, then all of the parameters match.
4816 static bool hasSimilarParameters(ASTContext &Context,
4817                                      FunctionDecl *Declaration,
4818                                      FunctionDecl *Definition,
4819                                      SmallVectorImpl<unsigned> &Params) {
4820   Params.clear();
4821   if (Declaration->param_size() != Definition->param_size())
4822     return false;
4823   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4824     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4825     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4826
4827     // The parameter types are identical
4828     if (Context.hasSameType(DefParamTy, DeclParamTy))
4829       continue;
4830
4831     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4832     QualType DefParamBaseTy = getCoreType(DefParamTy);
4833     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4834     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4835
4836     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4837         (DeclTyName && DeclTyName == DefTyName))
4838       Params.push_back(Idx);
4839     else  // The two parameters aren't even close
4840       return false;
4841   }
4842
4843   return true;
4844 }
4845
4846 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4847 /// declarator needs to be rebuilt in the current instantiation.
4848 /// Any bits of declarator which appear before the name are valid for
4849 /// consideration here.  That's specifically the type in the decl spec
4850 /// and the base type in any member-pointer chunks.
4851 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4852                                                     DeclarationName Name) {
4853   // The types we specifically need to rebuild are:
4854   //   - typenames, typeofs, and decltypes
4855   //   - types which will become injected class names
4856   // Of course, we also need to rebuild any type referencing such a
4857   // type.  It's safest to just say "dependent", but we call out a
4858   // few cases here.
4859
4860   DeclSpec &DS = D.getMutableDeclSpec();
4861   switch (DS.getTypeSpecType()) {
4862   case DeclSpec::TST_typename:
4863   case DeclSpec::TST_typeofType:
4864   case DeclSpec::TST_underlyingType:
4865   case DeclSpec::TST_atomic: {
4866     // Grab the type from the parser.
4867     TypeSourceInfo *TSI = nullptr;
4868     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4869     if (T.isNull() || !T->isDependentType()) break;
4870
4871     // Make sure there's a type source info.  This isn't really much
4872     // of a waste; most dependent types should have type source info
4873     // attached already.
4874     if (!TSI)
4875       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4876
4877     // Rebuild the type in the current instantiation.
4878     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4879     if (!TSI) return true;
4880
4881     // Store the new type back in the decl spec.
4882     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4883     DS.UpdateTypeRep(LocType);
4884     break;
4885   }
4886
4887   case DeclSpec::TST_decltype:
4888   case DeclSpec::TST_typeofExpr: {
4889     Expr *E = DS.getRepAsExpr();
4890     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4891     if (Result.isInvalid()) return true;
4892     DS.UpdateExprRep(Result.get());
4893     break;
4894   }
4895
4896   default:
4897     // Nothing to do for these decl specs.
4898     break;
4899   }
4900
4901   // It doesn't matter what order we do this in.
4902   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4903     DeclaratorChunk &Chunk = D.getTypeObject(I);
4904
4905     // The only type information in the declarator which can come
4906     // before the declaration name is the base type of a member
4907     // pointer.
4908     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4909       continue;
4910
4911     // Rebuild the scope specifier in-place.
4912     CXXScopeSpec &SS = Chunk.Mem.Scope();
4913     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4914       return true;
4915   }
4916
4917   return false;
4918 }
4919
4920 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4921   D.setFunctionDefinitionKind(FDK_Declaration);
4922   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4923
4924   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4925       Dcl && Dcl->getDeclContext()->isFileContext())
4926     Dcl->setTopLevelDeclInObjCContainer();
4927
4928   if (getLangOpts().OpenCL)
4929     setCurrentOpenCLExtensionForDecl(Dcl);
4930
4931   return Dcl;
4932 }
4933
4934 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4935 ///   If T is the name of a class, then each of the following shall have a
4936 ///   name different from T:
4937 ///     - every static data member of class T;
4938 ///     - every member function of class T
4939 ///     - every member of class T that is itself a type;
4940 /// \returns true if the declaration name violates these rules.
4941 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4942                                    DeclarationNameInfo NameInfo) {
4943   DeclarationName Name = NameInfo.getName();
4944
4945   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4946   while (Record && Record->isAnonymousStructOrUnion())
4947     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4948   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4949     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4950     return true;
4951   }
4952
4953   return false;
4954 }
4955
4956 /// \brief Diagnose a declaration whose declarator-id has the given
4957 /// nested-name-specifier.
4958 ///
4959 /// \param SS The nested-name-specifier of the declarator-id.
4960 ///
4961 /// \param DC The declaration context to which the nested-name-specifier
4962 /// resolves.
4963 ///
4964 /// \param Name The name of the entity being declared.
4965 ///
4966 /// \param Loc The location of the name of the entity being declared.
4967 ///
4968 /// \returns true if we cannot safely recover from this error, false otherwise.
4969 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4970                                         DeclarationName Name,
4971                                         SourceLocation Loc) {
4972   DeclContext *Cur = CurContext;
4973   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4974     Cur = Cur->getParent();
4975
4976   // If the user provided a superfluous scope specifier that refers back to the
4977   // class in which the entity is already declared, diagnose and ignore it.
4978   //
4979   // class X {
4980   //   void X::f();
4981   // };
4982   //
4983   // Note, it was once ill-formed to give redundant qualification in all
4984   // contexts, but that rule was removed by DR482.
4985   if (Cur->Equals(DC)) {
4986     if (Cur->isRecord()) {
4987       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4988                                       : diag::err_member_extra_qualification)
4989         << Name << FixItHint::CreateRemoval(SS.getRange());
4990       SS.clear();
4991     } else {
4992       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4993     }
4994     return false;
4995   }
4996
4997   // Check whether the qualifying scope encloses the scope of the original
4998   // declaration.
4999   if (!Cur->Encloses(DC)) {
5000     if (Cur->isRecord())
5001       Diag(Loc, diag::err_member_qualification)
5002         << Name << SS.getRange();
5003     else if (isa<TranslationUnitDecl>(DC))
5004       Diag(Loc, diag::err_invalid_declarator_global_scope)
5005         << Name << SS.getRange();
5006     else if (isa<FunctionDecl>(Cur))
5007       Diag(Loc, diag::err_invalid_declarator_in_function)
5008         << Name << SS.getRange();
5009     else if (isa<BlockDecl>(Cur))
5010       Diag(Loc, diag::err_invalid_declarator_in_block)
5011         << Name << SS.getRange();
5012     else
5013       Diag(Loc, diag::err_invalid_declarator_scope)
5014       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5015
5016     return true;
5017   }
5018
5019   if (Cur->isRecord()) {
5020     // Cannot qualify members within a class.
5021     Diag(Loc, diag::err_member_qualification)
5022       << Name << SS.getRange();
5023     SS.clear();
5024
5025     // C++ constructors and destructors with incorrect scopes can break
5026     // our AST invariants by having the wrong underlying types. If
5027     // that's the case, then drop this declaration entirely.
5028     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5029          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5030         !Context.hasSameType(Name.getCXXNameType(),
5031                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5032       return true;
5033
5034     return false;
5035   }
5036
5037   // C++11 [dcl.meaning]p1:
5038   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5039   //   not begin with a decltype-specifer"
5040   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5041   while (SpecLoc.getPrefix())
5042     SpecLoc = SpecLoc.getPrefix();
5043   if (dyn_cast_or_null<DecltypeType>(
5044         SpecLoc.getNestedNameSpecifier()->getAsType()))
5045     Diag(Loc, diag::err_decltype_in_declarator)
5046       << SpecLoc.getTypeLoc().getSourceRange();
5047
5048   return false;
5049 }
5050
5051 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5052                                   MultiTemplateParamsArg TemplateParamLists) {
5053   // TODO: consider using NameInfo for diagnostic.
5054   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5055   DeclarationName Name = NameInfo.getName();
5056
5057   // All of these full declarators require an identifier.  If it doesn't have
5058   // one, the ParsedFreeStandingDeclSpec action should be used.
5059   if (D.isDecompositionDeclarator()) {
5060     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5061   } else if (!Name) {
5062     if (!D.isInvalidType())  // Reject this if we think it is valid.
5063       Diag(D.getDeclSpec().getLocStart(),
5064            diag::err_declarator_need_ident)
5065         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5066     return nullptr;
5067   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5068     return nullptr;
5069
5070   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5071   // we find one that is.
5072   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5073          (S->getFlags() & Scope::TemplateParamScope) != 0)
5074     S = S->getParent();
5075
5076   DeclContext *DC = CurContext;
5077   if (D.getCXXScopeSpec().isInvalid())
5078     D.setInvalidType();
5079   else if (D.getCXXScopeSpec().isSet()) {
5080     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5081                                         UPPC_DeclarationQualifier))
5082       return nullptr;
5083
5084     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5085     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5086     if (!DC || isa<EnumDecl>(DC)) {
5087       // If we could not compute the declaration context, it's because the
5088       // declaration context is dependent but does not refer to a class,
5089       // class template, or class template partial specialization. Complain
5090       // and return early, to avoid the coming semantic disaster.
5091       Diag(D.getIdentifierLoc(),
5092            diag::err_template_qualified_declarator_no_match)
5093         << D.getCXXScopeSpec().getScopeRep()
5094         << D.getCXXScopeSpec().getRange();
5095       return nullptr;
5096     }
5097     bool IsDependentContext = DC->isDependentContext();
5098
5099     if (!IsDependentContext &&
5100         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5101       return nullptr;
5102
5103     // If a class is incomplete, do not parse entities inside it.
5104     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5105       Diag(D.getIdentifierLoc(),
5106            diag::err_member_def_undefined_record)
5107         << Name << DC << D.getCXXScopeSpec().getRange();
5108       return nullptr;
5109     }
5110     if (!D.getDeclSpec().isFriendSpecified()) {
5111       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5112                                       Name, D.getIdentifierLoc())) {
5113         if (DC->isRecord())
5114           return nullptr;
5115
5116         D.setInvalidType();
5117       }
5118     }
5119
5120     // Check whether we need to rebuild the type of the given
5121     // declaration in the current instantiation.
5122     if (EnteringContext && IsDependentContext &&
5123         TemplateParamLists.size() != 0) {
5124       ContextRAII SavedContext(*this, DC);
5125       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5126         D.setInvalidType();
5127     }
5128   }
5129
5130   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5131   QualType R = TInfo->getType();
5132
5133   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5134     // If this is a typedef, we'll end up spewing multiple diagnostics.
5135     // Just return early; it's safer. If this is a function, let the
5136     // "constructor cannot have a return type" diagnostic handle it.
5137     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5138       return nullptr;
5139
5140   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5141                                       UPPC_DeclarationType))
5142     D.setInvalidType();
5143
5144   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5145                         ForRedeclaration);
5146
5147   // See if this is a redefinition of a variable in the same scope.
5148   if (!D.getCXXScopeSpec().isSet()) {
5149     bool IsLinkageLookup = false;
5150     bool CreateBuiltins = false;
5151
5152     // If the declaration we're planning to build will be a function
5153     // or object with linkage, then look for another declaration with
5154     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5155     //
5156     // If the declaration we're planning to build will be declared with
5157     // external linkage in the translation unit, create any builtin with
5158     // the same name.
5159     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5160       /* Do nothing*/;
5161     else if (CurContext->isFunctionOrMethod() &&
5162              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5163               R->isFunctionType())) {
5164       IsLinkageLookup = true;
5165       CreateBuiltins =
5166           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5167     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5168                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5169       CreateBuiltins = true;
5170
5171     if (IsLinkageLookup)
5172       Previous.clear(LookupRedeclarationWithLinkage);
5173
5174     LookupName(Previous, S, CreateBuiltins);
5175   } else { // Something like "int foo::x;"
5176     LookupQualifiedName(Previous, DC);
5177
5178     // C++ [dcl.meaning]p1:
5179     //   When the declarator-id is qualified, the declaration shall refer to a
5180     //  previously declared member of the class or namespace to which the
5181     //  qualifier refers (or, in the case of a namespace, of an element of the
5182     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5183     //  thereof; [...]
5184     //
5185     // Note that we already checked the context above, and that we do not have
5186     // enough information to make sure that Previous contains the declaration
5187     // we want to match. For example, given:
5188     //
5189     //   class X {
5190     //     void f();
5191     //     void f(float);
5192     //   };
5193     //
5194     //   void X::f(int) { } // ill-formed
5195     //
5196     // In this case, Previous will point to the overload set
5197     // containing the two f's declared in X, but neither of them
5198     // matches.
5199
5200     // C++ [dcl.meaning]p1:
5201     //   [...] the member shall not merely have been introduced by a
5202     //   using-declaration in the scope of the class or namespace nominated by
5203     //   the nested-name-specifier of the declarator-id.
5204     RemoveUsingDecls(Previous);
5205   }
5206
5207   if (Previous.isSingleResult() &&
5208       Previous.getFoundDecl()->isTemplateParameter()) {
5209     // Maybe we will complain about the shadowed template parameter.
5210     if (!D.isInvalidType())
5211       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5212                                       Previous.getFoundDecl());
5213
5214     // Just pretend that we didn't see the previous declaration.
5215     Previous.clear();
5216   }
5217
5218   // In C++, the previous declaration we find might be a tag type
5219   // (class or enum). In this case, the new declaration will hide the
5220   // tag type. Note that this does does not apply if we're declaring a
5221   // typedef (C++ [dcl.typedef]p4).
5222   if (Previous.isSingleTagDecl() &&
5223       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5224     Previous.clear();
5225
5226   // Check that there are no default arguments other than in the parameters
5227   // of a function declaration (C++ only).
5228   if (getLangOpts().CPlusPlus)
5229     CheckExtraCXXDefaultArguments(D);
5230
5231   if (D.getDeclSpec().isConceptSpecified()) {
5232     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5233     // applied only to the definition of a function template or variable
5234     // template, declared in namespace scope
5235     if (!TemplateParamLists.size()) {
5236       Diag(D.getDeclSpec().getConceptSpecLoc(),
5237            diag:: err_concept_wrong_decl_kind);
5238       return nullptr;
5239     }
5240
5241     if (!DC->getRedeclContext()->isFileContext()) {
5242       Diag(D.getIdentifierLoc(),
5243            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5244       return nullptr;
5245     }
5246   }
5247
5248   NamedDecl *New;
5249
5250   bool AddToScope = true;
5251   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5252     if (TemplateParamLists.size()) {
5253       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5254       return nullptr;
5255     }
5256
5257     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5258   } else if (R->isFunctionType()) {
5259     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5260                                   TemplateParamLists,
5261                                   AddToScope);
5262   } else {
5263     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5264                                   AddToScope);
5265   }
5266
5267   if (!New)
5268     return nullptr;
5269
5270   // If this has an identifier and is not a function template specialization,
5271   // add it to the scope stack.
5272   if (New->getDeclName() && AddToScope) {
5273     // Only make a locally-scoped extern declaration visible if it is the first
5274     // declaration of this entity. Qualified lookup for such an entity should
5275     // only find this declaration if there is no visible declaration of it.
5276     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5277     PushOnScopeChains(New, S, AddToContext);
5278     if (!AddToContext)
5279       CurContext->addHiddenDecl(New);
5280   }
5281
5282   if (isInOpenMPDeclareTargetContext())
5283     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5284
5285   return New;
5286 }
5287
5288 /// Helper method to turn variable array types into constant array
5289 /// types in certain situations which would otherwise be errors (for
5290 /// GCC compatibility).
5291 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5292                                                     ASTContext &Context,
5293                                                     bool &SizeIsNegative,
5294                                                     llvm::APSInt &Oversized) {
5295   // This method tries to turn a variable array into a constant
5296   // array even when the size isn't an ICE.  This is necessary
5297   // for compatibility with code that depends on gcc's buggy
5298   // constant expression folding, like struct {char x[(int)(char*)2];}
5299   SizeIsNegative = false;
5300   Oversized = 0;
5301
5302   if (T->isDependentType())
5303     return QualType();
5304
5305   QualifierCollector Qs;
5306   const Type *Ty = Qs.strip(T);
5307
5308   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5309     QualType Pointee = PTy->getPointeeType();
5310     QualType FixedType =
5311         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5312                                             Oversized);
5313     if (FixedType.isNull()) return FixedType;
5314     FixedType = Context.getPointerType(FixedType);
5315     return Qs.apply(Context, FixedType);
5316   }
5317   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5318     QualType Inner = PTy->getInnerType();
5319     QualType FixedType =
5320         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5321                                             Oversized);
5322     if (FixedType.isNull()) return FixedType;
5323     FixedType = Context.getParenType(FixedType);
5324     return Qs.apply(Context, FixedType);
5325   }
5326
5327   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5328   if (!VLATy)
5329     return QualType();
5330   // FIXME: We should probably handle this case
5331   if (VLATy->getElementType()->isVariablyModifiedType())
5332     return QualType();
5333
5334   llvm::APSInt Res;
5335   if (!VLATy->getSizeExpr() ||
5336       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5337     return QualType();
5338
5339   // Check whether the array size is negative.
5340   if (Res.isSigned() && Res.isNegative()) {
5341     SizeIsNegative = true;
5342     return QualType();
5343   }
5344
5345   // Check whether the array is too large to be addressed.
5346   unsigned ActiveSizeBits
5347     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5348                                               Res);
5349   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5350     Oversized = Res;
5351     return QualType();
5352   }
5353
5354   return Context.getConstantArrayType(VLATy->getElementType(),
5355                                       Res, ArrayType::Normal, 0);
5356 }
5357
5358 static void
5359 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5360   SrcTL = SrcTL.getUnqualifiedLoc();
5361   DstTL = DstTL.getUnqualifiedLoc();
5362   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5363     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5364     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5365                                       DstPTL.getPointeeLoc());
5366     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5367     return;
5368   }
5369   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5370     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5371     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5372                                       DstPTL.getInnerLoc());
5373     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5374     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5375     return;
5376   }
5377   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5378   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5379   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5380   TypeLoc DstElemTL = DstATL.getElementLoc();
5381   DstElemTL.initializeFullCopy(SrcElemTL);
5382   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5383   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5384   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5385 }
5386
5387 /// Helper method to turn variable array types into constant array
5388 /// types in certain situations which would otherwise be errors (for
5389 /// GCC compatibility).
5390 static TypeSourceInfo*
5391 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5392                                               ASTContext &Context,
5393                                               bool &SizeIsNegative,
5394                                               llvm::APSInt &Oversized) {
5395   QualType FixedTy
5396     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5397                                           SizeIsNegative, Oversized);
5398   if (FixedTy.isNull())
5399     return nullptr;
5400   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5401   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5402                                     FixedTInfo->getTypeLoc());
5403   return FixedTInfo;
5404 }
5405
5406 /// \brief Register the given locally-scoped extern "C" declaration so
5407 /// that it can be found later for redeclarations. We include any extern "C"
5408 /// declaration that is not visible in the translation unit here, not just
5409 /// function-scope declarations.
5410 void
5411 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5412   if (!getLangOpts().CPlusPlus &&
5413       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5414     // Don't need to track declarations in the TU in C.
5415     return;
5416
5417   // Note that we have a locally-scoped external with this name.
5418   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5419 }
5420
5421 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5422   // FIXME: We can have multiple results via __attribute__((overloadable)).
5423   auto Result = Context.getExternCContextDecl()->lookup(Name);
5424   return Result.empty() ? nullptr : *Result.begin();
5425 }
5426
5427 /// \brief Diagnose function specifiers on a declaration of an identifier that
5428 /// does not identify a function.
5429 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5430   // FIXME: We should probably indicate the identifier in question to avoid
5431   // confusion for constructs like "virtual int a(), b;"
5432   if (DS.isVirtualSpecified())
5433     Diag(DS.getVirtualSpecLoc(),
5434          diag::err_virtual_non_function);
5435
5436   if (DS.isExplicitSpecified())
5437     Diag(DS.getExplicitSpecLoc(),
5438          diag::err_explicit_non_function);
5439
5440   if (DS.isNoreturnSpecified())
5441     Diag(DS.getNoreturnSpecLoc(),
5442          diag::err_noreturn_non_function);
5443 }
5444
5445 NamedDecl*
5446 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5447                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5448   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5449   if (D.getCXXScopeSpec().isSet()) {
5450     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5451       << D.getCXXScopeSpec().getRange();
5452     D.setInvalidType();
5453     // Pretend we didn't see the scope specifier.
5454     DC = CurContext;
5455     Previous.clear();
5456   }
5457
5458   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5459
5460   if (D.getDeclSpec().isInlineSpecified())
5461     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5462         << getLangOpts().CPlusPlus1z;
5463   if (D.getDeclSpec().isConstexprSpecified())
5464     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5465       << 1;
5466   if (D.getDeclSpec().isConceptSpecified())
5467     Diag(D.getDeclSpec().getConceptSpecLoc(),
5468          diag::err_concept_wrong_decl_kind);
5469
5470   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5471     if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
5472       Diag(D.getName().StartLocation,
5473            diag::err_deduction_guide_invalid_specifier)
5474           << "typedef";
5475     else
5476       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5477           << D.getName().getSourceRange();
5478     return nullptr;
5479   }
5480
5481   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5482   if (!NewTD) return nullptr;
5483
5484   // Handle attributes prior to checking for duplicates in MergeVarDecl
5485   ProcessDeclAttributes(S, NewTD, D);
5486
5487   CheckTypedefForVariablyModifiedType(S, NewTD);
5488
5489   bool Redeclaration = D.isRedeclaration();
5490   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5491   D.setRedeclaration(Redeclaration);
5492   return ND;
5493 }
5494
5495 void
5496 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5497   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5498   // then it shall have block scope.
5499   // Note that variably modified types must be fixed before merging the decl so
5500   // that redeclarations will match.
5501   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5502   QualType T = TInfo->getType();
5503   if (T->isVariablyModifiedType()) {
5504     getCurFunction()->setHasBranchProtectedScope();
5505
5506     if (S->getFnParent() == nullptr) {
5507       bool SizeIsNegative;
5508       llvm::APSInt Oversized;
5509       TypeSourceInfo *FixedTInfo =
5510         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5511                                                       SizeIsNegative,
5512                                                       Oversized);
5513       if (FixedTInfo) {
5514         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5515         NewTD->setTypeSourceInfo(FixedTInfo);
5516       } else {
5517         if (SizeIsNegative)
5518           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5519         else if (T->isVariableArrayType())
5520           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5521         else if (Oversized.getBoolValue())
5522           Diag(NewTD->getLocation(), diag::err_array_too_large)
5523             << Oversized.toString(10);
5524         else
5525           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5526         NewTD->setInvalidDecl();
5527       }
5528     }
5529   }
5530 }
5531
5532 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5533 /// declares a typedef-name, either using the 'typedef' type specifier or via
5534 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5535 NamedDecl*
5536 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5537                            LookupResult &Previous, bool &Redeclaration) {
5538
5539   // Find the shadowed declaration before filtering for scope.
5540   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5541
5542   // Merge the decl with the existing one if appropriate. If the decl is
5543   // in an outer scope, it isn't the same thing.
5544   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5545                        /*AllowInlineNamespace*/false);
5546   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5547   if (!Previous.empty()) {
5548     Redeclaration = true;
5549     MergeTypedefNameDecl(S, NewTD, Previous);
5550   }
5551
5552   if (ShadowedDecl && !Redeclaration)
5553     CheckShadow(NewTD, ShadowedDecl, Previous);
5554
5555   // If this is the C FILE type, notify the AST context.
5556   if (IdentifierInfo *II = NewTD->getIdentifier())
5557     if (!NewTD->isInvalidDecl() &&
5558         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5559       if (II->isStr("FILE"))
5560         Context.setFILEDecl(NewTD);
5561       else if (II->isStr("jmp_buf"))
5562         Context.setjmp_bufDecl(NewTD);
5563       else if (II->isStr("sigjmp_buf"))
5564         Context.setsigjmp_bufDecl(NewTD);
5565       else if (II->isStr("ucontext_t"))
5566         Context.setucontext_tDecl(NewTD);
5567     }
5568
5569   return NewTD;
5570 }
5571
5572 /// \brief Determines whether the given declaration is an out-of-scope
5573 /// previous declaration.
5574 ///
5575 /// This routine should be invoked when name lookup has found a
5576 /// previous declaration (PrevDecl) that is not in the scope where a
5577 /// new declaration by the same name is being introduced. If the new
5578 /// declaration occurs in a local scope, previous declarations with
5579 /// linkage may still be considered previous declarations (C99
5580 /// 6.2.2p4-5, C++ [basic.link]p6).
5581 ///
5582 /// \param PrevDecl the previous declaration found by name
5583 /// lookup
5584 ///
5585 /// \param DC the context in which the new declaration is being
5586 /// declared.
5587 ///
5588 /// \returns true if PrevDecl is an out-of-scope previous declaration
5589 /// for a new delcaration with the same name.
5590 static bool
5591 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5592                                 ASTContext &Context) {
5593   if (!PrevDecl)
5594     return false;
5595
5596   if (!PrevDecl->hasLinkage())
5597     return false;
5598
5599   if (Context.getLangOpts().CPlusPlus) {
5600     // C++ [basic.link]p6:
5601     //   If there is a visible declaration of an entity with linkage
5602     //   having the same name and type, ignoring entities declared
5603     //   outside the innermost enclosing namespace scope, the block
5604     //   scope declaration declares that same entity and receives the
5605     //   linkage of the previous declaration.
5606     DeclContext *OuterContext = DC->getRedeclContext();
5607     if (!OuterContext->isFunctionOrMethod())
5608       // This rule only applies to block-scope declarations.
5609       return false;
5610
5611     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5612     if (PrevOuterContext->isRecord())
5613       // We found a member function: ignore it.
5614       return false;
5615
5616     // Find the innermost enclosing namespace for the new and
5617     // previous declarations.
5618     OuterContext = OuterContext->getEnclosingNamespaceContext();
5619     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5620
5621     // The previous declaration is in a different namespace, so it
5622     // isn't the same function.
5623     if (!OuterContext->Equals(PrevOuterContext))
5624       return false;
5625   }
5626
5627   return true;
5628 }
5629
5630 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5631   CXXScopeSpec &SS = D.getCXXScopeSpec();
5632   if (!SS.isSet()) return;
5633   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5634 }
5635
5636 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5637   QualType type = decl->getType();
5638   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5639   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5640     // Various kinds of declaration aren't allowed to be __autoreleasing.
5641     unsigned kind = -1U;
5642     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5643       if (var->hasAttr<BlocksAttr>())
5644         kind = 0; // __block
5645       else if (!var->hasLocalStorage())
5646         kind = 1; // global
5647     } else if (isa<ObjCIvarDecl>(decl)) {
5648       kind = 3; // ivar
5649     } else if (isa<FieldDecl>(decl)) {
5650       kind = 2; // field
5651     }
5652
5653     if (kind != -1U) {
5654       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5655         << kind;
5656     }
5657   } else if (lifetime == Qualifiers::OCL_None) {
5658     // Try to infer lifetime.
5659     if (!type->isObjCLifetimeType())
5660       return false;
5661
5662     lifetime = type->getObjCARCImplicitLifetime();
5663     type = Context.getLifetimeQualifiedType(type, lifetime);
5664     decl->setType(type);
5665   }
5666
5667   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5668     // Thread-local variables cannot have lifetime.
5669     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5670         var->getTLSKind()) {
5671       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5672         << var->getType();
5673       return true;
5674     }
5675   }
5676
5677   return false;
5678 }
5679
5680 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5681   // Ensure that an auto decl is deduced otherwise the checks below might cache
5682   // the wrong linkage.
5683   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5684
5685   // 'weak' only applies to declarations with external linkage.
5686   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5687     if (!ND.isExternallyVisible()) {
5688       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5689       ND.dropAttr<WeakAttr>();
5690     }
5691   }
5692   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5693     if (ND.isExternallyVisible()) {
5694       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5695       ND.dropAttr<WeakRefAttr>();
5696       ND.dropAttr<AliasAttr>();
5697     }
5698   }
5699
5700   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5701     if (VD->hasInit()) {
5702       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5703         assert(VD->isThisDeclarationADefinition() &&
5704                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5705         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5706         VD->dropAttr<AliasAttr>();
5707       }
5708     }
5709   }
5710
5711   // 'selectany' only applies to externally visible variable declarations.
5712   // It does not apply to functions.
5713   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5714     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5715       S.Diag(Attr->getLocation(),
5716              diag::err_attribute_selectany_non_extern_data);
5717       ND.dropAttr<SelectAnyAttr>();
5718     }
5719   }
5720
5721   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5722     // dll attributes require external linkage. Static locals may have external
5723     // linkage but still cannot be explicitly imported or exported.
5724     auto *VD = dyn_cast<VarDecl>(&ND);
5725     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5726       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5727         << &ND << Attr;
5728       ND.setInvalidDecl();
5729     }
5730   }
5731
5732   // Virtual functions cannot be marked as 'notail'.
5733   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5734     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5735       if (MD->isVirtual()) {
5736         S.Diag(ND.getLocation(),
5737                diag::err_invalid_attribute_on_virtual_function)
5738             << Attr;
5739         ND.dropAttr<NotTailCalledAttr>();
5740       }
5741 }
5742
5743 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5744                                            NamedDecl *NewDecl,
5745                                            bool IsSpecialization,
5746                                            bool IsDefinition) {
5747   if (OldDecl->isInvalidDecl())
5748     return;
5749
5750   bool IsTemplate = false;
5751   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5752     OldDecl = OldTD->getTemplatedDecl();
5753     IsTemplate = true;
5754     if (!IsSpecialization)
5755       IsDefinition = false;
5756   }
5757   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5758     NewDecl = NewTD->getTemplatedDecl();
5759     IsTemplate = true;
5760   }
5761
5762   if (!OldDecl || !NewDecl)
5763     return;
5764
5765   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5766   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5767   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5768   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5769
5770   // dllimport and dllexport are inheritable attributes so we have to exclude
5771   // inherited attribute instances.
5772   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5773                     (NewExportAttr && !NewExportAttr->isInherited());
5774
5775   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5776   // the only exception being explicit specializations.
5777   // Implicitly generated declarations are also excluded for now because there
5778   // is no other way to switch these to use dllimport or dllexport.
5779   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5780
5781   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5782     // Allow with a warning for free functions and global variables.
5783     bool JustWarn = false;
5784     if (!OldDecl->isCXXClassMember()) {
5785       auto *VD = dyn_cast<VarDecl>(OldDecl);
5786       if (VD && !VD->getDescribedVarTemplate())
5787         JustWarn = true;
5788       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5789       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5790         JustWarn = true;
5791     }
5792
5793     // We cannot change a declaration that's been used because IR has already
5794     // been emitted. Dllimported functions will still work though (modulo
5795     // address equality) as they can use the thunk.
5796     if (OldDecl->isUsed())
5797       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5798         JustWarn = false;
5799
5800     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5801                                : diag::err_attribute_dll_redeclaration;
5802     S.Diag(NewDecl->getLocation(), DiagID)
5803         << NewDecl
5804         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5805     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5806     if (!JustWarn) {
5807       NewDecl->setInvalidDecl();
5808       return;
5809     }
5810   }
5811
5812   // A redeclaration is not allowed to drop a dllimport attribute, the only
5813   // exceptions being inline function definitions (except for function
5814   // templates), local extern declarations, qualified friend declarations or
5815   // special MSVC extension: in the last case, the declaration is treated as if
5816   // it were marked dllexport.
5817   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5818   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5819   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5820     // Ignore static data because out-of-line definitions are diagnosed
5821     // separately.
5822     IsStaticDataMember = VD->isStaticDataMember();
5823     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5824                    VarDecl::DeclarationOnly;
5825   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5826     IsInline = FD->isInlined();
5827     IsQualifiedFriend = FD->getQualifier() &&
5828                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5829   }
5830
5831   if (OldImportAttr && !HasNewAttr &&
5832       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
5833       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5834     if (IsMicrosoft && IsDefinition) {
5835       S.Diag(NewDecl->getLocation(),
5836              diag::warn_redeclaration_without_import_attribute)
5837           << NewDecl;
5838       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5839       NewDecl->dropAttr<DLLImportAttr>();
5840       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5841           NewImportAttr->getRange(), S.Context,
5842           NewImportAttr->getSpellingListIndex()));
5843     } else {
5844       S.Diag(NewDecl->getLocation(),
5845              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5846           << NewDecl << OldImportAttr;
5847       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5848       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5849       OldDecl->dropAttr<DLLImportAttr>();
5850       NewDecl->dropAttr<DLLImportAttr>();
5851     }
5852   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5853     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5854     OldDecl->dropAttr<DLLImportAttr>();
5855     NewDecl->dropAttr<DLLImportAttr>();
5856     S.Diag(NewDecl->getLocation(),
5857            diag::warn_dllimport_dropped_from_inline_function)
5858         << NewDecl << OldImportAttr;
5859   }
5860 }
5861
5862 /// Given that we are within the definition of the given function,
5863 /// will that definition behave like C99's 'inline', where the
5864 /// definition is discarded except for optimization purposes?
5865 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5866   // Try to avoid calling GetGVALinkageForFunction.
5867
5868   // All cases of this require the 'inline' keyword.
5869   if (!FD->isInlined()) return false;
5870
5871   // This is only possible in C++ with the gnu_inline attribute.
5872   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5873     return false;
5874
5875   // Okay, go ahead and call the relatively-more-expensive function.
5876   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5877 }
5878
5879 /// Determine whether a variable is extern "C" prior to attaching
5880 /// an initializer. We can't just call isExternC() here, because that
5881 /// will also compute and cache whether the declaration is externally
5882 /// visible, which might change when we attach the initializer.
5883 ///
5884 /// This can only be used if the declaration is known to not be a
5885 /// redeclaration of an internal linkage declaration.
5886 ///
5887 /// For instance:
5888 ///
5889 ///   auto x = []{};
5890 ///
5891 /// Attaching the initializer here makes this declaration not externally
5892 /// visible, because its type has internal linkage.
5893 ///
5894 /// FIXME: This is a hack.
5895 template<typename T>
5896 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5897   if (S.getLangOpts().CPlusPlus) {
5898     // In C++, the overloadable attribute negates the effects of extern "C".
5899     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5900       return false;
5901
5902     // So do CUDA's host/device attributes.
5903     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5904                                  D->template hasAttr<CUDAHostAttr>()))
5905       return false;
5906   }
5907   return D->isExternC();
5908 }
5909
5910 static bool shouldConsiderLinkage(const VarDecl *VD) {
5911   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5912   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5913     return VD->hasExternalStorage();
5914   if (DC->isFileContext())
5915     return true;
5916   if (DC->isRecord())
5917     return false;
5918   llvm_unreachable("Unexpected context");
5919 }
5920
5921 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5922   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5923   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5924       isa<OMPDeclareReductionDecl>(DC))
5925     return true;
5926   if (DC->isRecord())
5927     return false;
5928   llvm_unreachable("Unexpected context");
5929 }
5930
5931 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5932                           AttributeList::Kind Kind) {
5933   for (const AttributeList *L = AttrList; L; L = L->getNext())
5934     if (L->getKind() == Kind)
5935       return true;
5936   return false;
5937 }
5938
5939 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5940                           AttributeList::Kind Kind) {
5941   // Check decl attributes on the DeclSpec.
5942   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5943     return true;
5944
5945   // Walk the declarator structure, checking decl attributes that were in a type
5946   // position to the decl itself.
5947   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5948     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5949       return true;
5950   }
5951
5952   // Finally, check attributes on the decl itself.
5953   return hasParsedAttr(S, PD.getAttributes(), Kind);
5954 }
5955
5956 /// Adjust the \c DeclContext for a function or variable that might be a
5957 /// function-local external declaration.
5958 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5959   if (!DC->isFunctionOrMethod())
5960     return false;
5961
5962   // If this is a local extern function or variable declared within a function
5963   // template, don't add it into the enclosing namespace scope until it is
5964   // instantiated; it might have a dependent type right now.
5965   if (DC->isDependentContext())
5966     return true;
5967
5968   // C++11 [basic.link]p7:
5969   //   When a block scope declaration of an entity with linkage is not found to
5970   //   refer to some other declaration, then that entity is a member of the
5971   //   innermost enclosing namespace.
5972   //
5973   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5974   // semantically-enclosing namespace, not a lexically-enclosing one.
5975   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5976     DC = DC->getParent();
5977   return true;
5978 }
5979
5980 /// \brief Returns true if given declaration has external C language linkage.
5981 static bool isDeclExternC(const Decl *D) {
5982   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5983     return FD->isExternC();
5984   if (const auto *VD = dyn_cast<VarDecl>(D))
5985     return VD->isExternC();
5986
5987   llvm_unreachable("Unknown type of decl!");
5988 }
5989
5990 NamedDecl *Sema::ActOnVariableDeclarator(
5991     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
5992     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
5993     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
5994   QualType R = TInfo->getType();
5995   DeclarationName Name = GetNameForDeclarator(D).getName();
5996
5997   IdentifierInfo *II = Name.getAsIdentifierInfo();
5998
5999   if (D.isDecompositionDeclarator()) {
6000     AddToScope = false;
6001     // Take the name of the first declarator as our name for diagnostic
6002     // purposes.
6003     auto &Decomp = D.getDecompositionDeclarator();
6004     if (!Decomp.bindings().empty()) {
6005       II = Decomp.bindings()[0].Name;
6006       Name = II;
6007     }
6008   } else if (!II) {
6009     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6010     return nullptr;
6011   }
6012
6013   if (getLangOpts().OpenCL) {
6014     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6015     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6016     // argument.
6017     if (R->isImageType() || R->isPipeType()) {
6018       Diag(D.getIdentifierLoc(),
6019            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6020           << R;
6021       D.setInvalidType();
6022       return nullptr;
6023     }
6024
6025     // OpenCL v1.2 s6.9.r:
6026     // The event type cannot be used to declare a program scope variable.
6027     // OpenCL v2.0 s6.9.q:
6028     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6029     if (NULL == S->getParent()) {
6030       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6031         Diag(D.getIdentifierLoc(),
6032              diag::err_invalid_type_for_program_scope_var) << R;
6033         D.setInvalidType();
6034         return nullptr;
6035       }
6036     }
6037
6038     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6039     QualType NR = R;
6040     while (NR->isPointerType()) {
6041       if (NR->isFunctionPointerType()) {
6042         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
6043         D.setInvalidType();
6044         break;
6045       }
6046       NR = NR->getPointeeType();
6047     }
6048
6049     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6050       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6051       // half array type (unless the cl_khr_fp16 extension is enabled).
6052       if (Context.getBaseElementType(R)->isHalfType()) {
6053         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6054         D.setInvalidType();
6055       }
6056     }
6057
6058     // OpenCL v1.2 s6.9.b p4:
6059     // The sampler type cannot be used with the __local and __global address
6060     // space qualifiers.
6061     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
6062       R.getAddressSpace() == LangAS::opencl_global)) {
6063       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6064     }
6065
6066     // OpenCL v1.2 s6.9.r:
6067     // The event type cannot be used with the __local, __constant and __global
6068     // address space qualifiers.
6069     if (R->isEventT()) {
6070       if (R.getAddressSpace()) {
6071         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6072         D.setInvalidType();
6073       }
6074     }
6075   }
6076
6077   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6078   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6079
6080   // dllimport globals without explicit storage class are treated as extern. We
6081   // have to change the storage class this early to get the right DeclContext.
6082   if (SC == SC_None && !DC->isRecord() &&
6083       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6084       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6085     SC = SC_Extern;
6086
6087   DeclContext *OriginalDC = DC;
6088   bool IsLocalExternDecl = SC == SC_Extern &&
6089                            adjustContextForLocalExternDecl(DC);
6090
6091   if (SCSpec == DeclSpec::SCS_mutable) {
6092     // mutable can only appear on non-static class members, so it's always
6093     // an error here
6094     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6095     D.setInvalidType();
6096     SC = SC_None;
6097   }
6098
6099   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6100       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6101                               D.getDeclSpec().getStorageClassSpecLoc())) {
6102     // In C++11, the 'register' storage class specifier is deprecated.
6103     // Suppress the warning in system macros, it's used in macros in some
6104     // popular C system headers, such as in glibc's htonl() macro.
6105     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6106          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6107                                    : diag::warn_deprecated_register)
6108       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6109   }
6110
6111   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6112
6113   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6114     // C99 6.9p2: The storage-class specifiers auto and register shall not
6115     // appear in the declaration specifiers in an external declaration.
6116     // Global Register+Asm is a GNU extension we support.
6117     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6118       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6119       D.setInvalidType();
6120     }
6121   }
6122
6123   bool IsMemberSpecialization = false;
6124   bool IsVariableTemplateSpecialization = false;
6125   bool IsPartialSpecialization = false;
6126   bool IsVariableTemplate = false;
6127   VarDecl *NewVD = nullptr;
6128   VarTemplateDecl *NewTemplate = nullptr;
6129   TemplateParameterList *TemplateParams = nullptr;
6130   if (!getLangOpts().CPlusPlus) {
6131     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6132                             D.getIdentifierLoc(), II,
6133                             R, TInfo, SC);
6134
6135     if (R->getContainedDeducedType())
6136       ParsingInitForAutoVars.insert(NewVD);
6137
6138     if (D.isInvalidType())
6139       NewVD->setInvalidDecl();
6140   } else {
6141     bool Invalid = false;
6142
6143     if (DC->isRecord() && !CurContext->isRecord()) {
6144       // This is an out-of-line definition of a static data member.
6145       switch (SC) {
6146       case SC_None:
6147         break;
6148       case SC_Static:
6149         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6150              diag::err_static_out_of_line)
6151           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6152         break;
6153       case SC_Auto:
6154       case SC_Register:
6155       case SC_Extern:
6156         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6157         // to names of variables declared in a block or to function parameters.
6158         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6159         // of class members
6160
6161         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6162              diag::err_storage_class_for_static_member)
6163           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6164         break;
6165       case SC_PrivateExtern:
6166         llvm_unreachable("C storage class in c++!");
6167       }
6168     }
6169
6170     if (SC == SC_Static && CurContext->isRecord()) {
6171       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6172         if (RD->isLocalClass())
6173           Diag(D.getIdentifierLoc(),
6174                diag::err_static_data_member_not_allowed_in_local_class)
6175             << Name << RD->getDeclName();
6176
6177         // C++98 [class.union]p1: If a union contains a static data member,
6178         // the program is ill-formed. C++11 drops this restriction.
6179         if (RD->isUnion())
6180           Diag(D.getIdentifierLoc(),
6181                getLangOpts().CPlusPlus11
6182                  ? diag::warn_cxx98_compat_static_data_member_in_union
6183                  : diag::ext_static_data_member_in_union) << Name;
6184         // We conservatively disallow static data members in anonymous structs.
6185         else if (!RD->getDeclName())
6186           Diag(D.getIdentifierLoc(),
6187                diag::err_static_data_member_not_allowed_in_anon_struct)
6188             << Name << RD->isUnion();
6189       }
6190     }
6191
6192     // Match up the template parameter lists with the scope specifier, then
6193     // determine whether we have a template or a template specialization.
6194     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6195         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6196         D.getCXXScopeSpec(),
6197         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6198             ? D.getName().TemplateId
6199             : nullptr,
6200         TemplateParamLists,
6201         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6202
6203     if (TemplateParams) {
6204       if (!TemplateParams->size() &&
6205           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6206         // There is an extraneous 'template<>' for this variable. Complain
6207         // about it, but allow the declaration of the variable.
6208         Diag(TemplateParams->getTemplateLoc(),
6209              diag::err_template_variable_noparams)
6210           << II
6211           << SourceRange(TemplateParams->getTemplateLoc(),
6212                          TemplateParams->getRAngleLoc());
6213         TemplateParams = nullptr;
6214       } else {
6215         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6216           // This is an explicit specialization or a partial specialization.
6217           // FIXME: Check that we can declare a specialization here.
6218           IsVariableTemplateSpecialization = true;
6219           IsPartialSpecialization = TemplateParams->size() > 0;
6220         } else { // if (TemplateParams->size() > 0)
6221           // This is a template declaration.
6222           IsVariableTemplate = true;
6223
6224           // Check that we can declare a template here.
6225           if (CheckTemplateDeclScope(S, TemplateParams))
6226             return nullptr;
6227
6228           // Only C++1y supports variable templates (N3651).
6229           Diag(D.getIdentifierLoc(),
6230                getLangOpts().CPlusPlus14
6231                    ? diag::warn_cxx11_compat_variable_template
6232                    : diag::ext_variable_template);
6233         }
6234       }
6235     } else {
6236       assert(
6237           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6238           "should have a 'template<>' for this decl");
6239     }
6240
6241     if (IsVariableTemplateSpecialization) {
6242       SourceLocation TemplateKWLoc =
6243           TemplateParamLists.size() > 0
6244               ? TemplateParamLists[0]->getTemplateLoc()
6245               : SourceLocation();
6246       DeclResult Res = ActOnVarTemplateSpecialization(
6247           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6248           IsPartialSpecialization);
6249       if (Res.isInvalid())
6250         return nullptr;
6251       NewVD = cast<VarDecl>(Res.get());
6252       AddToScope = false;
6253     } else if (D.isDecompositionDeclarator()) {
6254       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6255                                         D.getIdentifierLoc(), R, TInfo, SC,
6256                                         Bindings);
6257     } else
6258       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6259                               D.getIdentifierLoc(), II, R, TInfo, SC);
6260
6261     // If this is supposed to be a variable template, create it as such.
6262     if (IsVariableTemplate) {
6263       NewTemplate =
6264           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6265                                   TemplateParams, NewVD);
6266       NewVD->setDescribedVarTemplate(NewTemplate);
6267     }
6268
6269     // If this decl has an auto type in need of deduction, make a note of the
6270     // Decl so we can diagnose uses of it in its own initializer.
6271     if (R->getContainedDeducedType())
6272       ParsingInitForAutoVars.insert(NewVD);
6273
6274     if (D.isInvalidType() || Invalid) {
6275       NewVD->setInvalidDecl();
6276       if (NewTemplate)
6277         NewTemplate->setInvalidDecl();
6278     }
6279
6280     SetNestedNameSpecifier(NewVD, D);
6281
6282     // If we have any template parameter lists that don't directly belong to
6283     // the variable (matching the scope specifier), store them.
6284     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6285     if (TemplateParamLists.size() > VDTemplateParamLists)
6286       NewVD->setTemplateParameterListsInfo(
6287           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6288
6289     if (D.getDeclSpec().isConstexprSpecified()) {
6290       NewVD->setConstexpr(true);
6291       // C++1z [dcl.spec.constexpr]p1:
6292       //   A static data member declared with the constexpr specifier is
6293       //   implicitly an inline variable.
6294       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6295         NewVD->setImplicitlyInline();
6296     }
6297
6298     if (D.getDeclSpec().isConceptSpecified()) {
6299       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6300         VTD->setConcept();
6301
6302       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6303       // be declared with the thread_local, inline, friend, or constexpr
6304       // specifiers, [...]
6305       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6306         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6307              diag::err_concept_decl_invalid_specifiers)
6308             << 0 << 0;
6309         NewVD->setInvalidDecl(true);
6310       }
6311
6312       if (D.getDeclSpec().isConstexprSpecified()) {
6313         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6314              diag::err_concept_decl_invalid_specifiers)
6315             << 0 << 3;
6316         NewVD->setInvalidDecl(true);
6317       }
6318
6319       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6320       // applied only to the definition of a function template or variable
6321       // template, declared in namespace scope.
6322       if (IsVariableTemplateSpecialization) {
6323         Diag(D.getDeclSpec().getConceptSpecLoc(),
6324              diag::err_concept_specified_specialization)
6325             << (IsPartialSpecialization ? 2 : 1);
6326       }
6327
6328       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6329       // following restrictions:
6330       // - The declared type shall have the type bool.
6331       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6332           !NewVD->isInvalidDecl()) {
6333         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6334         NewVD->setInvalidDecl(true);
6335       }
6336     }
6337   }
6338
6339   if (D.getDeclSpec().isInlineSpecified()) {
6340     if (!getLangOpts().CPlusPlus) {
6341       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6342           << 0;
6343     } else if (CurContext->isFunctionOrMethod()) {
6344       // 'inline' is not allowed on block scope variable declaration.
6345       Diag(D.getDeclSpec().getInlineSpecLoc(),
6346            diag::err_inline_declaration_block_scope) << Name
6347         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6348     } else {
6349       Diag(D.getDeclSpec().getInlineSpecLoc(),
6350            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6351                                      : diag::ext_inline_variable);
6352       NewVD->setInlineSpecified();
6353     }
6354   }
6355
6356   // Set the lexical context. If the declarator has a C++ scope specifier, the
6357   // lexical context will be different from the semantic context.
6358   NewVD->setLexicalDeclContext(CurContext);
6359   if (NewTemplate)
6360     NewTemplate->setLexicalDeclContext(CurContext);
6361
6362   if (IsLocalExternDecl) {
6363     if (D.isDecompositionDeclarator())
6364       for (auto *B : Bindings)
6365         B->setLocalExternDecl();
6366     else
6367       NewVD->setLocalExternDecl();
6368   }
6369
6370   bool EmitTLSUnsupportedError = false;
6371   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6372     // C++11 [dcl.stc]p4:
6373     //   When thread_local is applied to a variable of block scope the
6374     //   storage-class-specifier static is implied if it does not appear
6375     //   explicitly.
6376     // Core issue: 'static' is not implied if the variable is declared
6377     //   'extern'.
6378     if (NewVD->hasLocalStorage() &&
6379         (SCSpec != DeclSpec::SCS_unspecified ||
6380          TSCS != DeclSpec::TSCS_thread_local ||
6381          !DC->isFunctionOrMethod()))
6382       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6383            diag::err_thread_non_global)
6384         << DeclSpec::getSpecifierName(TSCS);
6385     else if (!Context.getTargetInfo().isTLSSupported()) {
6386       if (getLangOpts().CUDA) {
6387         // Postpone error emission until we've collected attributes required to
6388         // figure out whether it's a host or device variable and whether the
6389         // error should be ignored.
6390         EmitTLSUnsupportedError = true;
6391         // We still need to mark the variable as TLS so it shows up in AST with
6392         // proper storage class for other tools to use even if we're not going
6393         // to emit any code for it.
6394         NewVD->setTSCSpec(TSCS);
6395       } else
6396         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6397              diag::err_thread_unsupported);
6398     } else
6399       NewVD->setTSCSpec(TSCS);
6400   }
6401
6402   // C99 6.7.4p3
6403   //   An inline definition of a function with external linkage shall
6404   //   not contain a definition of a modifiable object with static or
6405   //   thread storage duration...
6406   // We only apply this when the function is required to be defined
6407   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6408   // that a local variable with thread storage duration still has to
6409   // be marked 'static'.  Also note that it's possible to get these
6410   // semantics in C++ using __attribute__((gnu_inline)).
6411   if (SC == SC_Static && S->getFnParent() != nullptr &&
6412       !NewVD->getType().isConstQualified()) {
6413     FunctionDecl *CurFD = getCurFunctionDecl();
6414     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6415       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6416            diag::warn_static_local_in_extern_inline);
6417       MaybeSuggestAddingStaticToDecl(CurFD);
6418     }
6419   }
6420
6421   if (D.getDeclSpec().isModulePrivateSpecified()) {
6422     if (IsVariableTemplateSpecialization)
6423       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6424           << (IsPartialSpecialization ? 1 : 0)
6425           << FixItHint::CreateRemoval(
6426                  D.getDeclSpec().getModulePrivateSpecLoc());
6427     else if (IsMemberSpecialization)
6428       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6429         << 2
6430         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6431     else if (NewVD->hasLocalStorage())
6432       Diag(NewVD->getLocation(), diag::err_module_private_local)
6433         << 0 << NewVD->getDeclName()
6434         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6435         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6436     else {
6437       NewVD->setModulePrivate();
6438       if (NewTemplate)
6439         NewTemplate->setModulePrivate();
6440       for (auto *B : Bindings)
6441         B->setModulePrivate();
6442     }
6443   }
6444
6445   // Handle attributes prior to checking for duplicates in MergeVarDecl
6446   ProcessDeclAttributes(S, NewVD, D);
6447
6448   if (getLangOpts().CUDA) {
6449     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6450       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6451            diag::err_thread_unsupported);
6452     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6453     // storage [duration]."
6454     if (SC == SC_None && S->getFnParent() != nullptr &&
6455         (NewVD->hasAttr<CUDASharedAttr>() ||
6456          NewVD->hasAttr<CUDAConstantAttr>())) {
6457       NewVD->setStorageClass(SC_Static);
6458     }
6459   }
6460
6461   // Ensure that dllimport globals without explicit storage class are treated as
6462   // extern. The storage class is set above using parsed attributes. Now we can
6463   // check the VarDecl itself.
6464   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6465          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6466          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6467
6468   // In auto-retain/release, infer strong retension for variables of
6469   // retainable type.
6470   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6471     NewVD->setInvalidDecl();
6472
6473   // Handle GNU asm-label extension (encoded as an attribute).
6474   if (Expr *E = (Expr*)D.getAsmLabel()) {
6475     // The parser guarantees this is a string.
6476     StringLiteral *SE = cast<StringLiteral>(E);
6477     StringRef Label = SE->getString();
6478     if (S->getFnParent() != nullptr) {
6479       switch (SC) {
6480       case SC_None:
6481       case SC_Auto:
6482         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6483         break;
6484       case SC_Register:
6485         // Local Named register
6486         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6487             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6488           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6489         break;
6490       case SC_Static:
6491       case SC_Extern:
6492       case SC_PrivateExtern:
6493         break;
6494       }
6495     } else if (SC == SC_Register) {
6496       // Global Named register
6497       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6498         const auto &TI = Context.getTargetInfo();
6499         bool HasSizeMismatch;
6500
6501         if (!TI.isValidGCCRegisterName(Label))
6502           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6503         else if (!TI.validateGlobalRegisterVariable(Label,
6504                                                     Context.getTypeSize(R),
6505                                                     HasSizeMismatch))
6506           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6507         else if (HasSizeMismatch)
6508           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6509       }
6510
6511       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6512         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6513         NewVD->setInvalidDecl(true);
6514       }
6515     }
6516
6517     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6518                                                 Context, Label, 0));
6519   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6520     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6521       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6522     if (I != ExtnameUndeclaredIdentifiers.end()) {
6523       if (isDeclExternC(NewVD)) {
6524         NewVD->addAttr(I->second);
6525         ExtnameUndeclaredIdentifiers.erase(I);
6526       } else
6527         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6528             << /*Variable*/1 << NewVD;
6529     }
6530   }
6531
6532   // Find the shadowed declaration before filtering for scope.
6533   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6534                                 ? getShadowedDeclaration(NewVD, Previous)
6535                                 : nullptr;
6536
6537   // Don't consider existing declarations that are in a different
6538   // scope and are out-of-semantic-context declarations (if the new
6539   // declaration has linkage).
6540   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6541                        D.getCXXScopeSpec().isNotEmpty() ||
6542                        IsMemberSpecialization ||
6543                        IsVariableTemplateSpecialization);
6544
6545   // Check whether the previous declaration is in the same block scope. This
6546   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6547   if (getLangOpts().CPlusPlus &&
6548       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6549     NewVD->setPreviousDeclInSameBlockScope(
6550         Previous.isSingleResult() && !Previous.isShadowed() &&
6551         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6552
6553   if (!getLangOpts().CPlusPlus) {
6554     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6555   } else {
6556     // If this is an explicit specialization of a static data member, check it.
6557     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6558         CheckMemberSpecialization(NewVD, Previous))
6559       NewVD->setInvalidDecl();
6560
6561     // Merge the decl with the existing one if appropriate.
6562     if (!Previous.empty()) {
6563       if (Previous.isSingleResult() &&
6564           isa<FieldDecl>(Previous.getFoundDecl()) &&
6565           D.getCXXScopeSpec().isSet()) {
6566         // The user tried to define a non-static data member
6567         // out-of-line (C++ [dcl.meaning]p1).
6568         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6569           << D.getCXXScopeSpec().getRange();
6570         Previous.clear();
6571         NewVD->setInvalidDecl();
6572       }
6573     } else if (D.getCXXScopeSpec().isSet()) {
6574       // No previous declaration in the qualifying scope.
6575       Diag(D.getIdentifierLoc(), diag::err_no_member)
6576         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6577         << D.getCXXScopeSpec().getRange();
6578       NewVD->setInvalidDecl();
6579     }
6580
6581     if (!IsVariableTemplateSpecialization)
6582       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6583
6584     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6585     // an explicit specialization (14.8.3) or a partial specialization of a
6586     // concept definition.
6587     if (IsVariableTemplateSpecialization &&
6588         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6589         Previous.isSingleResult()) {
6590       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6591       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6592         if (VarTmpl->isConcept()) {
6593           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6594               << 1                            /*variable*/
6595               << (IsPartialSpecialization ? 2 /*partially specialized*/
6596                                           : 1 /*explicitly specialized*/);
6597           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6598           NewVD->setInvalidDecl();
6599         }
6600       }
6601     }
6602
6603     if (NewTemplate) {
6604       VarTemplateDecl *PrevVarTemplate =
6605           NewVD->getPreviousDecl()
6606               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6607               : nullptr;
6608
6609       // Check the template parameter list of this declaration, possibly
6610       // merging in the template parameter list from the previous variable
6611       // template declaration.
6612       if (CheckTemplateParameterList(
6613               TemplateParams,
6614               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6615                               : nullptr,
6616               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6617                DC->isDependentContext())
6618                   ? TPC_ClassTemplateMember
6619                   : TPC_VarTemplate))
6620         NewVD->setInvalidDecl();
6621
6622       // If we are providing an explicit specialization of a static variable
6623       // template, make a note of that.
6624       if (PrevVarTemplate &&
6625           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6626         PrevVarTemplate->setMemberSpecialization();
6627     }
6628   }
6629
6630   // Diagnose shadowed variables iff this isn't a redeclaration.
6631   if (ShadowedDecl && !D.isRedeclaration())
6632     CheckShadow(NewVD, ShadowedDecl, Previous);
6633
6634   ProcessPragmaWeak(S, NewVD);
6635
6636   // If this is the first declaration of an extern C variable, update
6637   // the map of such variables.
6638   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6639       isIncompleteDeclExternC(*this, NewVD))
6640     RegisterLocallyScopedExternCDecl(NewVD, S);
6641
6642   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6643     Decl *ManglingContextDecl;
6644     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6645             NewVD->getDeclContext(), ManglingContextDecl)) {
6646       Context.setManglingNumber(
6647           NewVD, MCtx->getManglingNumber(
6648                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6649       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6650     }
6651   }
6652
6653   // Special handling of variable named 'main'.
6654   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6655       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6656       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6657
6658     // C++ [basic.start.main]p3
6659     // A program that declares a variable main at global scope is ill-formed.
6660     if (getLangOpts().CPlusPlus)
6661       Diag(D.getLocStart(), diag::err_main_global_variable);
6662
6663     // In C, and external-linkage variable named main results in undefined
6664     // behavior.
6665     else if (NewVD->hasExternalFormalLinkage())
6666       Diag(D.getLocStart(), diag::warn_main_redefined);
6667   }
6668
6669   if (D.isRedeclaration() && !Previous.empty()) {
6670     checkDLLAttributeRedeclaration(
6671         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6672         IsMemberSpecialization, D.isFunctionDefinition());
6673   }
6674
6675   if (NewTemplate) {
6676     if (NewVD->isInvalidDecl())
6677       NewTemplate->setInvalidDecl();
6678     ActOnDocumentableDecl(NewTemplate);
6679     return NewTemplate;
6680   }
6681
6682   return NewVD;
6683 }
6684
6685 /// Enum describing the %select options in diag::warn_decl_shadow.
6686 enum ShadowedDeclKind {
6687   SDK_Local,
6688   SDK_Global,
6689   SDK_StaticMember,
6690   SDK_Field,
6691   SDK_Typedef,
6692   SDK_Using
6693 };
6694
6695 /// Determine what kind of declaration we're shadowing.
6696 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6697                                                 const DeclContext *OldDC) {
6698   if (isa<TypeAliasDecl>(ShadowedDecl))
6699     return SDK_Using;
6700   else if (isa<TypedefDecl>(ShadowedDecl))
6701     return SDK_Typedef;
6702   else if (isa<RecordDecl>(OldDC))
6703     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6704
6705   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6706 }
6707
6708 /// Return the location of the capture if the given lambda captures the given
6709 /// variable \p VD, or an invalid source location otherwise.
6710 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6711                                          const VarDecl *VD) {
6712   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6713     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6714       return Capture.getLocation();
6715   }
6716   return SourceLocation();
6717 }
6718
6719 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6720                                      const LookupResult &R) {
6721   // Only diagnose if we're shadowing an unambiguous field or variable.
6722   if (R.getResultKind() != LookupResult::Found)
6723     return false;
6724
6725   // Return false if warning is ignored.
6726   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6727 }
6728
6729 /// \brief Return the declaration shadowed by the given variable \p D, or null
6730 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6731 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6732                                         const LookupResult &R) {
6733   if (!shouldWarnIfShadowedDecl(Diags, R))
6734     return nullptr;
6735
6736   // Don't diagnose declarations at file scope.
6737   if (D->hasGlobalStorage())
6738     return nullptr;
6739
6740   NamedDecl *ShadowedDecl = R.getFoundDecl();
6741   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6742              ? ShadowedDecl
6743              : nullptr;
6744 }
6745
6746 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6747 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6748 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6749                                         const LookupResult &R) {
6750   // Don't warn if typedef declaration is part of a class
6751   if (D->getDeclContext()->isRecord())
6752     return nullptr;
6753   
6754   if (!shouldWarnIfShadowedDecl(Diags, R))
6755     return nullptr;
6756
6757   NamedDecl *ShadowedDecl = R.getFoundDecl();
6758   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6759 }
6760
6761 /// \brief Diagnose variable or built-in function shadowing.  Implements
6762 /// -Wshadow.
6763 ///
6764 /// This method is called whenever a VarDecl is added to a "useful"
6765 /// scope.
6766 ///
6767 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6768 /// \param R the lookup of the name
6769 ///
6770 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6771                        const LookupResult &R) {
6772   DeclContext *NewDC = D->getDeclContext();
6773
6774   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6775     // Fields are not shadowed by variables in C++ static methods.
6776     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6777       if (MD->isStatic())
6778         return;
6779
6780     // Fields shadowed by constructor parameters are a special case. Usually
6781     // the constructor initializes the field with the parameter.
6782     if (isa<CXXConstructorDecl>(NewDC))
6783       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
6784         // Remember that this was shadowed so we can either warn about its
6785         // modification or its existence depending on warning settings.
6786         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
6787         return;
6788       }
6789   }
6790
6791   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6792     if (shadowedVar->isExternC()) {
6793       // For shadowing external vars, make sure that we point to the global
6794       // declaration, not a locally scoped extern declaration.
6795       for (auto I : shadowedVar->redecls())
6796         if (I->isFileVarDecl()) {
6797           ShadowedDecl = I;
6798           break;
6799         }
6800     }
6801
6802   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6803
6804   unsigned WarningDiag = diag::warn_decl_shadow;
6805   SourceLocation CaptureLoc;
6806   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
6807       isa<CXXMethodDecl>(NewDC)) {
6808     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6809       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6810         if (RD->getLambdaCaptureDefault() == LCD_None) {
6811           // Try to avoid warnings for lambdas with an explicit capture list.
6812           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6813           // Warn only when the lambda captures the shadowed decl explicitly.
6814           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6815           if (CaptureLoc.isInvalid())
6816             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6817         } else {
6818           // Remember that this was shadowed so we can avoid the warning if the
6819           // shadowed decl isn't captured and the warning settings allow it.
6820           cast<LambdaScopeInfo>(getCurFunction())
6821               ->ShadowingDecls.push_back(
6822                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
6823           return;
6824         }
6825       }
6826     }
6827   }
6828
6829   // Only warn about certain kinds of shadowing for class members.
6830   if (NewDC && NewDC->isRecord()) {
6831     // In particular, don't warn about shadowing non-class members.
6832     if (!OldDC->isRecord())
6833       return;
6834
6835     // TODO: should we warn about static data members shadowing
6836     // static data members from base classes?
6837
6838     // TODO: don't diagnose for inaccessible shadowed members.
6839     // This is hard to do perfectly because we might friend the
6840     // shadowing context, but that's just a false negative.
6841   }
6842
6843
6844   DeclarationName Name = R.getLookupName();
6845
6846   // Emit warning and note.
6847   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6848     return;
6849   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6850   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
6851   if (!CaptureLoc.isInvalid())
6852     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6853         << Name << /*explicitly*/ 1;
6854   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6855 }
6856
6857 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
6858 /// when these variables are captured by the lambda.
6859 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
6860   for (const auto &Shadow : LSI->ShadowingDecls) {
6861     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
6862     // Try to avoid the warning when the shadowed decl isn't captured.
6863     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
6864     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6865     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
6866                                        ? diag::warn_decl_shadow_uncaptured_local
6867                                        : diag::warn_decl_shadow)
6868         << Shadow.VD->getDeclName()
6869         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
6870     if (!CaptureLoc.isInvalid())
6871       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6872           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
6873     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6874   }
6875 }
6876
6877 /// \brief Check -Wshadow without the advantage of a previous lookup.
6878 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6879   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6880     return;
6881
6882   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6883                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6884   LookupName(R, S);
6885   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
6886     CheckShadow(D, ShadowedDecl, R);
6887 }
6888
6889 /// Check if 'E', which is an expression that is about to be modified, refers
6890 /// to a constructor parameter that shadows a field.
6891 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6892   // Quickly ignore expressions that can't be shadowing ctor parameters.
6893   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6894     return;
6895   E = E->IgnoreParenImpCasts();
6896   auto *DRE = dyn_cast<DeclRefExpr>(E);
6897   if (!DRE)
6898     return;
6899   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6900   auto I = ShadowingDecls.find(D);
6901   if (I == ShadowingDecls.end())
6902     return;
6903   const NamedDecl *ShadowedDecl = I->second;
6904   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6905   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6906   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6907   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6908
6909   // Avoid issuing multiple warnings about the same decl.
6910   ShadowingDecls.erase(I);
6911 }
6912
6913 /// Check for conflict between this global or extern "C" declaration and
6914 /// previous global or extern "C" declarations. This is only used in C++.
6915 template<typename T>
6916 static bool checkGlobalOrExternCConflict(
6917     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6918   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6919   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6920
6921   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6922     // The common case: this global doesn't conflict with any extern "C"
6923     // declaration.
6924     return false;
6925   }
6926
6927   if (Prev) {
6928     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6929       // Both the old and new declarations have C language linkage. This is a
6930       // redeclaration.
6931       Previous.clear();
6932       Previous.addDecl(Prev);
6933       return true;
6934     }
6935
6936     // This is a global, non-extern "C" declaration, and there is a previous
6937     // non-global extern "C" declaration. Diagnose if this is a variable
6938     // declaration.
6939     if (!isa<VarDecl>(ND))
6940       return false;
6941   } else {
6942     // The declaration is extern "C". Check for any declaration in the
6943     // translation unit which might conflict.
6944     if (IsGlobal) {
6945       // We have already performed the lookup into the translation unit.
6946       IsGlobal = false;
6947       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6948            I != E; ++I) {
6949         if (isa<VarDecl>(*I)) {
6950           Prev = *I;
6951           break;
6952         }
6953       }
6954     } else {
6955       DeclContext::lookup_result R =
6956           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6957       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6958            I != E; ++I) {
6959         if (isa<VarDecl>(*I)) {
6960           Prev = *I;
6961           break;
6962         }
6963         // FIXME: If we have any other entity with this name in global scope,
6964         // the declaration is ill-formed, but that is a defect: it breaks the
6965         // 'stat' hack, for instance. Only variables can have mangled name
6966         // clashes with extern "C" declarations, so only they deserve a
6967         // diagnostic.
6968       }
6969     }
6970
6971     if (!Prev)
6972       return false;
6973   }
6974
6975   // Use the first declaration's location to ensure we point at something which
6976   // is lexically inside an extern "C" linkage-spec.
6977   assert(Prev && "should have found a previous declaration to diagnose");
6978   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6979     Prev = FD->getFirstDecl();
6980   else
6981     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6982
6983   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6984     << IsGlobal << ND;
6985   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6986     << IsGlobal;
6987   return false;
6988 }
6989
6990 /// Apply special rules for handling extern "C" declarations. Returns \c true
6991 /// if we have found that this is a redeclaration of some prior entity.
6992 ///
6993 /// Per C++ [dcl.link]p6:
6994 ///   Two declarations [for a function or variable] with C language linkage
6995 ///   with the same name that appear in different scopes refer to the same
6996 ///   [entity]. An entity with C language linkage shall not be declared with
6997 ///   the same name as an entity in global scope.
6998 template<typename T>
6999 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7000                                                   LookupResult &Previous) {
7001   if (!S.getLangOpts().CPlusPlus) {
7002     // In C, when declaring a global variable, look for a corresponding 'extern'
7003     // variable declared in function scope. We don't need this in C++, because
7004     // we find local extern decls in the surrounding file-scope DeclContext.
7005     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7006       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7007         Previous.clear();
7008         Previous.addDecl(Prev);
7009         return true;
7010       }
7011     }
7012     return false;
7013   }
7014
7015   // A declaration in the translation unit can conflict with an extern "C"
7016   // declaration.
7017   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7018     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7019
7020   // An extern "C" declaration can conflict with a declaration in the
7021   // translation unit or can be a redeclaration of an extern "C" declaration
7022   // in another scope.
7023   if (isIncompleteDeclExternC(S,ND))
7024     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7025
7026   // Neither global nor extern "C": nothing to do.
7027   return false;
7028 }
7029
7030 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7031   // If the decl is already known invalid, don't check it.
7032   if (NewVD->isInvalidDecl())
7033     return;
7034
7035   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7036   QualType T = TInfo->getType();
7037
7038   // Defer checking an 'auto' type until its initializer is attached.
7039   if (T->isUndeducedType())
7040     return;
7041
7042   if (NewVD->hasAttrs())
7043     CheckAlignasUnderalignment(NewVD);
7044
7045   if (T->isObjCObjectType()) {
7046     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7047       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7048     T = Context.getObjCObjectPointerType(T);
7049     NewVD->setType(T);
7050   }
7051
7052   // Emit an error if an address space was applied to decl with local storage.
7053   // This includes arrays of objects with address space qualifiers, but not
7054   // automatic variables that point to other address spaces.
7055   // ISO/IEC TR 18037 S5.1.2
7056   if (!getLangOpts().OpenCL
7057       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7058     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
7059     NewVD->setInvalidDecl();
7060     return;
7061   }
7062
7063   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7064   // scope.
7065   if (getLangOpts().OpenCLVersion == 120 &&
7066       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7067       NewVD->isStaticLocal()) {
7068     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7069     NewVD->setInvalidDecl();
7070     return;
7071   }
7072
7073   if (getLangOpts().OpenCL) {
7074     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7075     if (NewVD->hasAttr<BlocksAttr>()) {
7076       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7077       return;
7078     }
7079
7080     if (T->isBlockPointerType()) {
7081       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7082       // can't use 'extern' storage class.
7083       if (!T.isConstQualified()) {
7084         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7085             << 0 /*const*/;
7086         NewVD->setInvalidDecl();
7087         return;
7088       }
7089       if (NewVD->hasExternalStorage()) {
7090         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7091         NewVD->setInvalidDecl();
7092         return;
7093       }
7094     }
7095     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7096     // __constant address space.
7097     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7098     // variables inside a function can also be declared in the global
7099     // address space.
7100     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7101         NewVD->hasExternalStorage()) {
7102       if (!T->isSamplerT() &&
7103           !(T.getAddressSpace() == LangAS::opencl_constant ||
7104             (T.getAddressSpace() == LangAS::opencl_global &&
7105              getLangOpts().OpenCLVersion == 200))) {
7106         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7107         if (getLangOpts().OpenCLVersion == 200)
7108           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7109               << Scope << "global or constant";
7110         else
7111           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7112               << Scope << "constant";
7113         NewVD->setInvalidDecl();
7114         return;
7115       }
7116     } else {
7117       if (T.getAddressSpace() == LangAS::opencl_global) {
7118         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7119             << 1 /*is any function*/ << "global";
7120         NewVD->setInvalidDecl();
7121         return;
7122       }
7123       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
7124       // in functions.
7125       if (T.getAddressSpace() == LangAS::opencl_constant ||
7126           T.getAddressSpace() == LangAS::opencl_local) {
7127         FunctionDecl *FD = getCurFunctionDecl();
7128         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7129           if (T.getAddressSpace() == LangAS::opencl_constant)
7130             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7131                 << 0 /*non-kernel only*/ << "constant";
7132           else
7133             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7134                 << 0 /*non-kernel only*/ << "local";
7135           NewVD->setInvalidDecl();
7136           return;
7137         }
7138       }
7139     }
7140   }
7141
7142   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7143       && !NewVD->hasAttr<BlocksAttr>()) {
7144     if (getLangOpts().getGC() != LangOptions::NonGC)
7145       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7146     else {
7147       assert(!getLangOpts().ObjCAutoRefCount);
7148       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7149     }
7150   }
7151
7152   bool isVM = T->isVariablyModifiedType();
7153   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7154       NewVD->hasAttr<BlocksAttr>())
7155     getCurFunction()->setHasBranchProtectedScope();
7156
7157   if ((isVM && NewVD->hasLinkage()) ||
7158       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7159     bool SizeIsNegative;
7160     llvm::APSInt Oversized;
7161     TypeSourceInfo *FixedTInfo =
7162       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7163                                                     SizeIsNegative, Oversized);
7164     if (!FixedTInfo && T->isVariableArrayType()) {
7165       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7166       // FIXME: This won't give the correct result for
7167       // int a[10][n];
7168       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7169
7170       if (NewVD->isFileVarDecl())
7171         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7172         << SizeRange;
7173       else if (NewVD->isStaticLocal())
7174         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7175         << SizeRange;
7176       else
7177         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7178         << SizeRange;
7179       NewVD->setInvalidDecl();
7180       return;
7181     }
7182
7183     if (!FixedTInfo) {
7184       if (NewVD->isFileVarDecl())
7185         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7186       else
7187         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7188       NewVD->setInvalidDecl();
7189       return;
7190     }
7191
7192     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7193     NewVD->setType(FixedTInfo->getType());
7194     NewVD->setTypeSourceInfo(FixedTInfo);
7195   }
7196
7197   if (T->isVoidType()) {
7198     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7199     //                    of objects and functions.
7200     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7201       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7202         << T;
7203       NewVD->setInvalidDecl();
7204       return;
7205     }
7206   }
7207
7208   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7209     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7210     NewVD->setInvalidDecl();
7211     return;
7212   }
7213
7214   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7215     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7216     NewVD->setInvalidDecl();
7217     return;
7218   }
7219
7220   if (NewVD->isConstexpr() && !T->isDependentType() &&
7221       RequireLiteralType(NewVD->getLocation(), T,
7222                          diag::err_constexpr_var_non_literal)) {
7223     NewVD->setInvalidDecl();
7224     return;
7225   }
7226 }
7227
7228 /// \brief Perform semantic checking on a newly-created variable
7229 /// declaration.
7230 ///
7231 /// This routine performs all of the type-checking required for a
7232 /// variable declaration once it has been built. It is used both to
7233 /// check variables after they have been parsed and their declarators
7234 /// have been translated into a declaration, and to check variables
7235 /// that have been instantiated from a template.
7236 ///
7237 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7238 ///
7239 /// Returns true if the variable declaration is a redeclaration.
7240 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7241   CheckVariableDeclarationType(NewVD);
7242
7243   // If the decl is already known invalid, don't check it.
7244   if (NewVD->isInvalidDecl())
7245     return false;
7246
7247   // If we did not find anything by this name, look for a non-visible
7248   // extern "C" declaration with the same name.
7249   if (Previous.empty() &&
7250       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7251     Previous.setShadowed();
7252
7253   if (!Previous.empty()) {
7254     MergeVarDecl(NewVD, Previous);
7255     return true;
7256   }
7257   return false;
7258 }
7259
7260 namespace {
7261 struct FindOverriddenMethod {
7262   Sema *S;
7263   CXXMethodDecl *Method;
7264
7265   /// Member lookup function that determines whether a given C++
7266   /// method overrides a method in a base class, to be used with
7267   /// CXXRecordDecl::lookupInBases().
7268   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7269     RecordDecl *BaseRecord =
7270         Specifier->getType()->getAs<RecordType>()->getDecl();
7271
7272     DeclarationName Name = Method->getDeclName();
7273
7274     // FIXME: Do we care about other names here too?
7275     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7276       // We really want to find the base class destructor here.
7277       QualType T = S->Context.getTypeDeclType(BaseRecord);
7278       CanQualType CT = S->Context.getCanonicalType(T);
7279
7280       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7281     }
7282
7283     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7284          Path.Decls = Path.Decls.slice(1)) {
7285       NamedDecl *D = Path.Decls.front();
7286       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7287         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7288           return true;
7289       }
7290     }
7291
7292     return false;
7293   }
7294 };
7295
7296 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7297 } // end anonymous namespace
7298
7299 /// \brief Report an error regarding overriding, along with any relevant
7300 /// overriden methods.
7301 ///
7302 /// \param DiagID the primary error to report.
7303 /// \param MD the overriding method.
7304 /// \param OEK which overrides to include as notes.
7305 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7306                             OverrideErrorKind OEK = OEK_All) {
7307   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7308   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7309                                       E = MD->end_overridden_methods();
7310        I != E; ++I) {
7311     // This check (& the OEK parameter) could be replaced by a predicate, but
7312     // without lambdas that would be overkill. This is still nicer than writing
7313     // out the diag loop 3 times.
7314     if ((OEK == OEK_All) ||
7315         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7316         (OEK == OEK_Deleted && (*I)->isDeleted()))
7317       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7318   }
7319 }
7320
7321 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7322 /// and if so, check that it's a valid override and remember it.
7323 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7324   // Look for methods in base classes that this method might override.
7325   CXXBasePaths Paths;
7326   FindOverriddenMethod FOM;
7327   FOM.Method = MD;
7328   FOM.S = this;
7329   bool hasDeletedOverridenMethods = false;
7330   bool hasNonDeletedOverridenMethods = false;
7331   bool AddedAny = false;
7332   if (DC->lookupInBases(FOM, Paths)) {
7333     for (auto *I : Paths.found_decls()) {
7334       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7335         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7336         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7337             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7338             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7339             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7340           hasDeletedOverridenMethods |= OldMD->isDeleted();
7341           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7342           AddedAny = true;
7343         }
7344       }
7345     }
7346   }
7347
7348   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7349     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7350   }
7351   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7352     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7353   }
7354
7355   return AddedAny;
7356 }
7357
7358 namespace {
7359   // Struct for holding all of the extra arguments needed by
7360   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7361   struct ActOnFDArgs {
7362     Scope *S;
7363     Declarator &D;
7364     MultiTemplateParamsArg TemplateParamLists;
7365     bool AddToScope;
7366   };
7367 } // end anonymous namespace
7368
7369 namespace {
7370
7371 // Callback to only accept typo corrections that have a non-zero edit distance.
7372 // Also only accept corrections that have the same parent decl.
7373 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7374  public:
7375   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7376                             CXXRecordDecl *Parent)
7377       : Context(Context), OriginalFD(TypoFD),
7378         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7379
7380   bool ValidateCandidate(const TypoCorrection &candidate) override {
7381     if (candidate.getEditDistance() == 0)
7382       return false;
7383
7384     SmallVector<unsigned, 1> MismatchedParams;
7385     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7386                                           CDeclEnd = candidate.end();
7387          CDecl != CDeclEnd; ++CDecl) {
7388       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7389
7390       if (FD && !FD->hasBody() &&
7391           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7392         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7393           CXXRecordDecl *Parent = MD->getParent();
7394           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7395             return true;
7396         } else if (!ExpectedParent) {
7397           return true;
7398         }
7399       }
7400     }
7401
7402     return false;
7403   }
7404
7405  private:
7406   ASTContext &Context;
7407   FunctionDecl *OriginalFD;
7408   CXXRecordDecl *ExpectedParent;
7409 };
7410
7411 } // end anonymous namespace
7412
7413 /// \brief Generate diagnostics for an invalid function redeclaration.
7414 ///
7415 /// This routine handles generating the diagnostic messages for an invalid
7416 /// function redeclaration, including finding possible similar declarations
7417 /// or performing typo correction if there are no previous declarations with
7418 /// the same name.
7419 ///
7420 /// Returns a NamedDecl iff typo correction was performed and substituting in
7421 /// the new declaration name does not cause new errors.
7422 static NamedDecl *DiagnoseInvalidRedeclaration(
7423     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7424     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7425   DeclarationName Name = NewFD->getDeclName();
7426   DeclContext *NewDC = NewFD->getDeclContext();
7427   SmallVector<unsigned, 1> MismatchedParams;
7428   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7429   TypoCorrection Correction;
7430   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7431   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7432                                    : diag::err_member_decl_does_not_match;
7433   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7434                     IsLocalFriend ? Sema::LookupLocalFriendName
7435                                   : Sema::LookupOrdinaryName,
7436                     Sema::ForRedeclaration);
7437
7438   NewFD->setInvalidDecl();
7439   if (IsLocalFriend)
7440     SemaRef.LookupName(Prev, S);
7441   else
7442     SemaRef.LookupQualifiedName(Prev, NewDC);
7443   assert(!Prev.isAmbiguous() &&
7444          "Cannot have an ambiguity in previous-declaration lookup");
7445   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7446   if (!Prev.empty()) {
7447     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7448          Func != FuncEnd; ++Func) {
7449       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7450       if (FD &&
7451           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7452         // Add 1 to the index so that 0 can mean the mismatch didn't
7453         // involve a parameter
7454         unsigned ParamNum =
7455             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7456         NearMatches.push_back(std::make_pair(FD, ParamNum));
7457       }
7458     }
7459   // If the qualified name lookup yielded nothing, try typo correction
7460   } else if ((Correction = SemaRef.CorrectTypo(
7461                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7462                   &ExtraArgs.D.getCXXScopeSpec(),
7463                   llvm::make_unique<DifferentNameValidatorCCC>(
7464                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7465                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7466     // Set up everything for the call to ActOnFunctionDeclarator
7467     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7468                               ExtraArgs.D.getIdentifierLoc());
7469     Previous.clear();
7470     Previous.setLookupName(Correction.getCorrection());
7471     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7472                                     CDeclEnd = Correction.end();
7473          CDecl != CDeclEnd; ++CDecl) {
7474       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7475       if (FD && !FD->hasBody() &&
7476           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7477         Previous.addDecl(FD);
7478       }
7479     }
7480     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7481
7482     NamedDecl *Result;
7483     // Retry building the function declaration with the new previous
7484     // declarations, and with errors suppressed.
7485     {
7486       // Trap errors.
7487       Sema::SFINAETrap Trap(SemaRef);
7488
7489       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7490       // pieces need to verify the typo-corrected C++ declaration and hopefully
7491       // eliminate the need for the parameter pack ExtraArgs.
7492       Result = SemaRef.ActOnFunctionDeclarator(
7493           ExtraArgs.S, ExtraArgs.D,
7494           Correction.getCorrectionDecl()->getDeclContext(),
7495           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7496           ExtraArgs.AddToScope);
7497
7498       if (Trap.hasErrorOccurred())
7499         Result = nullptr;
7500     }
7501
7502     if (Result) {
7503       // Determine which correction we picked.
7504       Decl *Canonical = Result->getCanonicalDecl();
7505       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7506            I != E; ++I)
7507         if ((*I)->getCanonicalDecl() == Canonical)
7508           Correction.setCorrectionDecl(*I);
7509
7510       SemaRef.diagnoseTypo(
7511           Correction,
7512           SemaRef.PDiag(IsLocalFriend
7513                           ? diag::err_no_matching_local_friend_suggest
7514                           : diag::err_member_decl_does_not_match_suggest)
7515             << Name << NewDC << IsDefinition);
7516       return Result;
7517     }
7518
7519     // Pretend the typo correction never occurred
7520     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7521                               ExtraArgs.D.getIdentifierLoc());
7522     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7523     Previous.clear();
7524     Previous.setLookupName(Name);
7525   }
7526
7527   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7528       << Name << NewDC << IsDefinition << NewFD->getLocation();
7529
7530   bool NewFDisConst = false;
7531   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7532     NewFDisConst = NewMD->isConst();
7533
7534   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7535        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7536        NearMatch != NearMatchEnd; ++NearMatch) {
7537     FunctionDecl *FD = NearMatch->first;
7538     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7539     bool FDisConst = MD && MD->isConst();
7540     bool IsMember = MD || !IsLocalFriend;
7541
7542     // FIXME: These notes are poorly worded for the local friend case.
7543     if (unsigned Idx = NearMatch->second) {
7544       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7545       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7546       if (Loc.isInvalid()) Loc = FD->getLocation();
7547       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7548                                  : diag::note_local_decl_close_param_match)
7549         << Idx << FDParam->getType()
7550         << NewFD->getParamDecl(Idx - 1)->getType();
7551     } else if (FDisConst != NewFDisConst) {
7552       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7553           << NewFDisConst << FD->getSourceRange().getEnd();
7554     } else
7555       SemaRef.Diag(FD->getLocation(),
7556                    IsMember ? diag::note_member_def_close_match
7557                             : diag::note_local_decl_close_match);
7558   }
7559   return nullptr;
7560 }
7561
7562 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7563   switch (D.getDeclSpec().getStorageClassSpec()) {
7564   default: llvm_unreachable("Unknown storage class!");
7565   case DeclSpec::SCS_auto:
7566   case DeclSpec::SCS_register:
7567   case DeclSpec::SCS_mutable:
7568     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7569                  diag::err_typecheck_sclass_func);
7570     D.getMutableDeclSpec().ClearStorageClassSpecs();
7571     D.setInvalidType();
7572     break;
7573   case DeclSpec::SCS_unspecified: break;
7574   case DeclSpec::SCS_extern:
7575     if (D.getDeclSpec().isExternInLinkageSpec())
7576       return SC_None;
7577     return SC_Extern;
7578   case DeclSpec::SCS_static: {
7579     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7580       // C99 6.7.1p5:
7581       //   The declaration of an identifier for a function that has
7582       //   block scope shall have no explicit storage-class specifier
7583       //   other than extern
7584       // See also (C++ [dcl.stc]p4).
7585       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7586                    diag::err_static_block_func);
7587       break;
7588     } else
7589       return SC_Static;
7590   }
7591   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7592   }
7593
7594   // No explicit storage class has already been returned
7595   return SC_None;
7596 }
7597
7598 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7599                                            DeclContext *DC, QualType &R,
7600                                            TypeSourceInfo *TInfo,
7601                                            StorageClass SC,
7602                                            bool &IsVirtualOkay) {
7603   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7604   DeclarationName Name = NameInfo.getName();
7605
7606   FunctionDecl *NewFD = nullptr;
7607   bool isInline = D.getDeclSpec().isInlineSpecified();
7608
7609   if (!SemaRef.getLangOpts().CPlusPlus) {
7610     // Determine whether the function was written with a
7611     // prototype. This true when:
7612     //   - there is a prototype in the declarator, or
7613     //   - the type R of the function is some kind of typedef or other non-
7614     //     attributed reference to a type name (which eventually refers to a
7615     //     function type).
7616     bool HasPrototype =
7617       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7618       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7619
7620     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7621                                  D.getLocStart(), NameInfo, R,
7622                                  TInfo, SC, isInline,
7623                                  HasPrototype, false);
7624     if (D.isInvalidType())
7625       NewFD->setInvalidDecl();
7626
7627     return NewFD;
7628   }
7629
7630   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7631   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7632
7633   // Check that the return type is not an abstract class type.
7634   // For record types, this is done by the AbstractClassUsageDiagnoser once
7635   // the class has been completely parsed.
7636   if (!DC->isRecord() &&
7637       SemaRef.RequireNonAbstractType(
7638           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7639           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7640     D.setInvalidType();
7641
7642   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7643     // This is a C++ constructor declaration.
7644     assert(DC->isRecord() &&
7645            "Constructors can only be declared in a member context");
7646
7647     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7648     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7649                                       D.getLocStart(), NameInfo,
7650                                       R, TInfo, isExplicit, isInline,
7651                                       /*isImplicitlyDeclared=*/false,
7652                                       isConstexpr);
7653
7654   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7655     // This is a C++ destructor declaration.
7656     if (DC->isRecord()) {
7657       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7658       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7659       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7660                                         SemaRef.Context, Record,
7661                                         D.getLocStart(),
7662                                         NameInfo, R, TInfo, isInline,
7663                                         /*isImplicitlyDeclared=*/false);
7664
7665       // If the class is complete, then we now create the implicit exception
7666       // specification. If the class is incomplete or dependent, we can't do
7667       // it yet.
7668       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7669           Record->getDefinition() && !Record->isBeingDefined() &&
7670           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7671         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7672       }
7673
7674       IsVirtualOkay = true;
7675       return NewDD;
7676
7677     } else {
7678       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7679       D.setInvalidType();
7680
7681       // Create a FunctionDecl to satisfy the function definition parsing
7682       // code path.
7683       return FunctionDecl::Create(SemaRef.Context, DC,
7684                                   D.getLocStart(),
7685                                   D.getIdentifierLoc(), Name, R, TInfo,
7686                                   SC, isInline,
7687                                   /*hasPrototype=*/true, isConstexpr);
7688     }
7689
7690   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7691     if (!DC->isRecord()) {
7692       SemaRef.Diag(D.getIdentifierLoc(),
7693            diag::err_conv_function_not_member);
7694       return nullptr;
7695     }
7696
7697     SemaRef.CheckConversionDeclarator(D, R, SC);
7698     IsVirtualOkay = true;
7699     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7700                                      D.getLocStart(), NameInfo,
7701                                      R, TInfo, isInline, isExplicit,
7702                                      isConstexpr, SourceLocation());
7703
7704   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7705     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7706
7707     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7708                                          isExplicit, NameInfo, R, TInfo,
7709                                          D.getLocEnd());
7710   } else if (DC->isRecord()) {
7711     // If the name of the function is the same as the name of the record,
7712     // then this must be an invalid constructor that has a return type.
7713     // (The parser checks for a return type and makes the declarator a
7714     // constructor if it has no return type).
7715     if (Name.getAsIdentifierInfo() &&
7716         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7717       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7718         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7719         << SourceRange(D.getIdentifierLoc());
7720       return nullptr;
7721     }
7722
7723     // This is a C++ method declaration.
7724     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7725                                                cast<CXXRecordDecl>(DC),
7726                                                D.getLocStart(), NameInfo, R,
7727                                                TInfo, SC, isInline,
7728                                                isConstexpr, SourceLocation());
7729     IsVirtualOkay = !Ret->isStatic();
7730     return Ret;
7731   } else {
7732     bool isFriend =
7733         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7734     if (!isFriend && SemaRef.CurContext->isRecord())
7735       return nullptr;
7736
7737     // Determine whether the function was written with a
7738     // prototype. This true when:
7739     //   - we're in C++ (where every function has a prototype),
7740     return FunctionDecl::Create(SemaRef.Context, DC,
7741                                 D.getLocStart(),
7742                                 NameInfo, R, TInfo, SC, isInline,
7743                                 true/*HasPrototype*/, isConstexpr);
7744   }
7745 }
7746
7747 enum OpenCLParamType {
7748   ValidKernelParam,
7749   PtrPtrKernelParam,
7750   PtrKernelParam,
7751   InvalidAddrSpacePtrKernelParam,
7752   InvalidKernelParam,
7753   RecordKernelParam
7754 };
7755
7756 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7757   if (PT->isPointerType()) {
7758     QualType PointeeType = PT->getPointeeType();
7759     if (PointeeType->isPointerType())
7760       return PtrPtrKernelParam;
7761     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7762         PointeeType.getAddressSpace() == 0)
7763       return InvalidAddrSpacePtrKernelParam;
7764     return PtrKernelParam;
7765   }
7766
7767   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7768   // be used as builtin types.
7769
7770   if (PT->isImageType())
7771     return PtrKernelParam;
7772
7773   if (PT->isBooleanType())
7774     return InvalidKernelParam;
7775
7776   if (PT->isEventT())
7777     return InvalidKernelParam;
7778
7779   // OpenCL extension spec v1.2 s9.5:
7780   // This extension adds support for half scalar and vector types as built-in
7781   // types that can be used for arithmetic operations, conversions etc.
7782   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7783     return InvalidKernelParam;
7784
7785   if (PT->isRecordType())
7786     return RecordKernelParam;
7787
7788   return ValidKernelParam;
7789 }
7790
7791 static void checkIsValidOpenCLKernelParameter(
7792   Sema &S,
7793   Declarator &D,
7794   ParmVarDecl *Param,
7795   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7796   QualType PT = Param->getType();
7797
7798   // Cache the valid types we encounter to avoid rechecking structs that are
7799   // used again
7800   if (ValidTypes.count(PT.getTypePtr()))
7801     return;
7802
7803   switch (getOpenCLKernelParameterType(S, PT)) {
7804   case PtrPtrKernelParam:
7805     // OpenCL v1.2 s6.9.a:
7806     // A kernel function argument cannot be declared as a
7807     // pointer to a pointer type.
7808     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7809     D.setInvalidType();
7810     return;
7811
7812   case InvalidAddrSpacePtrKernelParam:
7813     // OpenCL v1.0 s6.5:
7814     // __kernel function arguments declared to be a pointer of a type can point
7815     // to one of the following address spaces only : __global, __local or
7816     // __constant.
7817     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
7818     D.setInvalidType();
7819     return;
7820
7821     // OpenCL v1.2 s6.9.k:
7822     // Arguments to kernel functions in a program cannot be declared with the
7823     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7824     // uintptr_t or a struct and/or union that contain fields declared to be
7825     // one of these built-in scalar types.
7826
7827   case InvalidKernelParam:
7828     // OpenCL v1.2 s6.8 n:
7829     // A kernel function argument cannot be declared
7830     // of event_t type.
7831     // Do not diagnose half type since it is diagnosed as invalid argument
7832     // type for any function elsewhere.
7833     if (!PT->isHalfType())
7834       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7835     D.setInvalidType();
7836     return;
7837
7838   case PtrKernelParam:
7839   case ValidKernelParam:
7840     ValidTypes.insert(PT.getTypePtr());
7841     return;
7842
7843   case RecordKernelParam:
7844     break;
7845   }
7846
7847   // Track nested structs we will inspect
7848   SmallVector<const Decl *, 4> VisitStack;
7849
7850   // Track where we are in the nested structs. Items will migrate from
7851   // VisitStack to HistoryStack as we do the DFS for bad field.
7852   SmallVector<const FieldDecl *, 4> HistoryStack;
7853   HistoryStack.push_back(nullptr);
7854
7855   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7856   VisitStack.push_back(PD);
7857
7858   assert(VisitStack.back() && "First decl null?");
7859
7860   do {
7861     const Decl *Next = VisitStack.pop_back_val();
7862     if (!Next) {
7863       assert(!HistoryStack.empty());
7864       // Found a marker, we have gone up a level
7865       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7866         ValidTypes.insert(Hist->getType().getTypePtr());
7867
7868       continue;
7869     }
7870
7871     // Adds everything except the original parameter declaration (which is not a
7872     // field itself) to the history stack.
7873     const RecordDecl *RD;
7874     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7875       HistoryStack.push_back(Field);
7876       RD = Field->getType()->castAs<RecordType>()->getDecl();
7877     } else {
7878       RD = cast<RecordDecl>(Next);
7879     }
7880
7881     // Add a null marker so we know when we've gone back up a level
7882     VisitStack.push_back(nullptr);
7883
7884     for (const auto *FD : RD->fields()) {
7885       QualType QT = FD->getType();
7886
7887       if (ValidTypes.count(QT.getTypePtr()))
7888         continue;
7889
7890       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
7891       if (ParamType == ValidKernelParam)
7892         continue;
7893
7894       if (ParamType == RecordKernelParam) {
7895         VisitStack.push_back(FD);
7896         continue;
7897       }
7898
7899       // OpenCL v1.2 s6.9.p:
7900       // Arguments to kernel functions that are declared to be a struct or union
7901       // do not allow OpenCL objects to be passed as elements of the struct or
7902       // union.
7903       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7904           ParamType == InvalidAddrSpacePtrKernelParam) {
7905         S.Diag(Param->getLocation(),
7906                diag::err_record_with_pointers_kernel_param)
7907           << PT->isUnionType()
7908           << PT;
7909       } else {
7910         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7911       }
7912
7913       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7914         << PD->getDeclName();
7915
7916       // We have an error, now let's go back up through history and show where
7917       // the offending field came from
7918       for (ArrayRef<const FieldDecl *>::const_iterator
7919                I = HistoryStack.begin() + 1,
7920                E = HistoryStack.end();
7921            I != E; ++I) {
7922         const FieldDecl *OuterField = *I;
7923         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7924           << OuterField->getType();
7925       }
7926
7927       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7928         << QT->isPointerType()
7929         << QT;
7930       D.setInvalidType();
7931       return;
7932     }
7933   } while (!VisitStack.empty());
7934 }
7935
7936 /// Find the DeclContext in which a tag is implicitly declared if we see an
7937 /// elaborated type specifier in the specified context, and lookup finds
7938 /// nothing.
7939 static DeclContext *getTagInjectionContext(DeclContext *DC) {
7940   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
7941     DC = DC->getParent();
7942   return DC;
7943 }
7944
7945 /// Find the Scope in which a tag is implicitly declared if we see an
7946 /// elaborated type specifier in the specified context, and lookup finds
7947 /// nothing.
7948 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
7949   while (S->isClassScope() ||
7950          (LangOpts.CPlusPlus &&
7951           S->isFunctionPrototypeScope()) ||
7952          ((S->getFlags() & Scope::DeclScope) == 0) ||
7953          (S->getEntity() && S->getEntity()->isTransparentContext()))
7954     S = S->getParent();
7955   return S;
7956 }
7957
7958 NamedDecl*
7959 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7960                               TypeSourceInfo *TInfo, LookupResult &Previous,
7961                               MultiTemplateParamsArg TemplateParamLists,
7962                               bool &AddToScope) {
7963   QualType R = TInfo->getType();
7964
7965   assert(R.getTypePtr()->isFunctionType());
7966
7967   // TODO: consider using NameInfo for diagnostic.
7968   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7969   DeclarationName Name = NameInfo.getName();
7970   StorageClass SC = getFunctionStorageClass(*this, D);
7971
7972   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7973     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7974          diag::err_invalid_thread)
7975       << DeclSpec::getSpecifierName(TSCS);
7976
7977   if (D.isFirstDeclarationOfMember())
7978     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7979                            D.getIdentifierLoc());
7980
7981   bool isFriend = false;
7982   FunctionTemplateDecl *FunctionTemplate = nullptr;
7983   bool isMemberSpecialization = false;
7984   bool isFunctionTemplateSpecialization = false;
7985
7986   bool isDependentClassScopeExplicitSpecialization = false;
7987   bool HasExplicitTemplateArgs = false;
7988   TemplateArgumentListInfo TemplateArgs;
7989
7990   bool isVirtualOkay = false;
7991
7992   DeclContext *OriginalDC = DC;
7993   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7994
7995   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7996                                               isVirtualOkay);
7997   if (!NewFD) return nullptr;
7998
7999   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8000     NewFD->setTopLevelDeclInObjCContainer();
8001
8002   // Set the lexical context. If this is a function-scope declaration, or has a
8003   // C++ scope specifier, or is the object of a friend declaration, the lexical
8004   // context will be different from the semantic context.
8005   NewFD->setLexicalDeclContext(CurContext);
8006
8007   if (IsLocalExternDecl)
8008     NewFD->setLocalExternDecl();
8009
8010   if (getLangOpts().CPlusPlus) {
8011     bool isInline = D.getDeclSpec().isInlineSpecified();
8012     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8013     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8014     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8015     bool isConcept = D.getDeclSpec().isConceptSpecified();
8016     isFriend = D.getDeclSpec().isFriendSpecified();
8017     if (isFriend && !isInline && D.isFunctionDefinition()) {
8018       // C++ [class.friend]p5
8019       //   A function can be defined in a friend declaration of a
8020       //   class . . . . Such a function is implicitly inline.
8021       NewFD->setImplicitlyInline();
8022     }
8023
8024     // If this is a method defined in an __interface, and is not a constructor
8025     // or an overloaded operator, then set the pure flag (isVirtual will already
8026     // return true).
8027     if (const CXXRecordDecl *Parent =
8028           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8029       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8030         NewFD->setPure(true);
8031
8032       // C++ [class.union]p2
8033       //   A union can have member functions, but not virtual functions.
8034       if (isVirtual && Parent->isUnion())
8035         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8036     }
8037
8038     SetNestedNameSpecifier(NewFD, D);
8039     isMemberSpecialization = false;
8040     isFunctionTemplateSpecialization = false;
8041     if (D.isInvalidType())
8042       NewFD->setInvalidDecl();
8043
8044     // Match up the template parameter lists with the scope specifier, then
8045     // determine whether we have a template or a template specialization.
8046     bool Invalid = false;
8047     if (TemplateParameterList *TemplateParams =
8048             MatchTemplateParametersToScopeSpecifier(
8049                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8050                 D.getCXXScopeSpec(),
8051                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8052                     ? D.getName().TemplateId
8053                     : nullptr,
8054                 TemplateParamLists, isFriend, isMemberSpecialization,
8055                 Invalid)) {
8056       if (TemplateParams->size() > 0) {
8057         // This is a function template
8058
8059         // Check that we can declare a template here.
8060         if (CheckTemplateDeclScope(S, TemplateParams))
8061           NewFD->setInvalidDecl();
8062
8063         // A destructor cannot be a template.
8064         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8065           Diag(NewFD->getLocation(), diag::err_destructor_template);
8066           NewFD->setInvalidDecl();
8067         }
8068
8069         // If we're adding a template to a dependent context, we may need to
8070         // rebuilding some of the types used within the template parameter list,
8071         // now that we know what the current instantiation is.
8072         if (DC->isDependentContext()) {
8073           ContextRAII SavedContext(*this, DC);
8074           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8075             Invalid = true;
8076         }
8077
8078         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8079                                                         NewFD->getLocation(),
8080                                                         Name, TemplateParams,
8081                                                         NewFD);
8082         FunctionTemplate->setLexicalDeclContext(CurContext);
8083         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8084
8085         // For source fidelity, store the other template param lists.
8086         if (TemplateParamLists.size() > 1) {
8087           NewFD->setTemplateParameterListsInfo(Context,
8088                                                TemplateParamLists.drop_back(1));
8089         }
8090       } else {
8091         // This is a function template specialization.
8092         isFunctionTemplateSpecialization = true;
8093         // For source fidelity, store all the template param lists.
8094         if (TemplateParamLists.size() > 0)
8095           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8096
8097         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8098         if (isFriend) {
8099           // We want to remove the "template<>", found here.
8100           SourceRange RemoveRange = TemplateParams->getSourceRange();
8101
8102           // If we remove the template<> and the name is not a
8103           // template-id, we're actually silently creating a problem:
8104           // the friend declaration will refer to an untemplated decl,
8105           // and clearly the user wants a template specialization.  So
8106           // we need to insert '<>' after the name.
8107           SourceLocation InsertLoc;
8108           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8109             InsertLoc = D.getName().getSourceRange().getEnd();
8110             InsertLoc = getLocForEndOfToken(InsertLoc);
8111           }
8112
8113           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8114             << Name << RemoveRange
8115             << FixItHint::CreateRemoval(RemoveRange)
8116             << FixItHint::CreateInsertion(InsertLoc, "<>");
8117         }
8118       }
8119     }
8120     else {
8121       // All template param lists were matched against the scope specifier:
8122       // this is NOT (an explicit specialization of) a template.
8123       if (TemplateParamLists.size() > 0)
8124         // For source fidelity, store all the template param lists.
8125         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8126     }
8127
8128     if (Invalid) {
8129       NewFD->setInvalidDecl();
8130       if (FunctionTemplate)
8131         FunctionTemplate->setInvalidDecl();
8132     }
8133
8134     // C++ [dcl.fct.spec]p5:
8135     //   The virtual specifier shall only be used in declarations of
8136     //   nonstatic class member functions that appear within a
8137     //   member-specification of a class declaration; see 10.3.
8138     //
8139     if (isVirtual && !NewFD->isInvalidDecl()) {
8140       if (!isVirtualOkay) {
8141         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8142              diag::err_virtual_non_function);
8143       } else if (!CurContext->isRecord()) {
8144         // 'virtual' was specified outside of the class.
8145         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8146              diag::err_virtual_out_of_class)
8147           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8148       } else if (NewFD->getDescribedFunctionTemplate()) {
8149         // C++ [temp.mem]p3:
8150         //  A member function template shall not be virtual.
8151         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8152              diag::err_virtual_member_function_template)
8153           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8154       } else {
8155         // Okay: Add virtual to the method.
8156         NewFD->setVirtualAsWritten(true);
8157       }
8158
8159       if (getLangOpts().CPlusPlus14 &&
8160           NewFD->getReturnType()->isUndeducedType())
8161         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8162     }
8163
8164     if (getLangOpts().CPlusPlus14 &&
8165         (NewFD->isDependentContext() ||
8166          (isFriend && CurContext->isDependentContext())) &&
8167         NewFD->getReturnType()->isUndeducedType()) {
8168       // If the function template is referenced directly (for instance, as a
8169       // member of the current instantiation), pretend it has a dependent type.
8170       // This is not really justified by the standard, but is the only sane
8171       // thing to do.
8172       // FIXME: For a friend function, we have not marked the function as being
8173       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8174       const FunctionProtoType *FPT =
8175           NewFD->getType()->castAs<FunctionProtoType>();
8176       QualType Result =
8177           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8178       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8179                                              FPT->getExtProtoInfo()));
8180     }
8181
8182     // C++ [dcl.fct.spec]p3:
8183     //  The inline specifier shall not appear on a block scope function
8184     //  declaration.
8185     if (isInline && !NewFD->isInvalidDecl()) {
8186       if (CurContext->isFunctionOrMethod()) {
8187         // 'inline' is not allowed on block scope function declaration.
8188         Diag(D.getDeclSpec().getInlineSpecLoc(),
8189              diag::err_inline_declaration_block_scope) << Name
8190           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8191       }
8192     }
8193
8194     // C++ [dcl.fct.spec]p6:
8195     //  The explicit specifier shall be used only in the declaration of a
8196     //  constructor or conversion function within its class definition;
8197     //  see 12.3.1 and 12.3.2.
8198     if (isExplicit && !NewFD->isInvalidDecl() &&
8199         !isa<CXXDeductionGuideDecl>(NewFD)) {
8200       if (!CurContext->isRecord()) {
8201         // 'explicit' was specified outside of the class.
8202         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8203              diag::err_explicit_out_of_class)
8204           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8205       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8206                  !isa<CXXConversionDecl>(NewFD)) {
8207         // 'explicit' was specified on a function that wasn't a constructor
8208         // or conversion function.
8209         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8210              diag::err_explicit_non_ctor_or_conv_function)
8211           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8212       }
8213     }
8214
8215     if (isConstexpr) {
8216       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8217       // are implicitly inline.
8218       NewFD->setImplicitlyInline();
8219
8220       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8221       // be either constructors or to return a literal type. Therefore,
8222       // destructors cannot be declared constexpr.
8223       if (isa<CXXDestructorDecl>(NewFD))
8224         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8225     }
8226
8227     if (isConcept) {
8228       // This is a function concept.
8229       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8230         FTD->setConcept();
8231
8232       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8233       // applied only to the definition of a function template [...]
8234       if (!D.isFunctionDefinition()) {
8235         Diag(D.getDeclSpec().getConceptSpecLoc(),
8236              diag::err_function_concept_not_defined);
8237         NewFD->setInvalidDecl();
8238       }
8239
8240       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8241       // have no exception-specification and is treated as if it were specified
8242       // with noexcept(true) (15.4). [...]
8243       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8244         if (FPT->hasExceptionSpec()) {
8245           SourceRange Range;
8246           if (D.isFunctionDeclarator())
8247             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8248           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8249               << FixItHint::CreateRemoval(Range);
8250           NewFD->setInvalidDecl();
8251         } else {
8252           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8253         }
8254
8255         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8256         // following restrictions:
8257         // - The declared return type shall have the type bool.
8258         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8259           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8260           NewFD->setInvalidDecl();
8261         }
8262
8263         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8264         // following restrictions:
8265         // - The declaration's parameter list shall be equivalent to an empty
8266         //   parameter list.
8267         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8268           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8269       }
8270
8271       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8272       // implicity defined to be a constexpr declaration (implicitly inline)
8273       NewFD->setImplicitlyInline();
8274
8275       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8276       // be declared with the thread_local, inline, friend, or constexpr
8277       // specifiers, [...]
8278       if (isInline) {
8279         Diag(D.getDeclSpec().getInlineSpecLoc(),
8280              diag::err_concept_decl_invalid_specifiers)
8281             << 1 << 1;
8282         NewFD->setInvalidDecl(true);
8283       }
8284
8285       if (isFriend) {
8286         Diag(D.getDeclSpec().getFriendSpecLoc(),
8287              diag::err_concept_decl_invalid_specifiers)
8288             << 1 << 2;
8289         NewFD->setInvalidDecl(true);
8290       }
8291
8292       if (isConstexpr) {
8293         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8294              diag::err_concept_decl_invalid_specifiers)
8295             << 1 << 3;
8296         NewFD->setInvalidDecl(true);
8297       }
8298
8299       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8300       // applied only to the definition of a function template or variable
8301       // template, declared in namespace scope.
8302       if (isFunctionTemplateSpecialization) {
8303         Diag(D.getDeclSpec().getConceptSpecLoc(),
8304              diag::err_concept_specified_specialization) << 1;
8305         NewFD->setInvalidDecl(true);
8306         return NewFD;
8307       }
8308     }
8309
8310     // If __module_private__ was specified, mark the function accordingly.
8311     if (D.getDeclSpec().isModulePrivateSpecified()) {
8312       if (isFunctionTemplateSpecialization) {
8313         SourceLocation ModulePrivateLoc
8314           = D.getDeclSpec().getModulePrivateSpecLoc();
8315         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8316           << 0
8317           << FixItHint::CreateRemoval(ModulePrivateLoc);
8318       } else {
8319         NewFD->setModulePrivate();
8320         if (FunctionTemplate)
8321           FunctionTemplate->setModulePrivate();
8322       }
8323     }
8324
8325     if (isFriend) {
8326       if (FunctionTemplate) {
8327         FunctionTemplate->setObjectOfFriendDecl();
8328         FunctionTemplate->setAccess(AS_public);
8329       }
8330       NewFD->setObjectOfFriendDecl();
8331       NewFD->setAccess(AS_public);
8332     }
8333
8334     // If a function is defined as defaulted or deleted, mark it as such now.
8335     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8336     // definition kind to FDK_Definition.
8337     switch (D.getFunctionDefinitionKind()) {
8338       case FDK_Declaration:
8339       case FDK_Definition:
8340         break;
8341
8342       case FDK_Defaulted:
8343         NewFD->setDefaulted();
8344         break;
8345
8346       case FDK_Deleted:
8347         NewFD->setDeletedAsWritten();
8348         break;
8349     }
8350
8351     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8352         D.isFunctionDefinition()) {
8353       // C++ [class.mfct]p2:
8354       //   A member function may be defined (8.4) in its class definition, in
8355       //   which case it is an inline member function (7.1.2)
8356       NewFD->setImplicitlyInline();
8357     }
8358
8359     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8360         !CurContext->isRecord()) {
8361       // C++ [class.static]p1:
8362       //   A data or function member of a class may be declared static
8363       //   in a class definition, in which case it is a static member of
8364       //   the class.
8365
8366       // Complain about the 'static' specifier if it's on an out-of-line
8367       // member function definition.
8368       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8369            diag::err_static_out_of_line)
8370         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8371     }
8372
8373     // C++11 [except.spec]p15:
8374     //   A deallocation function with no exception-specification is treated
8375     //   as if it were specified with noexcept(true).
8376     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8377     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8378          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8379         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8380       NewFD->setType(Context.getFunctionType(
8381           FPT->getReturnType(), FPT->getParamTypes(),
8382           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8383   }
8384
8385   // Filter out previous declarations that don't match the scope.
8386   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8387                        D.getCXXScopeSpec().isNotEmpty() ||
8388                        isMemberSpecialization ||
8389                        isFunctionTemplateSpecialization);
8390
8391   // Handle GNU asm-label extension (encoded as an attribute).
8392   if (Expr *E = (Expr*) D.getAsmLabel()) {
8393     // The parser guarantees this is a string.
8394     StringLiteral *SE = cast<StringLiteral>(E);
8395     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8396                                                 SE->getString(), 0));
8397   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8398     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8399       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8400     if (I != ExtnameUndeclaredIdentifiers.end()) {
8401       if (isDeclExternC(NewFD)) {
8402         NewFD->addAttr(I->second);
8403         ExtnameUndeclaredIdentifiers.erase(I);
8404       } else
8405         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8406             << /*Variable*/0 << NewFD;
8407     }
8408   }
8409
8410   // Copy the parameter declarations from the declarator D to the function
8411   // declaration NewFD, if they are available.  First scavenge them into Params.
8412   SmallVector<ParmVarDecl*, 16> Params;
8413   unsigned FTIIdx;
8414   if (D.isFunctionDeclarator(FTIIdx)) {
8415     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8416
8417     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8418     // function that takes no arguments, not a function that takes a
8419     // single void argument.
8420     // We let through "const void" here because Sema::GetTypeForDeclarator
8421     // already checks for that case.
8422     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8423       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8424         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8425         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8426         Param->setDeclContext(NewFD);
8427         Params.push_back(Param);
8428
8429         if (Param->isInvalidDecl())
8430           NewFD->setInvalidDecl();
8431       }
8432     }
8433
8434     if (!getLangOpts().CPlusPlus) {
8435       // In C, find all the tag declarations from the prototype and move them
8436       // into the function DeclContext. Remove them from the surrounding tag
8437       // injection context of the function, which is typically but not always
8438       // the TU.
8439       DeclContext *PrototypeTagContext =
8440           getTagInjectionContext(NewFD->getLexicalDeclContext());
8441       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8442         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8443
8444         // We don't want to reparent enumerators. Look at their parent enum
8445         // instead.
8446         if (!TD) {
8447           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8448             TD = cast<EnumDecl>(ECD->getDeclContext());
8449         }
8450         if (!TD)
8451           continue;
8452         DeclContext *TagDC = TD->getLexicalDeclContext();
8453         if (!TagDC->containsDecl(TD))
8454           continue;
8455         TagDC->removeDecl(TD);
8456         TD->setDeclContext(NewFD);
8457         NewFD->addDecl(TD);
8458
8459         // Preserve the lexical DeclContext if it is not the surrounding tag
8460         // injection context of the FD. In this example, the semantic context of
8461         // E will be f and the lexical context will be S, while both the
8462         // semantic and lexical contexts of S will be f:
8463         //   void f(struct S { enum E { a } f; } s);
8464         if (TagDC != PrototypeTagContext)
8465           TD->setLexicalDeclContext(TagDC);
8466       }
8467     }
8468   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8469     // When we're declaring a function with a typedef, typeof, etc as in the
8470     // following example, we'll need to synthesize (unnamed)
8471     // parameters for use in the declaration.
8472     //
8473     // @code
8474     // typedef void fn(int);
8475     // fn f;
8476     // @endcode
8477
8478     // Synthesize a parameter for each argument type.
8479     for (const auto &AI : FT->param_types()) {
8480       ParmVarDecl *Param =
8481           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8482       Param->setScopeInfo(0, Params.size());
8483       Params.push_back(Param);
8484     }
8485   } else {
8486     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8487            "Should not need args for typedef of non-prototype fn");
8488   }
8489
8490   // Finally, we know we have the right number of parameters, install them.
8491   NewFD->setParams(Params);
8492
8493   if (D.getDeclSpec().isNoreturnSpecified())
8494     NewFD->addAttr(
8495         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8496                                        Context, 0));
8497
8498   // Functions returning a variably modified type violate C99 6.7.5.2p2
8499   // because all functions have linkage.
8500   if (!NewFD->isInvalidDecl() &&
8501       NewFD->getReturnType()->isVariablyModifiedType()) {
8502     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8503     NewFD->setInvalidDecl();
8504   }
8505
8506   // Apply an implicit SectionAttr if #pragma code_seg is active.
8507   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8508       !NewFD->hasAttr<SectionAttr>()) {
8509     NewFD->addAttr(
8510         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8511                                     CodeSegStack.CurrentValue->getString(),
8512                                     CodeSegStack.CurrentPragmaLocation));
8513     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8514                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8515                          ASTContext::PSF_Read,
8516                      NewFD))
8517       NewFD->dropAttr<SectionAttr>();
8518   }
8519
8520   // Handle attributes.
8521   ProcessDeclAttributes(S, NewFD, D);
8522
8523   if (getLangOpts().OpenCL) {
8524     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8525     // type declaration will generate a compilation error.
8526     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8527     if (AddressSpace == LangAS::opencl_local ||
8528         AddressSpace == LangAS::opencl_global ||
8529         AddressSpace == LangAS::opencl_constant) {
8530       Diag(NewFD->getLocation(),
8531            diag::err_opencl_return_value_with_address_space);
8532       NewFD->setInvalidDecl();
8533     }
8534   }
8535
8536   if (!getLangOpts().CPlusPlus) {
8537     // Perform semantic checking on the function declaration.
8538     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8539       CheckMain(NewFD, D.getDeclSpec());
8540
8541     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8542       CheckMSVCRTEntryPoint(NewFD);
8543
8544     if (!NewFD->isInvalidDecl())
8545       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8546                                                   isMemberSpecialization));
8547     else if (!Previous.empty())
8548       // Recover gracefully from an invalid redeclaration.
8549       D.setRedeclaration(true);
8550     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8551             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8552            "previous declaration set still overloaded");
8553
8554     // Diagnose no-prototype function declarations with calling conventions that
8555     // don't support variadic calls. Only do this in C and do it after merging
8556     // possibly prototyped redeclarations.
8557     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8558     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8559       CallingConv CC = FT->getExtInfo().getCC();
8560       if (!supportsVariadicCall(CC)) {
8561         // Windows system headers sometimes accidentally use stdcall without
8562         // (void) parameters, so we relax this to a warning.
8563         int DiagID =
8564             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8565         Diag(NewFD->getLocation(), DiagID)
8566             << FunctionType::getNameForCallConv(CC);
8567       }
8568     }
8569   } else {
8570     // C++11 [replacement.functions]p3:
8571     //  The program's definitions shall not be specified as inline.
8572     //
8573     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8574     //
8575     // Suppress the diagnostic if the function is __attribute__((used)), since
8576     // that forces an external definition to be emitted.
8577     if (D.getDeclSpec().isInlineSpecified() &&
8578         NewFD->isReplaceableGlobalAllocationFunction() &&
8579         !NewFD->hasAttr<UsedAttr>())
8580       Diag(D.getDeclSpec().getInlineSpecLoc(),
8581            diag::ext_operator_new_delete_declared_inline)
8582         << NewFD->getDeclName();
8583
8584     // If the declarator is a template-id, translate the parser's template
8585     // argument list into our AST format.
8586     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8587       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8588       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8589       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8590       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8591                                          TemplateId->NumArgs);
8592       translateTemplateArguments(TemplateArgsPtr,
8593                                  TemplateArgs);
8594
8595       HasExplicitTemplateArgs = true;
8596
8597       if (NewFD->isInvalidDecl()) {
8598         HasExplicitTemplateArgs = false;
8599       } else if (FunctionTemplate) {
8600         // Function template with explicit template arguments.
8601         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8602           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8603
8604         HasExplicitTemplateArgs = false;
8605       } else {
8606         assert((isFunctionTemplateSpecialization ||
8607                 D.getDeclSpec().isFriendSpecified()) &&
8608                "should have a 'template<>' for this decl");
8609         // "friend void foo<>(int);" is an implicit specialization decl.
8610         isFunctionTemplateSpecialization = true;
8611       }
8612     } else if (isFriend && isFunctionTemplateSpecialization) {
8613       // This combination is only possible in a recovery case;  the user
8614       // wrote something like:
8615       //   template <> friend void foo(int);
8616       // which we're recovering from as if the user had written:
8617       //   friend void foo<>(int);
8618       // Go ahead and fake up a template id.
8619       HasExplicitTemplateArgs = true;
8620       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8621       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8622     }
8623
8624     // We do not add HD attributes to specializations here because
8625     // they may have different constexpr-ness compared to their
8626     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8627     // may end up with different effective targets. Instead, a
8628     // specialization inherits its target attributes from its template
8629     // in the CheckFunctionTemplateSpecialization() call below.
8630     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8631       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8632
8633     // If it's a friend (and only if it's a friend), it's possible
8634     // that either the specialized function type or the specialized
8635     // template is dependent, and therefore matching will fail.  In
8636     // this case, don't check the specialization yet.
8637     bool InstantiationDependent = false;
8638     if (isFunctionTemplateSpecialization && isFriend &&
8639         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8640          TemplateSpecializationType::anyDependentTemplateArguments(
8641             TemplateArgs,
8642             InstantiationDependent))) {
8643       assert(HasExplicitTemplateArgs &&
8644              "friend function specialization without template args");
8645       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8646                                                        Previous))
8647         NewFD->setInvalidDecl();
8648     } else if (isFunctionTemplateSpecialization) {
8649       if (CurContext->isDependentContext() && CurContext->isRecord()
8650           && !isFriend) {
8651         isDependentClassScopeExplicitSpecialization = true;
8652         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8653           diag::ext_function_specialization_in_class :
8654           diag::err_function_specialization_in_class)
8655           << NewFD->getDeclName();
8656       } else if (CheckFunctionTemplateSpecialization(NewFD,
8657                                   (HasExplicitTemplateArgs ? &TemplateArgs
8658                                                            : nullptr),
8659                                                      Previous))
8660         NewFD->setInvalidDecl();
8661
8662       // C++ [dcl.stc]p1:
8663       //   A storage-class-specifier shall not be specified in an explicit
8664       //   specialization (14.7.3)
8665       FunctionTemplateSpecializationInfo *Info =
8666           NewFD->getTemplateSpecializationInfo();
8667       if (Info && SC != SC_None) {
8668         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8669           Diag(NewFD->getLocation(),
8670                diag::err_explicit_specialization_inconsistent_storage_class)
8671             << SC
8672             << FixItHint::CreateRemoval(
8673                                       D.getDeclSpec().getStorageClassSpecLoc());
8674
8675         else
8676           Diag(NewFD->getLocation(),
8677                diag::ext_explicit_specialization_storage_class)
8678             << FixItHint::CreateRemoval(
8679                                       D.getDeclSpec().getStorageClassSpecLoc());
8680       }
8681     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8682       if (CheckMemberSpecialization(NewFD, Previous))
8683           NewFD->setInvalidDecl();
8684     }
8685
8686     // Perform semantic checking on the function declaration.
8687     if (!isDependentClassScopeExplicitSpecialization) {
8688       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8689         CheckMain(NewFD, D.getDeclSpec());
8690
8691       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8692         CheckMSVCRTEntryPoint(NewFD);
8693
8694       if (!NewFD->isInvalidDecl())
8695         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8696                                                     isMemberSpecialization));
8697       else if (!Previous.empty())
8698         // Recover gracefully from an invalid redeclaration.
8699         D.setRedeclaration(true);
8700     }
8701
8702     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8703             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8704            "previous declaration set still overloaded");
8705
8706     NamedDecl *PrincipalDecl = (FunctionTemplate
8707                                 ? cast<NamedDecl>(FunctionTemplate)
8708                                 : NewFD);
8709
8710     if (isFriend && NewFD->getPreviousDecl()) {
8711       AccessSpecifier Access = AS_public;
8712       if (!NewFD->isInvalidDecl())
8713         Access = NewFD->getPreviousDecl()->getAccess();
8714
8715       NewFD->setAccess(Access);
8716       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8717     }
8718
8719     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8720         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8721       PrincipalDecl->setNonMemberOperator();
8722
8723     // If we have a function template, check the template parameter
8724     // list. This will check and merge default template arguments.
8725     if (FunctionTemplate) {
8726       FunctionTemplateDecl *PrevTemplate =
8727                                      FunctionTemplate->getPreviousDecl();
8728       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8729                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8730                                     : nullptr,
8731                             D.getDeclSpec().isFriendSpecified()
8732                               ? (D.isFunctionDefinition()
8733                                    ? TPC_FriendFunctionTemplateDefinition
8734                                    : TPC_FriendFunctionTemplate)
8735                               : (D.getCXXScopeSpec().isSet() &&
8736                                  DC && DC->isRecord() &&
8737                                  DC->isDependentContext())
8738                                   ? TPC_ClassTemplateMember
8739                                   : TPC_FunctionTemplate);
8740     }
8741
8742     if (NewFD->isInvalidDecl()) {
8743       // Ignore all the rest of this.
8744     } else if (!D.isRedeclaration()) {
8745       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8746                                        AddToScope };
8747       // Fake up an access specifier if it's supposed to be a class member.
8748       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8749         NewFD->setAccess(AS_public);
8750
8751       // Qualified decls generally require a previous declaration.
8752       if (D.getCXXScopeSpec().isSet()) {
8753         // ...with the major exception of templated-scope or
8754         // dependent-scope friend declarations.
8755
8756         // TODO: we currently also suppress this check in dependent
8757         // contexts because (1) the parameter depth will be off when
8758         // matching friend templates and (2) we might actually be
8759         // selecting a friend based on a dependent factor.  But there
8760         // are situations where these conditions don't apply and we
8761         // can actually do this check immediately.
8762         if (isFriend &&
8763             (TemplateParamLists.size() ||
8764              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8765              CurContext->isDependentContext())) {
8766           // ignore these
8767         } else {
8768           // The user tried to provide an out-of-line definition for a
8769           // function that is a member of a class or namespace, but there
8770           // was no such member function declared (C++ [class.mfct]p2,
8771           // C++ [namespace.memdef]p2). For example:
8772           //
8773           // class X {
8774           //   void f() const;
8775           // };
8776           //
8777           // void X::f() { } // ill-formed
8778           //
8779           // Complain about this problem, and attempt to suggest close
8780           // matches (e.g., those that differ only in cv-qualifiers and
8781           // whether the parameter types are references).
8782
8783           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8784                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8785             AddToScope = ExtraArgs.AddToScope;
8786             return Result;
8787           }
8788         }
8789
8790         // Unqualified local friend declarations are required to resolve
8791         // to something.
8792       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8793         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8794                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8795           AddToScope = ExtraArgs.AddToScope;
8796           return Result;
8797         }
8798       }
8799     } else if (!D.isFunctionDefinition() &&
8800                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8801                !isFriend && !isFunctionTemplateSpecialization &&
8802                !isMemberSpecialization) {
8803       // An out-of-line member function declaration must also be a
8804       // definition (C++ [class.mfct]p2).
8805       // Note that this is not the case for explicit specializations of
8806       // function templates or member functions of class templates, per
8807       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8808       // extension for compatibility with old SWIG code which likes to
8809       // generate them.
8810       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8811         << D.getCXXScopeSpec().getRange();
8812     }
8813   }
8814
8815   ProcessPragmaWeak(S, NewFD);
8816   checkAttributesAfterMerging(*this, *NewFD);
8817
8818   AddKnownFunctionAttributes(NewFD);
8819
8820   if (NewFD->hasAttr<OverloadableAttr>() &&
8821       !NewFD->getType()->getAs<FunctionProtoType>()) {
8822     Diag(NewFD->getLocation(),
8823          diag::err_attribute_overloadable_no_prototype)
8824       << NewFD;
8825
8826     // Turn this into a variadic function with no parameters.
8827     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8828     FunctionProtoType::ExtProtoInfo EPI(
8829         Context.getDefaultCallingConvention(true, false));
8830     EPI.Variadic = true;
8831     EPI.ExtInfo = FT->getExtInfo();
8832
8833     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8834     NewFD->setType(R);
8835   }
8836
8837   // If there's a #pragma GCC visibility in scope, and this isn't a class
8838   // member, set the visibility of this function.
8839   if (!DC->isRecord() && NewFD->isExternallyVisible())
8840     AddPushedVisibilityAttribute(NewFD);
8841
8842   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8843   // marking the function.
8844   AddCFAuditedAttribute(NewFD);
8845
8846   // If this is a function definition, check if we have to apply optnone due to
8847   // a pragma.
8848   if(D.isFunctionDefinition())
8849     AddRangeBasedOptnone(NewFD);
8850
8851   // If this is the first declaration of an extern C variable, update
8852   // the map of such variables.
8853   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8854       isIncompleteDeclExternC(*this, NewFD))
8855     RegisterLocallyScopedExternCDecl(NewFD, S);
8856
8857   // Set this FunctionDecl's range up to the right paren.
8858   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8859
8860   if (D.isRedeclaration() && !Previous.empty()) {
8861     checkDLLAttributeRedeclaration(
8862         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8863         isMemberSpecialization || isFunctionTemplateSpecialization,
8864         D.isFunctionDefinition());
8865   }
8866
8867   if (getLangOpts().CUDA) {
8868     IdentifierInfo *II = NewFD->getIdentifier();
8869     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8870         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8871       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8872         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8873
8874       Context.setcudaConfigureCallDecl(NewFD);
8875     }
8876
8877     // Variadic functions, other than a *declaration* of printf, are not allowed
8878     // in device-side CUDA code, unless someone passed
8879     // -fcuda-allow-variadic-functions.
8880     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8881         (NewFD->hasAttr<CUDADeviceAttr>() ||
8882          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8883         !(II && II->isStr("printf") && NewFD->isExternC() &&
8884           !D.isFunctionDefinition())) {
8885       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8886     }
8887   }
8888
8889   if (getLangOpts().CPlusPlus) {
8890     if (FunctionTemplate) {
8891       if (NewFD->isInvalidDecl())
8892         FunctionTemplate->setInvalidDecl();
8893       return FunctionTemplate;
8894     }
8895   }
8896
8897   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8898     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8899     if ((getLangOpts().OpenCLVersion >= 120)
8900         && (SC == SC_Static)) {
8901       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8902       D.setInvalidType();
8903     }
8904
8905     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8906     if (!NewFD->getReturnType()->isVoidType()) {
8907       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8908       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8909           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8910                                 : FixItHint());
8911       D.setInvalidType();
8912     }
8913
8914     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8915     for (auto Param : NewFD->parameters())
8916       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8917   }
8918   for (const ParmVarDecl *Param : NewFD->parameters()) {
8919     QualType PT = Param->getType();
8920
8921     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8922     // types.
8923     if (getLangOpts().OpenCLVersion >= 200) {
8924       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8925         QualType ElemTy = PipeTy->getElementType();
8926           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8927             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8928             D.setInvalidType();
8929           }
8930       }
8931     }
8932   }
8933
8934   MarkUnusedFileScopedDecl(NewFD);
8935
8936   // Here we have an function template explicit specialization at class scope.
8937   // The actually specialization will be postponed to template instatiation
8938   // time via the ClassScopeFunctionSpecializationDecl node.
8939   if (isDependentClassScopeExplicitSpecialization) {
8940     ClassScopeFunctionSpecializationDecl *NewSpec =
8941                          ClassScopeFunctionSpecializationDecl::Create(
8942                                 Context, CurContext, SourceLocation(),
8943                                 cast<CXXMethodDecl>(NewFD),
8944                                 HasExplicitTemplateArgs, TemplateArgs);
8945     CurContext->addDecl(NewSpec);
8946     AddToScope = false;
8947   }
8948
8949   return NewFD;
8950 }
8951
8952 /// \brief Checks if the new declaration declared in dependent context must be
8953 /// put in the same redeclaration chain as the specified declaration.
8954 ///
8955 /// \param D Declaration that is checked.
8956 /// \param PrevDecl Previous declaration found with proper lookup method for the
8957 ///                 same declaration name.
8958 /// \returns True if D must be added to the redeclaration chain which PrevDecl
8959 ///          belongs to.
8960 ///
8961 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
8962   // Any declarations should be put into redeclaration chains except for
8963   // friend declaration in a dependent context that names a function in
8964   // namespace scope.
8965   //
8966   // This allows to compile code like:
8967   //
8968   //       void func();
8969   //       template<typename T> class C1 { friend void func() { } };
8970   //       template<typename T> class C2 { friend void func() { } };
8971   //
8972   // This code snippet is a valid code unless both templates are instantiated.
8973   return !(D->getLexicalDeclContext()->isDependentContext() &&
8974            D->getDeclContext()->isFileContext() &&
8975            D->getFriendObjectKind() != Decl::FOK_None);
8976 }
8977
8978 /// \brief Perform semantic checking of a new function declaration.
8979 ///
8980 /// Performs semantic analysis of the new function declaration
8981 /// NewFD. This routine performs all semantic checking that does not
8982 /// require the actual declarator involved in the declaration, and is
8983 /// used both for the declaration of functions as they are parsed
8984 /// (called via ActOnDeclarator) and for the declaration of functions
8985 /// that have been instantiated via C++ template instantiation (called
8986 /// via InstantiateDecl).
8987 ///
8988 /// \param IsMemberSpecialization whether this new function declaration is
8989 /// a member specialization (that replaces any definition provided by the
8990 /// previous declaration).
8991 ///
8992 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8993 ///
8994 /// \returns true if the function declaration is a redeclaration.
8995 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8996                                     LookupResult &Previous,
8997                                     bool IsMemberSpecialization) {
8998   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8999          "Variably modified return types are not handled here");
9000
9001   // Determine whether the type of this function should be merged with
9002   // a previous visible declaration. This never happens for functions in C++,
9003   // and always happens in C if the previous declaration was visible.
9004   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9005                                !Previous.isShadowed();
9006
9007   bool Redeclaration = false;
9008   NamedDecl *OldDecl = nullptr;
9009
9010   // Merge or overload the declaration with an existing declaration of
9011   // the same name, if appropriate.
9012   if (!Previous.empty()) {
9013     // Determine whether NewFD is an overload of PrevDecl or
9014     // a declaration that requires merging. If it's an overload,
9015     // there's no more work to do here; we'll just add the new
9016     // function to the scope.
9017     if (!AllowOverloadingOfFunction(Previous, Context)) {
9018       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9019       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9020         Redeclaration = true;
9021         OldDecl = Candidate;
9022       }
9023     } else {
9024       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9025                             /*NewIsUsingDecl*/ false)) {
9026       case Ovl_Match:
9027         Redeclaration = true;
9028         break;
9029
9030       case Ovl_NonFunction:
9031         Redeclaration = true;
9032         break;
9033
9034       case Ovl_Overload:
9035         Redeclaration = false;
9036         break;
9037       }
9038
9039       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9040         // If a function name is overloadable in C, then every function
9041         // with that name must be marked "overloadable".
9042         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9043           << Redeclaration << NewFD;
9044         NamedDecl *OverloadedDecl =
9045             Redeclaration ? OldDecl : Previous.getRepresentativeDecl();
9046         Diag(OverloadedDecl->getLocation(),
9047              diag::note_attribute_overloadable_prev_overload);
9048         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9049       }
9050     }
9051   }
9052
9053   // Check for a previous extern "C" declaration with this name.
9054   if (!Redeclaration &&
9055       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9056     if (!Previous.empty()) {
9057       // This is an extern "C" declaration with the same name as a previous
9058       // declaration, and thus redeclares that entity...
9059       Redeclaration = true;
9060       OldDecl = Previous.getFoundDecl();
9061       MergeTypeWithPrevious = false;
9062
9063       // ... except in the presence of __attribute__((overloadable)).
9064       if (OldDecl->hasAttr<OverloadableAttr>()) {
9065         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9066           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9067             << Redeclaration << NewFD;
9068           Diag(Previous.getFoundDecl()->getLocation(),
9069                diag::note_attribute_overloadable_prev_overload);
9070           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9071         }
9072         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9073           Redeclaration = false;
9074           OldDecl = nullptr;
9075         }
9076       }
9077     }
9078   }
9079
9080   // C++11 [dcl.constexpr]p8:
9081   //   A constexpr specifier for a non-static member function that is not
9082   //   a constructor declares that member function to be const.
9083   //
9084   // This needs to be delayed until we know whether this is an out-of-line
9085   // definition of a static member function.
9086   //
9087   // This rule is not present in C++1y, so we produce a backwards
9088   // compatibility warning whenever it happens in C++11.
9089   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9090   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9091       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9092       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9093     CXXMethodDecl *OldMD = nullptr;
9094     if (OldDecl)
9095       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9096     if (!OldMD || !OldMD->isStatic()) {
9097       const FunctionProtoType *FPT =
9098         MD->getType()->castAs<FunctionProtoType>();
9099       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9100       EPI.TypeQuals |= Qualifiers::Const;
9101       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9102                                           FPT->getParamTypes(), EPI));
9103
9104       // Warn that we did this, if we're not performing template instantiation.
9105       // In that case, we'll have warned already when the template was defined.
9106       if (!inTemplateInstantiation()) {
9107         SourceLocation AddConstLoc;
9108         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9109                 .IgnoreParens().getAs<FunctionTypeLoc>())
9110           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9111
9112         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9113           << FixItHint::CreateInsertion(AddConstLoc, " const");
9114       }
9115     }
9116   }
9117
9118   if (Redeclaration) {
9119     // NewFD and OldDecl represent declarations that need to be
9120     // merged.
9121     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9122       NewFD->setInvalidDecl();
9123       return Redeclaration;
9124     }
9125
9126     Previous.clear();
9127     Previous.addDecl(OldDecl);
9128
9129     if (FunctionTemplateDecl *OldTemplateDecl
9130                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9131       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9132       FunctionTemplateDecl *NewTemplateDecl
9133         = NewFD->getDescribedFunctionTemplate();
9134       assert(NewTemplateDecl && "Template/non-template mismatch");
9135       if (CXXMethodDecl *Method
9136             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9137         Method->setAccess(OldTemplateDecl->getAccess());
9138         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9139       }
9140
9141       // If this is an explicit specialization of a member that is a function
9142       // template, mark it as a member specialization.
9143       if (IsMemberSpecialization &&
9144           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9145         NewTemplateDecl->setMemberSpecialization();
9146         assert(OldTemplateDecl->isMemberSpecialization());
9147         // Explicit specializations of a member template do not inherit deleted
9148         // status from the parent member template that they are specializing.
9149         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9150           FunctionDecl *const OldTemplatedDecl =
9151               OldTemplateDecl->getTemplatedDecl();
9152           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9153           OldTemplatedDecl->setDeletedAsWritten(false);
9154         }
9155       }
9156
9157     } else {
9158       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9159         // This needs to happen first so that 'inline' propagates.
9160         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9161         if (isa<CXXMethodDecl>(NewFD))
9162           NewFD->setAccess(OldDecl->getAccess());
9163       }
9164     }
9165   }
9166
9167   // Semantic checking for this function declaration (in isolation).
9168
9169   if (getLangOpts().CPlusPlus) {
9170     // C++-specific checks.
9171     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9172       CheckConstructor(Constructor);
9173     } else if (CXXDestructorDecl *Destructor =
9174                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9175       CXXRecordDecl *Record = Destructor->getParent();
9176       QualType ClassType = Context.getTypeDeclType(Record);
9177
9178       // FIXME: Shouldn't we be able to perform this check even when the class
9179       // type is dependent? Both gcc and edg can handle that.
9180       if (!ClassType->isDependentType()) {
9181         DeclarationName Name
9182           = Context.DeclarationNames.getCXXDestructorName(
9183                                         Context.getCanonicalType(ClassType));
9184         if (NewFD->getDeclName() != Name) {
9185           Diag(NewFD->getLocation(), diag::err_destructor_name);
9186           NewFD->setInvalidDecl();
9187           return Redeclaration;
9188         }
9189       }
9190     } else if (CXXConversionDecl *Conversion
9191                = dyn_cast<CXXConversionDecl>(NewFD)) {
9192       ActOnConversionDeclarator(Conversion);
9193     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9194       if (auto *TD = Guide->getDescribedFunctionTemplate())
9195         CheckDeductionGuideTemplate(TD);
9196
9197       // A deduction guide is not on the list of entities that can be
9198       // explicitly specialized.
9199       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9200         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9201             << /*explicit specialization*/ 1;
9202     }
9203
9204     // Find any virtual functions that this function overrides.
9205     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9206       if (!Method->isFunctionTemplateSpecialization() &&
9207           !Method->getDescribedFunctionTemplate() &&
9208           Method->isCanonicalDecl()) {
9209         if (AddOverriddenMethods(Method->getParent(), Method)) {
9210           // If the function was marked as "static", we have a problem.
9211           if (NewFD->getStorageClass() == SC_Static) {
9212             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9213           }
9214         }
9215       }
9216
9217       if (Method->isStatic())
9218         checkThisInStaticMemberFunctionType(Method);
9219     }
9220
9221     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9222     if (NewFD->isOverloadedOperator() &&
9223         CheckOverloadedOperatorDeclaration(NewFD)) {
9224       NewFD->setInvalidDecl();
9225       return Redeclaration;
9226     }
9227
9228     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9229     if (NewFD->getLiteralIdentifier() &&
9230         CheckLiteralOperatorDeclaration(NewFD)) {
9231       NewFD->setInvalidDecl();
9232       return Redeclaration;
9233     }
9234
9235     // In C++, check default arguments now that we have merged decls. Unless
9236     // the lexical context is the class, because in this case this is done
9237     // during delayed parsing anyway.
9238     if (!CurContext->isRecord())
9239       CheckCXXDefaultArguments(NewFD);
9240
9241     // If this function declares a builtin function, check the type of this
9242     // declaration against the expected type for the builtin.
9243     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9244       ASTContext::GetBuiltinTypeError Error;
9245       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9246       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9247       // If the type of the builtin differs only in its exception
9248       // specification, that's OK.
9249       // FIXME: If the types do differ in this way, it would be better to
9250       // retain the 'noexcept' form of the type.
9251       if (!T.isNull() &&
9252           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9253                                                             NewFD->getType()))
9254         // The type of this function differs from the type of the builtin,
9255         // so forget about the builtin entirely.
9256         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9257     }
9258
9259     // If this function is declared as being extern "C", then check to see if
9260     // the function returns a UDT (class, struct, or union type) that is not C
9261     // compatible, and if it does, warn the user.
9262     // But, issue any diagnostic on the first declaration only.
9263     if (Previous.empty() && NewFD->isExternC()) {
9264       QualType R = NewFD->getReturnType();
9265       if (R->isIncompleteType() && !R->isVoidType())
9266         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9267             << NewFD << R;
9268       else if (!R.isPODType(Context) && !R->isVoidType() &&
9269                !R->isObjCObjectPointerType())
9270         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9271     }
9272
9273     // C++1z [dcl.fct]p6:
9274     //   [...] whether the function has a non-throwing exception-specification
9275     //   [is] part of the function type
9276     //
9277     // This results in an ABI break between C++14 and C++17 for functions whose
9278     // declared type includes an exception-specification in a parameter or
9279     // return type. (Exception specifications on the function itself are OK in
9280     // most cases, and exception specifications are not permitted in most other
9281     // contexts where they could make it into a mangling.)
9282     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9283       auto HasNoexcept = [&](QualType T) -> bool {
9284         // Strip off declarator chunks that could be between us and a function
9285         // type. We don't need to look far, exception specifications are very
9286         // restricted prior to C++17.
9287         if (auto *RT = T->getAs<ReferenceType>())
9288           T = RT->getPointeeType();
9289         else if (T->isAnyPointerType())
9290           T = T->getPointeeType();
9291         else if (auto *MPT = T->getAs<MemberPointerType>())
9292           T = MPT->getPointeeType();
9293         if (auto *FPT = T->getAs<FunctionProtoType>())
9294           if (FPT->isNothrow(Context))
9295             return true;
9296         return false;
9297       };
9298
9299       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9300       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9301       for (QualType T : FPT->param_types())
9302         AnyNoexcept |= HasNoexcept(T);
9303       if (AnyNoexcept)
9304         Diag(NewFD->getLocation(),
9305              diag::warn_cxx1z_compat_exception_spec_in_signature)
9306             << NewFD;
9307     }
9308
9309     if (!Redeclaration && LangOpts.CUDA)
9310       checkCUDATargetOverload(NewFD, Previous);
9311   }
9312   return Redeclaration;
9313 }
9314
9315 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9316   // C++11 [basic.start.main]p3:
9317   //   A program that [...] declares main to be inline, static or
9318   //   constexpr is ill-formed.
9319   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9320   //   appear in a declaration of main.
9321   // static main is not an error under C99, but we should warn about it.
9322   // We accept _Noreturn main as an extension.
9323   if (FD->getStorageClass() == SC_Static)
9324     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9325          ? diag::err_static_main : diag::warn_static_main)
9326       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9327   if (FD->isInlineSpecified())
9328     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9329       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9330   if (DS.isNoreturnSpecified()) {
9331     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9332     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9333     Diag(NoreturnLoc, diag::ext_noreturn_main);
9334     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9335       << FixItHint::CreateRemoval(NoreturnRange);
9336   }
9337   if (FD->isConstexpr()) {
9338     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9339       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9340     FD->setConstexpr(false);
9341   }
9342
9343   if (getLangOpts().OpenCL) {
9344     Diag(FD->getLocation(), diag::err_opencl_no_main)
9345         << FD->hasAttr<OpenCLKernelAttr>();
9346     FD->setInvalidDecl();
9347     return;
9348   }
9349
9350   QualType T = FD->getType();
9351   assert(T->isFunctionType() && "function decl is not of function type");
9352   const FunctionType* FT = T->castAs<FunctionType>();
9353
9354   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9355     // In C with GNU extensions we allow main() to have non-integer return
9356     // type, but we should warn about the extension, and we disable the
9357     // implicit-return-zero rule.
9358
9359     // GCC in C mode accepts qualified 'int'.
9360     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9361       FD->setHasImplicitReturnZero(true);
9362     else {
9363       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9364       SourceRange RTRange = FD->getReturnTypeSourceRange();
9365       if (RTRange.isValid())
9366         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9367             << FixItHint::CreateReplacement(RTRange, "int");
9368     }
9369   } else {
9370     // In C and C++, main magically returns 0 if you fall off the end;
9371     // set the flag which tells us that.
9372     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9373
9374     // All the standards say that main() should return 'int'.
9375     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9376       FD->setHasImplicitReturnZero(true);
9377     else {
9378       // Otherwise, this is just a flat-out error.
9379       SourceRange RTRange = FD->getReturnTypeSourceRange();
9380       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9381           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9382                                 : FixItHint());
9383       FD->setInvalidDecl(true);
9384     }
9385   }
9386
9387   // Treat protoless main() as nullary.
9388   if (isa<FunctionNoProtoType>(FT)) return;
9389
9390   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9391   unsigned nparams = FTP->getNumParams();
9392   assert(FD->getNumParams() == nparams);
9393
9394   bool HasExtraParameters = (nparams > 3);
9395
9396   if (FTP->isVariadic()) {
9397     Diag(FD->getLocation(), diag::ext_variadic_main);
9398     // FIXME: if we had information about the location of the ellipsis, we
9399     // could add a FixIt hint to remove it as a parameter.
9400   }
9401
9402   // Darwin passes an undocumented fourth argument of type char**.  If
9403   // other platforms start sprouting these, the logic below will start
9404   // getting shifty.
9405   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9406     HasExtraParameters = false;
9407
9408   if (HasExtraParameters) {
9409     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9410     FD->setInvalidDecl(true);
9411     nparams = 3;
9412   }
9413
9414   // FIXME: a lot of the following diagnostics would be improved
9415   // if we had some location information about types.
9416
9417   QualType CharPP =
9418     Context.getPointerType(Context.getPointerType(Context.CharTy));
9419   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9420
9421   for (unsigned i = 0; i < nparams; ++i) {
9422     QualType AT = FTP->getParamType(i);
9423
9424     bool mismatch = true;
9425
9426     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9427       mismatch = false;
9428     else if (Expected[i] == CharPP) {
9429       // As an extension, the following forms are okay:
9430       //   char const **
9431       //   char const * const *
9432       //   char * const *
9433
9434       QualifierCollector qs;
9435       const PointerType* PT;
9436       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9437           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9438           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9439                               Context.CharTy)) {
9440         qs.removeConst();
9441         mismatch = !qs.empty();
9442       }
9443     }
9444
9445     if (mismatch) {
9446       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9447       // TODO: suggest replacing given type with expected type
9448       FD->setInvalidDecl(true);
9449     }
9450   }
9451
9452   if (nparams == 1 && !FD->isInvalidDecl()) {
9453     Diag(FD->getLocation(), diag::warn_main_one_arg);
9454   }
9455
9456   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9457     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9458     FD->setInvalidDecl();
9459   }
9460 }
9461
9462 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9463   QualType T = FD->getType();
9464   assert(T->isFunctionType() && "function decl is not of function type");
9465   const FunctionType *FT = T->castAs<FunctionType>();
9466
9467   // Set an implicit return of 'zero' if the function can return some integral,
9468   // enumeration, pointer or nullptr type.
9469   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9470       FT->getReturnType()->isAnyPointerType() ||
9471       FT->getReturnType()->isNullPtrType())
9472     // DllMain is exempt because a return value of zero means it failed.
9473     if (FD->getName() != "DllMain")
9474       FD->setHasImplicitReturnZero(true);
9475
9476   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9477     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9478     FD->setInvalidDecl();
9479   }
9480 }
9481
9482 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9483   // FIXME: Need strict checking.  In C89, we need to check for
9484   // any assignment, increment, decrement, function-calls, or
9485   // commas outside of a sizeof.  In C99, it's the same list,
9486   // except that the aforementioned are allowed in unevaluated
9487   // expressions.  Everything else falls under the
9488   // "may accept other forms of constant expressions" exception.
9489   // (We never end up here for C++, so the constant expression
9490   // rules there don't matter.)
9491   const Expr *Culprit;
9492   if (Init->isConstantInitializer(Context, false, &Culprit))
9493     return false;
9494   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9495     << Culprit->getSourceRange();
9496   return true;
9497 }
9498
9499 namespace {
9500   // Visits an initialization expression to see if OrigDecl is evaluated in
9501   // its own initialization and throws a warning if it does.
9502   class SelfReferenceChecker
9503       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9504     Sema &S;
9505     Decl *OrigDecl;
9506     bool isRecordType;
9507     bool isPODType;
9508     bool isReferenceType;
9509
9510     bool isInitList;
9511     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9512
9513   public:
9514     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9515
9516     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9517                                                     S(S), OrigDecl(OrigDecl) {
9518       isPODType = false;
9519       isRecordType = false;
9520       isReferenceType = false;
9521       isInitList = false;
9522       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9523         isPODType = VD->getType().isPODType(S.Context);
9524         isRecordType = VD->getType()->isRecordType();
9525         isReferenceType = VD->getType()->isReferenceType();
9526       }
9527     }
9528
9529     // For most expressions, just call the visitor.  For initializer lists,
9530     // track the index of the field being initialized since fields are
9531     // initialized in order allowing use of previously initialized fields.
9532     void CheckExpr(Expr *E) {
9533       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9534       if (!InitList) {
9535         Visit(E);
9536         return;
9537       }
9538
9539       // Track and increment the index here.
9540       isInitList = true;
9541       InitFieldIndex.push_back(0);
9542       for (auto Child : InitList->children()) {
9543         CheckExpr(cast<Expr>(Child));
9544         ++InitFieldIndex.back();
9545       }
9546       InitFieldIndex.pop_back();
9547     }
9548
9549     // Returns true if MemberExpr is checked and no further checking is needed.
9550     // Returns false if additional checking is required.
9551     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9552       llvm::SmallVector<FieldDecl*, 4> Fields;
9553       Expr *Base = E;
9554       bool ReferenceField = false;
9555
9556       // Get the field memebers used.
9557       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9558         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9559         if (!FD)
9560           return false;
9561         Fields.push_back(FD);
9562         if (FD->getType()->isReferenceType())
9563           ReferenceField = true;
9564         Base = ME->getBase()->IgnoreParenImpCasts();
9565       }
9566
9567       // Keep checking only if the base Decl is the same.
9568       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9569       if (!DRE || DRE->getDecl() != OrigDecl)
9570         return false;
9571
9572       // A reference field can be bound to an unininitialized field.
9573       if (CheckReference && !ReferenceField)
9574         return true;
9575
9576       // Convert FieldDecls to their index number.
9577       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9578       for (const FieldDecl *I : llvm::reverse(Fields))
9579         UsedFieldIndex.push_back(I->getFieldIndex());
9580
9581       // See if a warning is needed by checking the first difference in index
9582       // numbers.  If field being used has index less than the field being
9583       // initialized, then the use is safe.
9584       for (auto UsedIter = UsedFieldIndex.begin(),
9585                 UsedEnd = UsedFieldIndex.end(),
9586                 OrigIter = InitFieldIndex.begin(),
9587                 OrigEnd = InitFieldIndex.end();
9588            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9589         if (*UsedIter < *OrigIter)
9590           return true;
9591         if (*UsedIter > *OrigIter)
9592           break;
9593       }
9594
9595       // TODO: Add a different warning which will print the field names.
9596       HandleDeclRefExpr(DRE);
9597       return true;
9598     }
9599
9600     // For most expressions, the cast is directly above the DeclRefExpr.
9601     // For conditional operators, the cast can be outside the conditional
9602     // operator if both expressions are DeclRefExpr's.
9603     void HandleValue(Expr *E) {
9604       E = E->IgnoreParens();
9605       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9606         HandleDeclRefExpr(DRE);
9607         return;
9608       }
9609
9610       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9611         Visit(CO->getCond());
9612         HandleValue(CO->getTrueExpr());
9613         HandleValue(CO->getFalseExpr());
9614         return;
9615       }
9616
9617       if (BinaryConditionalOperator *BCO =
9618               dyn_cast<BinaryConditionalOperator>(E)) {
9619         Visit(BCO->getCond());
9620         HandleValue(BCO->getFalseExpr());
9621         return;
9622       }
9623
9624       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9625         HandleValue(OVE->getSourceExpr());
9626         return;
9627       }
9628
9629       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9630         if (BO->getOpcode() == BO_Comma) {
9631           Visit(BO->getLHS());
9632           HandleValue(BO->getRHS());
9633           return;
9634         }
9635       }
9636
9637       if (isa<MemberExpr>(E)) {
9638         if (isInitList) {
9639           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9640                                       false /*CheckReference*/))
9641             return;
9642         }
9643
9644         Expr *Base = E->IgnoreParenImpCasts();
9645         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9646           // Check for static member variables and don't warn on them.
9647           if (!isa<FieldDecl>(ME->getMemberDecl()))
9648             return;
9649           Base = ME->getBase()->IgnoreParenImpCasts();
9650         }
9651         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9652           HandleDeclRefExpr(DRE);
9653         return;
9654       }
9655
9656       Visit(E);
9657     }
9658
9659     // Reference types not handled in HandleValue are handled here since all
9660     // uses of references are bad, not just r-value uses.
9661     void VisitDeclRefExpr(DeclRefExpr *E) {
9662       if (isReferenceType)
9663         HandleDeclRefExpr(E);
9664     }
9665
9666     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9667       if (E->getCastKind() == CK_LValueToRValue) {
9668         HandleValue(E->getSubExpr());
9669         return;
9670       }
9671
9672       Inherited::VisitImplicitCastExpr(E);
9673     }
9674
9675     void VisitMemberExpr(MemberExpr *E) {
9676       if (isInitList) {
9677         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9678           return;
9679       }
9680
9681       // Don't warn on arrays since they can be treated as pointers.
9682       if (E->getType()->canDecayToPointerType()) return;
9683
9684       // Warn when a non-static method call is followed by non-static member
9685       // field accesses, which is followed by a DeclRefExpr.
9686       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9687       bool Warn = (MD && !MD->isStatic());
9688       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9689       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9690         if (!isa<FieldDecl>(ME->getMemberDecl()))
9691           Warn = false;
9692         Base = ME->getBase()->IgnoreParenImpCasts();
9693       }
9694
9695       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9696         if (Warn)
9697           HandleDeclRefExpr(DRE);
9698         return;
9699       }
9700
9701       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9702       // Visit that expression.
9703       Visit(Base);
9704     }
9705
9706     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9707       Expr *Callee = E->getCallee();
9708
9709       if (isa<UnresolvedLookupExpr>(Callee))
9710         return Inherited::VisitCXXOperatorCallExpr(E);
9711
9712       Visit(Callee);
9713       for (auto Arg: E->arguments())
9714         HandleValue(Arg->IgnoreParenImpCasts());
9715     }
9716
9717     void VisitUnaryOperator(UnaryOperator *E) {
9718       // For POD record types, addresses of its own members are well-defined.
9719       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9720           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9721         if (!isPODType)
9722           HandleValue(E->getSubExpr());
9723         return;
9724       }
9725
9726       if (E->isIncrementDecrementOp()) {
9727         HandleValue(E->getSubExpr());
9728         return;
9729       }
9730
9731       Inherited::VisitUnaryOperator(E);
9732     }
9733
9734     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9735
9736     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9737       if (E->getConstructor()->isCopyConstructor()) {
9738         Expr *ArgExpr = E->getArg(0);
9739         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9740           if (ILE->getNumInits() == 1)
9741             ArgExpr = ILE->getInit(0);
9742         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9743           if (ICE->getCastKind() == CK_NoOp)
9744             ArgExpr = ICE->getSubExpr();
9745         HandleValue(ArgExpr);
9746         return;
9747       }
9748       Inherited::VisitCXXConstructExpr(E);
9749     }
9750
9751     void VisitCallExpr(CallExpr *E) {
9752       // Treat std::move as a use.
9753       if (E->getNumArgs() == 1) {
9754         if (FunctionDecl *FD = E->getDirectCallee()) {
9755           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9756               FD->getIdentifier()->isStr("move")) {
9757             HandleValue(E->getArg(0));
9758             return;
9759           }
9760         }
9761       }
9762
9763       Inherited::VisitCallExpr(E);
9764     }
9765
9766     void VisitBinaryOperator(BinaryOperator *E) {
9767       if (E->isCompoundAssignmentOp()) {
9768         HandleValue(E->getLHS());
9769         Visit(E->getRHS());
9770         return;
9771       }
9772
9773       Inherited::VisitBinaryOperator(E);
9774     }
9775
9776     // A custom visitor for BinaryConditionalOperator is needed because the
9777     // regular visitor would check the condition and true expression separately
9778     // but both point to the same place giving duplicate diagnostics.
9779     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9780       Visit(E->getCond());
9781       Visit(E->getFalseExpr());
9782     }
9783
9784     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9785       Decl* ReferenceDecl = DRE->getDecl();
9786       if (OrigDecl != ReferenceDecl) return;
9787       unsigned diag;
9788       if (isReferenceType) {
9789         diag = diag::warn_uninit_self_reference_in_reference_init;
9790       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9791         diag = diag::warn_static_self_reference_in_init;
9792       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9793                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9794                  DRE->getDecl()->getType()->isRecordType()) {
9795         diag = diag::warn_uninit_self_reference_in_init;
9796       } else {
9797         // Local variables will be handled by the CFG analysis.
9798         return;
9799       }
9800
9801       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9802                             S.PDiag(diag)
9803                               << DRE->getNameInfo().getName()
9804                               << OrigDecl->getLocation()
9805                               << DRE->getSourceRange());
9806     }
9807   };
9808
9809   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9810   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9811                                  bool DirectInit) {
9812     // Parameters arguments are occassionially constructed with itself,
9813     // for instance, in recursive functions.  Skip them.
9814     if (isa<ParmVarDecl>(OrigDecl))
9815       return;
9816
9817     E = E->IgnoreParens();
9818
9819     // Skip checking T a = a where T is not a record or reference type.
9820     // Doing so is a way to silence uninitialized warnings.
9821     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9822       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9823         if (ICE->getCastKind() == CK_LValueToRValue)
9824           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9825             if (DRE->getDecl() == OrigDecl)
9826               return;
9827
9828     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9829   }
9830 } // end anonymous namespace
9831
9832 namespace {
9833   // Simple wrapper to add the name of a variable or (if no variable is
9834   // available) a DeclarationName into a diagnostic.
9835   struct VarDeclOrName {
9836     VarDecl *VDecl;
9837     DeclarationName Name;
9838
9839     friend const Sema::SemaDiagnosticBuilder &
9840     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
9841       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
9842     }
9843   };
9844 } // end anonymous namespace
9845
9846 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9847                                             DeclarationName Name, QualType Type,
9848                                             TypeSourceInfo *TSI,
9849                                             SourceRange Range, bool DirectInit,
9850                                             Expr *Init) {
9851   bool IsInitCapture = !VDecl;
9852   assert((!VDecl || !VDecl->isInitCapture()) &&
9853          "init captures are expected to be deduced prior to initialization");
9854
9855   VarDeclOrName VN{VDecl, Name};
9856
9857   DeducedType *Deduced = Type->getContainedDeducedType();
9858   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
9859
9860   // C++11 [dcl.spec.auto]p3
9861   if (!Init) {
9862     assert(VDecl && "no init for init capture deduction?");
9863     Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
9864       << VDecl->getDeclName() << Type;
9865     return QualType();
9866   }
9867
9868   ArrayRef<Expr*> DeduceInits = Init;
9869   if (DirectInit) {
9870     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
9871       DeduceInits = PL->exprs();
9872   }
9873
9874   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
9875     assert(VDecl && "non-auto type for init capture deduction?");
9876     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9877     InitializationKind Kind = InitializationKind::CreateForInit(
9878         VDecl->getLocation(), DirectInit, Init);
9879     // FIXME: Initialization should not be taking a mutable list of inits. 
9880     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
9881     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
9882                                                        InitsCopy);
9883   }
9884
9885   if (DirectInit) {
9886     if (auto *IL = dyn_cast<InitListExpr>(Init))
9887       DeduceInits = IL->inits();
9888   }
9889
9890   // Deduction only works if we have exactly one source expression.
9891   if (DeduceInits.empty()) {
9892     // It isn't possible to write this directly, but it is possible to
9893     // end up in this situation with "auto x(some_pack...);"
9894     Diag(Init->getLocStart(), IsInitCapture
9895                                   ? diag::err_init_capture_no_expression
9896                                   : diag::err_auto_var_init_no_expression)
9897         << VN << Type << Range;
9898     return QualType();
9899   }
9900
9901   if (DeduceInits.size() > 1) {
9902     Diag(DeduceInits[1]->getLocStart(),
9903          IsInitCapture ? diag::err_init_capture_multiple_expressions
9904                        : diag::err_auto_var_init_multiple_expressions)
9905         << VN << Type << Range;
9906     return QualType();
9907   }
9908
9909   Expr *DeduceInit = DeduceInits[0];
9910   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9911     Diag(Init->getLocStart(), IsInitCapture
9912                                   ? diag::err_init_capture_paren_braces
9913                                   : diag::err_auto_var_init_paren_braces)
9914         << isa<InitListExpr>(Init) << VN << Type << Range;
9915     return QualType();
9916   }
9917
9918   // Expressions default to 'id' when we're in a debugger.
9919   bool DefaultedAnyToId = false;
9920   if (getLangOpts().DebuggerCastResultToId &&
9921       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9922     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9923     if (Result.isInvalid()) {
9924       return QualType();
9925     }
9926     Init = Result.get();
9927     DefaultedAnyToId = true;
9928   }
9929
9930   // C++ [dcl.decomp]p1:
9931   //   If the assignment-expression [...] has array type A and no ref-qualifier
9932   //   is present, e has type cv A
9933   if (VDecl && isa<DecompositionDecl>(VDecl) &&
9934       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
9935       DeduceInit->getType()->isConstantArrayType())
9936     return Context.getQualifiedType(DeduceInit->getType(),
9937                                     Type.getQualifiers());
9938
9939   QualType DeducedType;
9940   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9941     if (!IsInitCapture)
9942       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9943     else if (isa<InitListExpr>(Init))
9944       Diag(Range.getBegin(),
9945            diag::err_init_capture_deduction_failure_from_init_list)
9946           << VN
9947           << (DeduceInit->getType().isNull() ? TSI->getType()
9948                                              : DeduceInit->getType())
9949           << DeduceInit->getSourceRange();
9950     else
9951       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9952           << VN << TSI->getType()
9953           << (DeduceInit->getType().isNull() ? TSI->getType()
9954                                              : DeduceInit->getType())
9955           << DeduceInit->getSourceRange();
9956   }
9957
9958   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9959   // 'id' instead of a specific object type prevents most of our usual
9960   // checks.
9961   // We only want to warn outside of template instantiations, though:
9962   // inside a template, the 'id' could have come from a parameter.
9963   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
9964       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9965     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9966     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
9967   }
9968
9969   return DeducedType;
9970 }
9971
9972 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
9973                                          Expr *Init) {
9974   QualType DeducedType = deduceVarTypeFromInitializer(
9975       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
9976       VDecl->getSourceRange(), DirectInit, Init);
9977   if (DeducedType.isNull()) {
9978     VDecl->setInvalidDecl();
9979     return true;
9980   }
9981
9982   VDecl->setType(DeducedType);
9983   assert(VDecl->isLinkageValid());
9984
9985   // In ARC, infer lifetime.
9986   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9987     VDecl->setInvalidDecl();
9988
9989   // If this is a redeclaration, check that the type we just deduced matches
9990   // the previously declared type.
9991   if (VarDecl *Old = VDecl->getPreviousDecl()) {
9992     // We never need to merge the type, because we cannot form an incomplete
9993     // array of auto, nor deduce such a type.
9994     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9995   }
9996
9997   // Check the deduced type is valid for a variable declaration.
9998   CheckVariableDeclarationType(VDecl);
9999   return VDecl->isInvalidDecl();
10000 }
10001
10002 /// AddInitializerToDecl - Adds the initializer Init to the
10003 /// declaration dcl. If DirectInit is true, this is C++ direct
10004 /// initialization rather than copy initialization.
10005 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10006   // If there is no declaration, there was an error parsing it.  Just ignore
10007   // the initializer.
10008   if (!RealDecl || RealDecl->isInvalidDecl()) {
10009     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10010     return;
10011   }
10012
10013   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10014     // Pure-specifiers are handled in ActOnPureSpecifier.
10015     Diag(Method->getLocation(), diag::err_member_function_initialization)
10016       << Method->getDeclName() << Init->getSourceRange();
10017     Method->setInvalidDecl();
10018     return;
10019   }
10020
10021   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10022   if (!VDecl) {
10023     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10024     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10025     RealDecl->setInvalidDecl();
10026     return;
10027   }
10028
10029   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10030   if (VDecl->getType()->isUndeducedType()) {
10031     // Attempt typo correction early so that the type of the init expression can
10032     // be deduced based on the chosen correction if the original init contains a
10033     // TypoExpr.
10034     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10035     if (!Res.isUsable()) {
10036       RealDecl->setInvalidDecl();
10037       return;
10038     }
10039     Init = Res.get();
10040
10041     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10042       return;
10043   }
10044
10045   // dllimport cannot be used on variable definitions.
10046   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10047     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10048     VDecl->setInvalidDecl();
10049     return;
10050   }
10051
10052   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10053     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10054     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10055     VDecl->setInvalidDecl();
10056     return;
10057   }
10058
10059   if (!VDecl->getType()->isDependentType()) {
10060     // A definition must end up with a complete type, which means it must be
10061     // complete with the restriction that an array type might be completed by
10062     // the initializer; note that later code assumes this restriction.
10063     QualType BaseDeclType = VDecl->getType();
10064     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10065       BaseDeclType = Array->getElementType();
10066     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10067                             diag::err_typecheck_decl_incomplete_type)) {
10068       RealDecl->setInvalidDecl();
10069       return;
10070     }
10071
10072     // The variable can not have an abstract class type.
10073     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10074                                diag::err_abstract_type_in_decl,
10075                                AbstractVariableType))
10076       VDecl->setInvalidDecl();
10077   }
10078
10079   // If adding the initializer will turn this declaration into a definition,
10080   // and we already have a definition for this variable, diagnose or otherwise
10081   // handle the situation.
10082   VarDecl *Def;
10083   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10084       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10085       !VDecl->isThisDeclarationADemotedDefinition() &&
10086       checkVarDeclRedefinition(Def, VDecl))
10087     return;
10088
10089   if (getLangOpts().CPlusPlus) {
10090     // C++ [class.static.data]p4
10091     //   If a static data member is of const integral or const
10092     //   enumeration type, its declaration in the class definition can
10093     //   specify a constant-initializer which shall be an integral
10094     //   constant expression (5.19). In that case, the member can appear
10095     //   in integral constant expressions. The member shall still be
10096     //   defined in a namespace scope if it is used in the program and the
10097     //   namespace scope definition shall not contain an initializer.
10098     //
10099     // We already performed a redefinition check above, but for static
10100     // data members we also need to check whether there was an in-class
10101     // declaration with an initializer.
10102     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10103       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10104           << VDecl->getDeclName();
10105       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10106            diag::note_previous_initializer)
10107           << 0;
10108       return;
10109     }
10110
10111     if (VDecl->hasLocalStorage())
10112       getCurFunction()->setHasBranchProtectedScope();
10113
10114     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10115       VDecl->setInvalidDecl();
10116       return;
10117     }
10118   }
10119
10120   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10121   // a kernel function cannot be initialized."
10122   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10123     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10124     VDecl->setInvalidDecl();
10125     return;
10126   }
10127
10128   // Get the decls type and save a reference for later, since
10129   // CheckInitializerTypes may change it.
10130   QualType DclT = VDecl->getType(), SavT = DclT;
10131
10132   // Expressions default to 'id' when we're in a debugger
10133   // and we are assigning it to a variable of Objective-C pointer type.
10134   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10135       Init->getType() == Context.UnknownAnyTy) {
10136     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10137     if (Result.isInvalid()) {
10138       VDecl->setInvalidDecl();
10139       return;
10140     }
10141     Init = Result.get();
10142   }
10143
10144   // Perform the initialization.
10145   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10146   if (!VDecl->isInvalidDecl()) {
10147     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10148     InitializationKind Kind = InitializationKind::CreateForInit(
10149         VDecl->getLocation(), DirectInit, Init);
10150
10151     MultiExprArg Args = Init;
10152     if (CXXDirectInit)
10153       Args = MultiExprArg(CXXDirectInit->getExprs(),
10154                           CXXDirectInit->getNumExprs());
10155
10156     // Try to correct any TypoExprs in the initialization arguments.
10157     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10158       ExprResult Res = CorrectDelayedTyposInExpr(
10159           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10160             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10161             return Init.Failed() ? ExprError() : E;
10162           });
10163       if (Res.isInvalid()) {
10164         VDecl->setInvalidDecl();
10165       } else if (Res.get() != Args[Idx]) {
10166         Args[Idx] = Res.get();
10167       }
10168     }
10169     if (VDecl->isInvalidDecl())
10170       return;
10171
10172     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10173                                    /*TopLevelOfInitList=*/false,
10174                                    /*TreatUnavailableAsInvalid=*/false);
10175     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10176     if (Result.isInvalid()) {
10177       VDecl->setInvalidDecl();
10178       return;
10179     }
10180
10181     Init = Result.getAs<Expr>();
10182   }
10183
10184   // Check for self-references within variable initializers.
10185   // Variables declared within a function/method body (except for references)
10186   // are handled by a dataflow analysis.
10187   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10188       VDecl->getType()->isReferenceType()) {
10189     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10190   }
10191
10192   // If the type changed, it means we had an incomplete type that was
10193   // completed by the initializer. For example:
10194   //   int ary[] = { 1, 3, 5 };
10195   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10196   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10197     VDecl->setType(DclT);
10198
10199   if (!VDecl->isInvalidDecl()) {
10200     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10201
10202     if (VDecl->hasAttr<BlocksAttr>())
10203       checkRetainCycles(VDecl, Init);
10204
10205     // It is safe to assign a weak reference into a strong variable.
10206     // Although this code can still have problems:
10207     //   id x = self.weakProp;
10208     //   id y = self.weakProp;
10209     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10210     // paths through the function. This should be revisited if
10211     // -Wrepeated-use-of-weak is made flow-sensitive.
10212     if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10213          VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10214         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10215                          Init->getLocStart()))
10216       getCurFunction()->markSafeWeakUse(Init);
10217   }
10218
10219   // The initialization is usually a full-expression.
10220   //
10221   // FIXME: If this is a braced initialization of an aggregate, it is not
10222   // an expression, and each individual field initializer is a separate
10223   // full-expression. For instance, in:
10224   //
10225   //   struct Temp { ~Temp(); };
10226   //   struct S { S(Temp); };
10227   //   struct T { S a, b; } t = { Temp(), Temp() }
10228   //
10229   // we should destroy the first Temp before constructing the second.
10230   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10231                                           false,
10232                                           VDecl->isConstexpr());
10233   if (Result.isInvalid()) {
10234     VDecl->setInvalidDecl();
10235     return;
10236   }
10237   Init = Result.get();
10238
10239   // Attach the initializer to the decl.
10240   VDecl->setInit(Init);
10241
10242   if (VDecl->isLocalVarDecl()) {
10243     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10244     // static storage duration shall be constant expressions or string literals.
10245     // C++ does not have this restriction.
10246     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
10247       const Expr *Culprit;
10248       if (VDecl->getStorageClass() == SC_Static)
10249         CheckForConstantInitializer(Init, DclT);
10250       // C89 is stricter than C99 for non-static aggregate types.
10251       // C89 6.5.7p3: All the expressions [...] in an initializer list
10252       // for an object that has aggregate or union type shall be
10253       // constant expressions.
10254       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10255                isa<InitListExpr>(Init) &&
10256                !Init->isConstantInitializer(Context, false, &Culprit))
10257         Diag(Culprit->getExprLoc(),
10258              diag::ext_aggregate_init_not_constant)
10259           << Culprit->getSourceRange();
10260     }
10261   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10262              VDecl->getLexicalDeclContext()->isRecord()) {
10263     // This is an in-class initialization for a static data member, e.g.,
10264     //
10265     // struct S {
10266     //   static const int value = 17;
10267     // };
10268
10269     // C++ [class.mem]p4:
10270     //   A member-declarator can contain a constant-initializer only
10271     //   if it declares a static member (9.4) of const integral or
10272     //   const enumeration type, see 9.4.2.
10273     //
10274     // C++11 [class.static.data]p3:
10275     //   If a non-volatile non-inline const static data member is of integral
10276     //   or enumeration type, its declaration in the class definition can
10277     //   specify a brace-or-equal-initializer in which every initializer-clause
10278     //   that is an assignment-expression is a constant expression. A static
10279     //   data member of literal type can be declared in the class definition
10280     //   with the constexpr specifier; if so, its declaration shall specify a
10281     //   brace-or-equal-initializer in which every initializer-clause that is
10282     //   an assignment-expression is a constant expression.
10283
10284     // Do nothing on dependent types.
10285     if (DclT->isDependentType()) {
10286
10287     // Allow any 'static constexpr' members, whether or not they are of literal
10288     // type. We separately check that every constexpr variable is of literal
10289     // type.
10290     } else if (VDecl->isConstexpr()) {
10291
10292     // Require constness.
10293     } else if (!DclT.isConstQualified()) {
10294       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10295         << Init->getSourceRange();
10296       VDecl->setInvalidDecl();
10297
10298     // We allow integer constant expressions in all cases.
10299     } else if (DclT->isIntegralOrEnumerationType()) {
10300       // Check whether the expression is a constant expression.
10301       SourceLocation Loc;
10302       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10303         // In C++11, a non-constexpr const static data member with an
10304         // in-class initializer cannot be volatile.
10305         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10306       else if (Init->isValueDependent())
10307         ; // Nothing to check.
10308       else if (Init->isIntegerConstantExpr(Context, &Loc))
10309         ; // Ok, it's an ICE!
10310       else if (Init->isEvaluatable(Context)) {
10311         // If we can constant fold the initializer through heroics, accept it,
10312         // but report this as a use of an extension for -pedantic.
10313         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10314           << Init->getSourceRange();
10315       } else {
10316         // Otherwise, this is some crazy unknown case.  Report the issue at the
10317         // location provided by the isIntegerConstantExpr failed check.
10318         Diag(Loc, diag::err_in_class_initializer_non_constant)
10319           << Init->getSourceRange();
10320         VDecl->setInvalidDecl();
10321       }
10322
10323     // We allow foldable floating-point constants as an extension.
10324     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10325       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10326       // it anyway and provide a fixit to add the 'constexpr'.
10327       if (getLangOpts().CPlusPlus11) {
10328         Diag(VDecl->getLocation(),
10329              diag::ext_in_class_initializer_float_type_cxx11)
10330             << DclT << Init->getSourceRange();
10331         Diag(VDecl->getLocStart(),
10332              diag::note_in_class_initializer_float_type_cxx11)
10333             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10334       } else {
10335         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10336           << DclT << Init->getSourceRange();
10337
10338         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10339           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10340             << Init->getSourceRange();
10341           VDecl->setInvalidDecl();
10342         }
10343       }
10344
10345     // Suggest adding 'constexpr' in C++11 for literal types.
10346     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10347       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10348         << DclT << Init->getSourceRange()
10349         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10350       VDecl->setConstexpr(true);
10351
10352     } else {
10353       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10354         << DclT << Init->getSourceRange();
10355       VDecl->setInvalidDecl();
10356     }
10357   } else if (VDecl->isFileVarDecl()) {
10358     // In C, extern is typically used to avoid tentative definitions when
10359     // declaring variables in headers, but adding an intializer makes it a
10360     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10361     // In C++, extern is often used to give implictly static const variables
10362     // external linkage, so don't warn in that case. If selectany is present,
10363     // this might be header code intended for C and C++ inclusion, so apply the
10364     // C++ rules.
10365     if (VDecl->getStorageClass() == SC_Extern &&
10366         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10367          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10368         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10369         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10370       Diag(VDecl->getLocation(), diag::warn_extern_init);
10371
10372     // C99 6.7.8p4. All file scoped initializers need to be constant.
10373     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10374       CheckForConstantInitializer(Init, DclT);
10375   }
10376
10377   // We will represent direct-initialization similarly to copy-initialization:
10378   //    int x(1);  -as-> int x = 1;
10379   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10380   //
10381   // Clients that want to distinguish between the two forms, can check for
10382   // direct initializer using VarDecl::getInitStyle().
10383   // A major benefit is that clients that don't particularly care about which
10384   // exactly form was it (like the CodeGen) can handle both cases without
10385   // special case code.
10386
10387   // C++ 8.5p11:
10388   // The form of initialization (using parentheses or '=') is generally
10389   // insignificant, but does matter when the entity being initialized has a
10390   // class type.
10391   if (CXXDirectInit) {
10392     assert(DirectInit && "Call-style initializer must be direct init.");
10393     VDecl->setInitStyle(VarDecl::CallInit);
10394   } else if (DirectInit) {
10395     // This must be list-initialization. No other way is direct-initialization.
10396     VDecl->setInitStyle(VarDecl::ListInit);
10397   }
10398
10399   CheckCompleteVariableDeclaration(VDecl);
10400 }
10401
10402 /// ActOnInitializerError - Given that there was an error parsing an
10403 /// initializer for the given declaration, try to return to some form
10404 /// of sanity.
10405 void Sema::ActOnInitializerError(Decl *D) {
10406   // Our main concern here is re-establishing invariants like "a
10407   // variable's type is either dependent or complete".
10408   if (!D || D->isInvalidDecl()) return;
10409
10410   VarDecl *VD = dyn_cast<VarDecl>(D);
10411   if (!VD) return;
10412
10413   // Bindings are not usable if we can't make sense of the initializer.
10414   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10415     for (auto *BD : DD->bindings())
10416       BD->setInvalidDecl();
10417
10418   // Auto types are meaningless if we can't make sense of the initializer.
10419   if (ParsingInitForAutoVars.count(D)) {
10420     D->setInvalidDecl();
10421     return;
10422   }
10423
10424   QualType Ty = VD->getType();
10425   if (Ty->isDependentType()) return;
10426
10427   // Require a complete type.
10428   if (RequireCompleteType(VD->getLocation(),
10429                           Context.getBaseElementType(Ty),
10430                           diag::err_typecheck_decl_incomplete_type)) {
10431     VD->setInvalidDecl();
10432     return;
10433   }
10434
10435   // Require a non-abstract type.
10436   if (RequireNonAbstractType(VD->getLocation(), Ty,
10437                              diag::err_abstract_type_in_decl,
10438                              AbstractVariableType)) {
10439     VD->setInvalidDecl();
10440     return;
10441   }
10442
10443   // Don't bother complaining about constructors or destructors,
10444   // though.
10445 }
10446
10447 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10448   // If there is no declaration, there was an error parsing it. Just ignore it.
10449   if (!RealDecl)
10450     return;
10451
10452   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10453     QualType Type = Var->getType();
10454
10455     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10456     if (isa<DecompositionDecl>(RealDecl)) {
10457       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10458       Var->setInvalidDecl();
10459       return;
10460     }
10461
10462     if (Type->isUndeducedType() &&
10463         DeduceVariableDeclarationType(Var, false, nullptr))
10464       return;
10465
10466     // C++11 [class.static.data]p3: A static data member can be declared with
10467     // the constexpr specifier; if so, its declaration shall specify
10468     // a brace-or-equal-initializer.
10469     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10470     // the definition of a variable [...] or the declaration of a static data
10471     // member.
10472     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10473         !Var->isThisDeclarationADemotedDefinition()) {
10474       if (Var->isStaticDataMember()) {
10475         // C++1z removes the relevant rule; the in-class declaration is always
10476         // a definition there.
10477         if (!getLangOpts().CPlusPlus1z) {
10478           Diag(Var->getLocation(),
10479                diag::err_constexpr_static_mem_var_requires_init)
10480             << Var->getDeclName();
10481           Var->setInvalidDecl();
10482           return;
10483         }
10484       } else {
10485         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10486         Var->setInvalidDecl();
10487         return;
10488       }
10489     }
10490
10491     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10492     // definition having the concept specifier is called a variable concept. A
10493     // concept definition refers to [...] a variable concept and its initializer.
10494     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10495       if (VTD->isConcept()) {
10496         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10497         Var->setInvalidDecl();
10498         return;
10499       }
10500     }
10501
10502     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10503     // be initialized.
10504     if (!Var->isInvalidDecl() &&
10505         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10506         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10507       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10508       Var->setInvalidDecl();
10509       return;
10510     }
10511
10512     switch (Var->isThisDeclarationADefinition()) {
10513     case VarDecl::Definition:
10514       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10515         break;
10516
10517       // We have an out-of-line definition of a static data member
10518       // that has an in-class initializer, so we type-check this like
10519       // a declaration.
10520       //
10521       // Fall through
10522
10523     case VarDecl::DeclarationOnly:
10524       // It's only a declaration.
10525
10526       // Block scope. C99 6.7p7: If an identifier for an object is
10527       // declared with no linkage (C99 6.2.2p6), the type for the
10528       // object shall be complete.
10529       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10530           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10531           RequireCompleteType(Var->getLocation(), Type,
10532                               diag::err_typecheck_decl_incomplete_type))
10533         Var->setInvalidDecl();
10534
10535       // Make sure that the type is not abstract.
10536       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10537           RequireNonAbstractType(Var->getLocation(), Type,
10538                                  diag::err_abstract_type_in_decl,
10539                                  AbstractVariableType))
10540         Var->setInvalidDecl();
10541       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10542           Var->getStorageClass() == SC_PrivateExtern) {
10543         Diag(Var->getLocation(), diag::warn_private_extern);
10544         Diag(Var->getLocation(), diag::note_private_extern);
10545       }
10546
10547       return;
10548
10549     case VarDecl::TentativeDefinition:
10550       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10551       // object that has file scope without an initializer, and without a
10552       // storage-class specifier or with the storage-class specifier "static",
10553       // constitutes a tentative definition. Note: A tentative definition with
10554       // external linkage is valid (C99 6.2.2p5).
10555       if (!Var->isInvalidDecl()) {
10556         if (const IncompleteArrayType *ArrayT
10557                                     = Context.getAsIncompleteArrayType(Type)) {
10558           if (RequireCompleteType(Var->getLocation(),
10559                                   ArrayT->getElementType(),
10560                                   diag::err_illegal_decl_array_incomplete_type))
10561             Var->setInvalidDecl();
10562         } else if (Var->getStorageClass() == SC_Static) {
10563           // C99 6.9.2p3: If the declaration of an identifier for an object is
10564           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10565           // declared type shall not be an incomplete type.
10566           // NOTE: code such as the following
10567           //     static struct s;
10568           //     struct s { int a; };
10569           // is accepted by gcc. Hence here we issue a warning instead of
10570           // an error and we do not invalidate the static declaration.
10571           // NOTE: to avoid multiple warnings, only check the first declaration.
10572           if (Var->isFirstDecl())
10573             RequireCompleteType(Var->getLocation(), Type,
10574                                 diag::ext_typecheck_decl_incomplete_type);
10575         }
10576       }
10577
10578       // Record the tentative definition; we're done.
10579       if (!Var->isInvalidDecl())
10580         TentativeDefinitions.push_back(Var);
10581       return;
10582     }
10583
10584     // Provide a specific diagnostic for uninitialized variable
10585     // definitions with incomplete array type.
10586     if (Type->isIncompleteArrayType()) {
10587       Diag(Var->getLocation(),
10588            diag::err_typecheck_incomplete_array_needs_initializer);
10589       Var->setInvalidDecl();
10590       return;
10591     }
10592
10593     // Provide a specific diagnostic for uninitialized variable
10594     // definitions with reference type.
10595     if (Type->isReferenceType()) {
10596       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10597         << Var->getDeclName()
10598         << SourceRange(Var->getLocation(), Var->getLocation());
10599       Var->setInvalidDecl();
10600       return;
10601     }
10602
10603     // Do not attempt to type-check the default initializer for a
10604     // variable with dependent type.
10605     if (Type->isDependentType())
10606       return;
10607
10608     if (Var->isInvalidDecl())
10609       return;
10610
10611     if (!Var->hasAttr<AliasAttr>()) {
10612       if (RequireCompleteType(Var->getLocation(),
10613                               Context.getBaseElementType(Type),
10614                               diag::err_typecheck_decl_incomplete_type)) {
10615         Var->setInvalidDecl();
10616         return;
10617       }
10618     } else {
10619       return;
10620     }
10621
10622     // The variable can not have an abstract class type.
10623     if (RequireNonAbstractType(Var->getLocation(), Type,
10624                                diag::err_abstract_type_in_decl,
10625                                AbstractVariableType)) {
10626       Var->setInvalidDecl();
10627       return;
10628     }
10629
10630     // Check for jumps past the implicit initializer.  C++0x
10631     // clarifies that this applies to a "variable with automatic
10632     // storage duration", not a "local variable".
10633     // C++11 [stmt.dcl]p3
10634     //   A program that jumps from a point where a variable with automatic
10635     //   storage duration is not in scope to a point where it is in scope is
10636     //   ill-formed unless the variable has scalar type, class type with a
10637     //   trivial default constructor and a trivial destructor, a cv-qualified
10638     //   version of one of these types, or an array of one of the preceding
10639     //   types and is declared without an initializer.
10640     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10641       if (const RecordType *Record
10642             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10643         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10644         // Mark the function for further checking even if the looser rules of
10645         // C++11 do not require such checks, so that we can diagnose
10646         // incompatibilities with C++98.
10647         if (!CXXRecord->isPOD())
10648           getCurFunction()->setHasBranchProtectedScope();
10649       }
10650     }
10651
10652     // C++03 [dcl.init]p9:
10653     //   If no initializer is specified for an object, and the
10654     //   object is of (possibly cv-qualified) non-POD class type (or
10655     //   array thereof), the object shall be default-initialized; if
10656     //   the object is of const-qualified type, the underlying class
10657     //   type shall have a user-declared default
10658     //   constructor. Otherwise, if no initializer is specified for
10659     //   a non- static object, the object and its subobjects, if
10660     //   any, have an indeterminate initial value); if the object
10661     //   or any of its subobjects are of const-qualified type, the
10662     //   program is ill-formed.
10663     // C++0x [dcl.init]p11:
10664     //   If no initializer is specified for an object, the object is
10665     //   default-initialized; [...].
10666     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10667     InitializationKind Kind
10668       = InitializationKind::CreateDefault(Var->getLocation());
10669
10670     InitializationSequence InitSeq(*this, Entity, Kind, None);
10671     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10672     if (Init.isInvalid())
10673       Var->setInvalidDecl();
10674     else if (Init.get()) {
10675       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10676       // This is important for template substitution.
10677       Var->setInitStyle(VarDecl::CallInit);
10678     }
10679
10680     CheckCompleteVariableDeclaration(Var);
10681   }
10682 }
10683
10684 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10685   // If there is no declaration, there was an error parsing it. Ignore it.
10686   if (!D)
10687     return;
10688
10689   VarDecl *VD = dyn_cast<VarDecl>(D);
10690   if (!VD) {
10691     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10692     D->setInvalidDecl();
10693     return;
10694   }
10695
10696   VD->setCXXForRangeDecl(true);
10697
10698   // for-range-declaration cannot be given a storage class specifier.
10699   int Error = -1;
10700   switch (VD->getStorageClass()) {
10701   case SC_None:
10702     break;
10703   case SC_Extern:
10704     Error = 0;
10705     break;
10706   case SC_Static:
10707     Error = 1;
10708     break;
10709   case SC_PrivateExtern:
10710     Error = 2;
10711     break;
10712   case SC_Auto:
10713     Error = 3;
10714     break;
10715   case SC_Register:
10716     Error = 4;
10717     break;
10718   }
10719   if (Error != -1) {
10720     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10721       << VD->getDeclName() << Error;
10722     D->setInvalidDecl();
10723   }
10724 }
10725
10726 StmtResult
10727 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10728                                  IdentifierInfo *Ident,
10729                                  ParsedAttributes &Attrs,
10730                                  SourceLocation AttrEnd) {
10731   // C++1y [stmt.iter]p1:
10732   //   A range-based for statement of the form
10733   //      for ( for-range-identifier : for-range-initializer ) statement
10734   //   is equivalent to
10735   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10736   DeclSpec DS(Attrs.getPool().getFactory());
10737
10738   const char *PrevSpec;
10739   unsigned DiagID;
10740   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10741                      getPrintingPolicy());
10742
10743   Declarator D(DS, Declarator::ForContext);
10744   D.SetIdentifier(Ident, IdentLoc);
10745   D.takeAttributes(Attrs, AttrEnd);
10746
10747   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10748   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10749                 EmptyAttrs, IdentLoc);
10750   Decl *Var = ActOnDeclarator(S, D);
10751   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10752   FinalizeDeclaration(Var);
10753   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10754                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10755 }
10756
10757 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10758   if (var->isInvalidDecl()) return;
10759
10760   if (getLangOpts().OpenCL) {
10761     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10762     // initialiser
10763     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10764         !var->hasInit()) {
10765       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10766           << 1 /*Init*/;
10767       var->setInvalidDecl();
10768       return;
10769     }
10770   }
10771
10772   // In Objective-C, don't allow jumps past the implicit initialization of a
10773   // local retaining variable.
10774   if (getLangOpts().ObjC1 &&
10775       var->hasLocalStorage()) {
10776     switch (var->getType().getObjCLifetime()) {
10777     case Qualifiers::OCL_None:
10778     case Qualifiers::OCL_ExplicitNone:
10779     case Qualifiers::OCL_Autoreleasing:
10780       break;
10781
10782     case Qualifiers::OCL_Weak:
10783     case Qualifiers::OCL_Strong:
10784       getCurFunction()->setHasBranchProtectedScope();
10785       break;
10786     }
10787   }
10788
10789   // Warn about externally-visible variables being defined without a
10790   // prior declaration.  We only want to do this for global
10791   // declarations, but we also specifically need to avoid doing it for
10792   // class members because the linkage of an anonymous class can
10793   // change if it's later given a typedef name.
10794   if (var->isThisDeclarationADefinition() &&
10795       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10796       var->isExternallyVisible() && var->hasLinkage() &&
10797       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10798                                   var->getLocation())) {
10799     // Find a previous declaration that's not a definition.
10800     VarDecl *prev = var->getPreviousDecl();
10801     while (prev && prev->isThisDeclarationADefinition())
10802       prev = prev->getPreviousDecl();
10803
10804     if (!prev)
10805       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10806   }
10807
10808   // Cache the result of checking for constant initialization.
10809   Optional<bool> CacheHasConstInit;
10810   const Expr *CacheCulprit;
10811   auto checkConstInit = [&]() mutable {
10812     if (!CacheHasConstInit)
10813       CacheHasConstInit = var->getInit()->isConstantInitializer(
10814             Context, var->getType()->isReferenceType(), &CacheCulprit);
10815     return *CacheHasConstInit;
10816   };
10817
10818   if (var->getTLSKind() == VarDecl::TLS_Static) {
10819     if (var->getType().isDestructedType()) {
10820       // GNU C++98 edits for __thread, [basic.start.term]p3:
10821       //   The type of an object with thread storage duration shall not
10822       //   have a non-trivial destructor.
10823       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10824       if (getLangOpts().CPlusPlus11)
10825         Diag(var->getLocation(), diag::note_use_thread_local);
10826     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
10827       if (!checkConstInit()) {
10828         // GNU C++98 edits for __thread, [basic.start.init]p4:
10829         //   An object of thread storage duration shall not require dynamic
10830         //   initialization.
10831         // FIXME: Need strict checking here.
10832         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
10833           << CacheCulprit->getSourceRange();
10834         if (getLangOpts().CPlusPlus11)
10835           Diag(var->getLocation(), diag::note_use_thread_local);
10836       }
10837     }
10838   }
10839
10840   // Apply section attributes and pragmas to global variables.
10841   bool GlobalStorage = var->hasGlobalStorage();
10842   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10843       !inTemplateInstantiation()) {
10844     PragmaStack<StringLiteral *> *Stack = nullptr;
10845     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10846     if (var->getType().isConstQualified())
10847       Stack = &ConstSegStack;
10848     else if (!var->getInit()) {
10849       Stack = &BSSSegStack;
10850       SectionFlags |= ASTContext::PSF_Write;
10851     } else {
10852       Stack = &DataSegStack;
10853       SectionFlags |= ASTContext::PSF_Write;
10854     }
10855     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10856       var->addAttr(SectionAttr::CreateImplicit(
10857           Context, SectionAttr::Declspec_allocate,
10858           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10859     }
10860     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10861       if (UnifySection(SA->getName(), SectionFlags, var))
10862         var->dropAttr<SectionAttr>();
10863
10864     // Apply the init_seg attribute if this has an initializer.  If the
10865     // initializer turns out to not be dynamic, we'll end up ignoring this
10866     // attribute.
10867     if (CurInitSeg && var->getInit())
10868       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10869                                                CurInitSegLoc));
10870   }
10871
10872   // All the following checks are C++ only.
10873   if (!getLangOpts().CPlusPlus) {
10874       // If this variable must be emitted, add it as an initializer for the
10875       // current module.
10876      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10877        Context.addModuleInitializer(ModuleScopes.back().Module, var);
10878      return;
10879   }
10880
10881   if (auto *DD = dyn_cast<DecompositionDecl>(var))
10882     CheckCompleteDecompositionDeclaration(DD);
10883
10884   QualType type = var->getType();
10885   if (type->isDependentType()) return;
10886
10887   // __block variables might require us to capture a copy-initializer.
10888   if (var->hasAttr<BlocksAttr>()) {
10889     // It's currently invalid to ever have a __block variable with an
10890     // array type; should we diagnose that here?
10891
10892     // Regardless, we don't want to ignore array nesting when
10893     // constructing this copy.
10894     if (type->isStructureOrClassType()) {
10895       EnterExpressionEvaluationContext scope(
10896           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
10897       SourceLocation poi = var->getLocation();
10898       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10899       ExprResult result
10900         = PerformMoveOrCopyInitialization(
10901             InitializedEntity::InitializeBlock(poi, type, false),
10902             var, var->getType(), varRef, /*AllowNRVO=*/true);
10903       if (!result.isInvalid()) {
10904         result = MaybeCreateExprWithCleanups(result);
10905         Expr *init = result.getAs<Expr>();
10906         Context.setBlockVarCopyInits(var, init);
10907       }
10908     }
10909   }
10910
10911   Expr *Init = var->getInit();
10912   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10913   QualType baseType = Context.getBaseElementType(type);
10914
10915   if (!var->getDeclContext()->isDependentContext() &&
10916       Init && !Init->isValueDependent()) {
10917
10918     if (var->isConstexpr()) {
10919       SmallVector<PartialDiagnosticAt, 8> Notes;
10920       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10921         SourceLocation DiagLoc = var->getLocation();
10922         // If the note doesn't add any useful information other than a source
10923         // location, fold it into the primary diagnostic.
10924         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10925               diag::note_invalid_subexpr_in_const_expr) {
10926           DiagLoc = Notes[0].first;
10927           Notes.clear();
10928         }
10929         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10930           << var << Init->getSourceRange();
10931         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10932           Diag(Notes[I].first, Notes[I].second);
10933       }
10934     } else if (var->isUsableInConstantExpressions(Context)) {
10935       // Check whether the initializer of a const variable of integral or
10936       // enumeration type is an ICE now, since we can't tell whether it was
10937       // initialized by a constant expression if we check later.
10938       var->checkInitIsICE();
10939     }
10940
10941     // Don't emit further diagnostics about constexpr globals since they
10942     // were just diagnosed.
10943     if (!var->isConstexpr() && GlobalStorage &&
10944             var->hasAttr<RequireConstantInitAttr>()) {
10945       // FIXME: Need strict checking in C++03 here.
10946       bool DiagErr = getLangOpts().CPlusPlus11
10947           ? !var->checkInitIsICE() : !checkConstInit();
10948       if (DiagErr) {
10949         auto attr = var->getAttr<RequireConstantInitAttr>();
10950         Diag(var->getLocation(), diag::err_require_constant_init_failed)
10951           << Init->getSourceRange();
10952         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
10953           << attr->getRange();
10954       }
10955     }
10956     else if (!var->isConstexpr() && IsGlobal &&
10957              !getDiagnostics().isIgnored(diag::warn_global_constructor,
10958                                     var->getLocation())) {
10959       // Warn about globals which don't have a constant initializer.  Don't
10960       // warn about globals with a non-trivial destructor because we already
10961       // warned about them.
10962       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10963       if (!(RD && !RD->hasTrivialDestructor())) {
10964         if (!checkConstInit())
10965           Diag(var->getLocation(), diag::warn_global_constructor)
10966             << Init->getSourceRange();
10967       }
10968     }
10969   }
10970
10971   // Require the destructor.
10972   if (const RecordType *recordType = baseType->getAs<RecordType>())
10973     FinalizeVarWithDestructor(var, recordType);
10974
10975   // If this variable must be emitted, add it as an initializer for the current
10976   // module.
10977   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10978     Context.addModuleInitializer(ModuleScopes.back().Module, var);
10979 }
10980
10981 /// \brief Determines if a variable's alignment is dependent.
10982 static bool hasDependentAlignment(VarDecl *VD) {
10983   if (VD->getType()->isDependentType())
10984     return true;
10985   for (auto *I : VD->specific_attrs<AlignedAttr>())
10986     if (I->isAlignmentDependent())
10987       return true;
10988   return false;
10989 }
10990
10991 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10992 /// any semantic actions necessary after any initializer has been attached.
10993 void
10994 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10995   // Note that we are no longer parsing the initializer for this declaration.
10996   ParsingInitForAutoVars.erase(ThisDecl);
10997
10998   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10999   if (!VD)
11000     return;
11001
11002   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11003     for (auto *BD : DD->bindings()) {
11004       FinalizeDeclaration(BD);
11005     }
11006   }
11007
11008   checkAttributesAfterMerging(*this, *VD);
11009
11010   // Perform TLS alignment check here after attributes attached to the variable
11011   // which may affect the alignment have been processed. Only perform the check
11012   // if the target has a maximum TLS alignment (zero means no constraints).
11013   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11014     // Protect the check so that it's not performed on dependent types and
11015     // dependent alignments (we can't determine the alignment in that case).
11016     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11017         !VD->isInvalidDecl()) {
11018       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11019       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11020         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11021           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11022           << (unsigned)MaxAlignChars.getQuantity();
11023       }
11024     }
11025   }
11026
11027   if (VD->isStaticLocal()) {
11028     if (FunctionDecl *FD =
11029             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11030       // Static locals inherit dll attributes from their function.
11031       if (Attr *A = getDLLAttr(FD)) {
11032         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11033         NewAttr->setInherited(true);
11034         VD->addAttr(NewAttr);
11035       }
11036       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11037       // function, only __shared__ variables may be declared with
11038       // static storage class.
11039       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11040           CUDADiagIfDeviceCode(VD->getLocation(),
11041                                diag::err_device_static_local_var)
11042               << CurrentCUDATarget())
11043         VD->setInvalidDecl();
11044     }
11045   }
11046
11047   // Perform check for initializers of device-side global variables.
11048   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11049   // 7.5). We must also apply the same checks to all __shared__
11050   // variables whether they are local or not. CUDA also allows
11051   // constant initializers for __constant__ and __device__ variables.
11052   if (getLangOpts().CUDA) {
11053     const Expr *Init = VD->getInit();
11054     if (Init && VD->hasGlobalStorage()) {
11055       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11056           VD->hasAttr<CUDASharedAttr>()) {
11057         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11058         bool AllowedInit = false;
11059         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11060           AllowedInit =
11061               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11062         // We'll allow constant initializers even if it's a non-empty
11063         // constructor according to CUDA rules. This deviates from NVCC,
11064         // but allows us to handle things like constexpr constructors.
11065         if (!AllowedInit &&
11066             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11067           AllowedInit = VD->getInit()->isConstantInitializer(
11068               Context, VD->getType()->isReferenceType());
11069
11070         // Also make sure that destructor, if there is one, is empty.
11071         if (AllowedInit)
11072           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11073             AllowedInit =
11074                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11075
11076         if (!AllowedInit) {
11077           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11078                                       ? diag::err_shared_var_init
11079                                       : diag::err_dynamic_var_init)
11080               << Init->getSourceRange();
11081           VD->setInvalidDecl();
11082         }
11083       } else {
11084         // This is a host-side global variable.  Check that the initializer is
11085         // callable from the host side.
11086         const FunctionDecl *InitFn = nullptr;
11087         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11088           InitFn = CE->getConstructor();
11089         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11090           InitFn = CE->getDirectCallee();
11091         }
11092         if (InitFn) {
11093           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11094           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11095             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11096                 << InitFnTarget << InitFn;
11097             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11098             VD->setInvalidDecl();
11099           }
11100         }
11101       }
11102     }
11103   }
11104
11105   // Grab the dllimport or dllexport attribute off of the VarDecl.
11106   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11107
11108   // Imported static data members cannot be defined out-of-line.
11109   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11110     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11111         VD->isThisDeclarationADefinition()) {
11112       // We allow definitions of dllimport class template static data members
11113       // with a warning.
11114       CXXRecordDecl *Context =
11115         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11116       bool IsClassTemplateMember =
11117           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11118           Context->getDescribedClassTemplate();
11119
11120       Diag(VD->getLocation(),
11121            IsClassTemplateMember
11122                ? diag::warn_attribute_dllimport_static_field_definition
11123                : diag::err_attribute_dllimport_static_field_definition);
11124       Diag(IA->getLocation(), diag::note_attribute);
11125       if (!IsClassTemplateMember)
11126         VD->setInvalidDecl();
11127     }
11128   }
11129
11130   // dllimport/dllexport variables cannot be thread local, their TLS index
11131   // isn't exported with the variable.
11132   if (DLLAttr && VD->getTLSKind()) {
11133     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11134     if (F && getDLLAttr(F)) {
11135       assert(VD->isStaticLocal());
11136       // But if this is a static local in a dlimport/dllexport function, the
11137       // function will never be inlined, which means the var would never be
11138       // imported, so having it marked import/export is safe.
11139     } else {
11140       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11141                                                                     << DLLAttr;
11142       VD->setInvalidDecl();
11143     }
11144   }
11145
11146   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11147     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11148       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11149       VD->dropAttr<UsedAttr>();
11150     }
11151   }
11152
11153   const DeclContext *DC = VD->getDeclContext();
11154   // If there's a #pragma GCC visibility in scope, and this isn't a class
11155   // member, set the visibility of this variable.
11156   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11157     AddPushedVisibilityAttribute(VD);
11158
11159   // FIXME: Warn on unused templates.
11160   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
11161       !isa<VarTemplatePartialSpecializationDecl>(VD))
11162     MarkUnusedFileScopedDecl(VD);
11163
11164   // Now we have parsed the initializer and can update the table of magic
11165   // tag values.
11166   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11167       !VD->getType()->isIntegralOrEnumerationType())
11168     return;
11169
11170   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11171     const Expr *MagicValueExpr = VD->getInit();
11172     if (!MagicValueExpr) {
11173       continue;
11174     }
11175     llvm::APSInt MagicValueInt;
11176     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11177       Diag(I->getRange().getBegin(),
11178            diag::err_type_tag_for_datatype_not_ice)
11179         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11180       continue;
11181     }
11182     if (MagicValueInt.getActiveBits() > 64) {
11183       Diag(I->getRange().getBegin(),
11184            diag::err_type_tag_for_datatype_too_large)
11185         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11186       continue;
11187     }
11188     uint64_t MagicValue = MagicValueInt.getZExtValue();
11189     RegisterTypeTagForDatatype(I->getArgumentKind(),
11190                                MagicValue,
11191                                I->getMatchingCType(),
11192                                I->getLayoutCompatible(),
11193                                I->getMustBeNull());
11194   }
11195 }
11196
11197 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11198   auto *VD = dyn_cast<VarDecl>(DD);
11199   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11200 }
11201
11202 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11203                                                    ArrayRef<Decl *> Group) {
11204   SmallVector<Decl*, 8> Decls;
11205
11206   if (DS.isTypeSpecOwned())
11207     Decls.push_back(DS.getRepAsDecl());
11208
11209   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11210   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11211   bool DiagnosedMultipleDecomps = false;
11212   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11213   bool DiagnosedNonDeducedAuto = false;
11214
11215   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11216     if (Decl *D = Group[i]) {
11217       // For declarators, there are some additional syntactic-ish checks we need
11218       // to perform.
11219       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11220         if (!FirstDeclaratorInGroup)
11221           FirstDeclaratorInGroup = DD;
11222         if (!FirstDecompDeclaratorInGroup)
11223           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11224         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11225             !hasDeducedAuto(DD))
11226           FirstNonDeducedAutoInGroup = DD;
11227
11228         if (FirstDeclaratorInGroup != DD) {
11229           // A decomposition declaration cannot be combined with any other
11230           // declaration in the same group.
11231           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11232             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11233                  diag::err_decomp_decl_not_alone)
11234                 << FirstDeclaratorInGroup->getSourceRange()
11235                 << DD->getSourceRange();
11236             DiagnosedMultipleDecomps = true;
11237           }
11238
11239           // A declarator that uses 'auto' in any way other than to declare a
11240           // variable with a deduced type cannot be combined with any other
11241           // declarator in the same group.
11242           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11243             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11244                  diag::err_auto_non_deduced_not_alone)
11245                 << FirstNonDeducedAutoInGroup->getType()
11246                        ->hasAutoForTrailingReturnType()
11247                 << FirstDeclaratorInGroup->getSourceRange()
11248                 << DD->getSourceRange();
11249             DiagnosedNonDeducedAuto = true;
11250           }
11251         }
11252       }
11253
11254       Decls.push_back(D);
11255     }
11256   }
11257
11258   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11259     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11260       handleTagNumbering(Tag, S);
11261       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11262           getLangOpts().CPlusPlus)
11263         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11264     }
11265   }
11266
11267   return BuildDeclaratorGroup(Decls);
11268 }
11269
11270 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11271 /// group, performing any necessary semantic checking.
11272 Sema::DeclGroupPtrTy
11273 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11274   // C++14 [dcl.spec.auto]p7: (DR1347)
11275   //   If the type that replaces the placeholder type is not the same in each
11276   //   deduction, the program is ill-formed.
11277   if (Group.size() > 1) {
11278     QualType Deduced;
11279     VarDecl *DeducedDecl = nullptr;
11280     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11281       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11282       if (!D || D->isInvalidDecl())
11283         break;
11284       DeducedType *DT = D->getType()->getContainedDeducedType();
11285       if (!DT || DT->getDeducedType().isNull())
11286         continue;
11287       if (Deduced.isNull()) {
11288         Deduced = DT->getDeducedType();
11289         DeducedDecl = D;
11290       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11291         auto *AT = dyn_cast<AutoType>(DT);
11292         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11293              diag::err_auto_different_deductions)
11294           << (AT ? (unsigned)AT->getKeyword() : 3)
11295           << Deduced << DeducedDecl->getDeclName()
11296           << DT->getDeducedType() << D->getDeclName()
11297           << DeducedDecl->getInit()->getSourceRange()
11298           << D->getInit()->getSourceRange();
11299         D->setInvalidDecl();
11300         break;
11301       }
11302     }
11303   }
11304
11305   ActOnDocumentableDecls(Group);
11306
11307   return DeclGroupPtrTy::make(
11308       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11309 }
11310
11311 void Sema::ActOnDocumentableDecl(Decl *D) {
11312   ActOnDocumentableDecls(D);
11313 }
11314
11315 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11316   // Don't parse the comment if Doxygen diagnostics are ignored.
11317   if (Group.empty() || !Group[0])
11318     return;
11319
11320   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11321                       Group[0]->getLocation()) &&
11322       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11323                       Group[0]->getLocation()))
11324     return;
11325
11326   if (Group.size() >= 2) {
11327     // This is a decl group.  Normally it will contain only declarations
11328     // produced from declarator list.  But in case we have any definitions or
11329     // additional declaration references:
11330     //   'typedef struct S {} S;'
11331     //   'typedef struct S *S;'
11332     //   'struct S *pS;'
11333     // FinalizeDeclaratorGroup adds these as separate declarations.
11334     Decl *MaybeTagDecl = Group[0];
11335     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11336       Group = Group.slice(1);
11337     }
11338   }
11339
11340   // See if there are any new comments that are not attached to a decl.
11341   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11342   if (!Comments.empty() &&
11343       !Comments.back()->isAttached()) {
11344     // There is at least one comment that not attached to a decl.
11345     // Maybe it should be attached to one of these decls?
11346     //
11347     // Note that this way we pick up not only comments that precede the
11348     // declaration, but also comments that *follow* the declaration -- thanks to
11349     // the lookahead in the lexer: we've consumed the semicolon and looked
11350     // ahead through comments.
11351     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11352       Context.getCommentForDecl(Group[i], &PP);
11353   }
11354 }
11355
11356 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11357 /// to introduce parameters into function prototype scope.
11358 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11359   const DeclSpec &DS = D.getDeclSpec();
11360
11361   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11362
11363   // C++03 [dcl.stc]p2 also permits 'auto'.
11364   StorageClass SC = SC_None;
11365   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11366     SC = SC_Register;
11367   } else if (getLangOpts().CPlusPlus &&
11368              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11369     SC = SC_Auto;
11370   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11371     Diag(DS.getStorageClassSpecLoc(),
11372          diag::err_invalid_storage_class_in_func_decl);
11373     D.getMutableDeclSpec().ClearStorageClassSpecs();
11374   }
11375
11376   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11377     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11378       << DeclSpec::getSpecifierName(TSCS);
11379   if (DS.isInlineSpecified())
11380     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11381         << getLangOpts().CPlusPlus1z;
11382   if (DS.isConstexprSpecified())
11383     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11384       << 0;
11385   if (DS.isConceptSpecified())
11386     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11387
11388   DiagnoseFunctionSpecifiers(DS);
11389
11390   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11391   QualType parmDeclType = TInfo->getType();
11392
11393   if (getLangOpts().CPlusPlus) {
11394     // Check that there are no default arguments inside the type of this
11395     // parameter.
11396     CheckExtraCXXDefaultArguments(D);
11397
11398     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11399     if (D.getCXXScopeSpec().isSet()) {
11400       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11401         << D.getCXXScopeSpec().getRange();
11402       D.getCXXScopeSpec().clear();
11403     }
11404   }
11405
11406   // Ensure we have a valid name
11407   IdentifierInfo *II = nullptr;
11408   if (D.hasName()) {
11409     II = D.getIdentifier();
11410     if (!II) {
11411       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11412         << GetNameForDeclarator(D).getName();
11413       D.setInvalidType(true);
11414     }
11415   }
11416
11417   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11418   if (II) {
11419     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11420                    ForRedeclaration);
11421     LookupName(R, S);
11422     if (R.isSingleResult()) {
11423       NamedDecl *PrevDecl = R.getFoundDecl();
11424       if (PrevDecl->isTemplateParameter()) {
11425         // Maybe we will complain about the shadowed template parameter.
11426         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11427         // Just pretend that we didn't see the previous declaration.
11428         PrevDecl = nullptr;
11429       } else if (S->isDeclScope(PrevDecl)) {
11430         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11431         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11432
11433         // Recover by removing the name
11434         II = nullptr;
11435         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11436         D.setInvalidType(true);
11437       }
11438     }
11439   }
11440
11441   // Temporarily put parameter variables in the translation unit, not
11442   // the enclosing context.  This prevents them from accidentally
11443   // looking like class members in C++.
11444   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11445                                     D.getLocStart(),
11446                                     D.getIdentifierLoc(), II,
11447                                     parmDeclType, TInfo,
11448                                     SC);
11449
11450   if (D.isInvalidType())
11451     New->setInvalidDecl();
11452
11453   assert(S->isFunctionPrototypeScope());
11454   assert(S->getFunctionPrototypeDepth() >= 1);
11455   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11456                     S->getNextFunctionPrototypeIndex());
11457
11458   // Add the parameter declaration into this scope.
11459   S->AddDecl(New);
11460   if (II)
11461     IdResolver.AddDecl(New);
11462
11463   ProcessDeclAttributes(S, New, D);
11464
11465   if (D.getDeclSpec().isModulePrivateSpecified())
11466     Diag(New->getLocation(), diag::err_module_private_local)
11467       << 1 << New->getDeclName()
11468       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11469       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11470
11471   if (New->hasAttr<BlocksAttr>()) {
11472     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11473   }
11474   return New;
11475 }
11476
11477 /// \brief Synthesizes a variable for a parameter arising from a
11478 /// typedef.
11479 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11480                                               SourceLocation Loc,
11481                                               QualType T) {
11482   /* FIXME: setting StartLoc == Loc.
11483      Would it be worth to modify callers so as to provide proper source
11484      location for the unnamed parameters, embedding the parameter's type? */
11485   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11486                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11487                                            SC_None, nullptr);
11488   Param->setImplicit();
11489   return Param;
11490 }
11491
11492 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11493   // Don't diagnose unused-parameter errors in template instantiations; we
11494   // will already have done so in the template itself.
11495   if (inTemplateInstantiation())
11496     return;
11497
11498   for (const ParmVarDecl *Parameter : Parameters) {
11499     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11500         !Parameter->hasAttr<UnusedAttr>()) {
11501       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11502         << Parameter->getDeclName();
11503     }
11504   }
11505 }
11506
11507 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11508     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11509   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11510     return;
11511
11512   // Warn if the return value is pass-by-value and larger than the specified
11513   // threshold.
11514   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11515     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11516     if (Size > LangOpts.NumLargeByValueCopy)
11517       Diag(D->getLocation(), diag::warn_return_value_size)
11518           << D->getDeclName() << Size;
11519   }
11520
11521   // Warn if any parameter is pass-by-value and larger than the specified
11522   // threshold.
11523   for (const ParmVarDecl *Parameter : Parameters) {
11524     QualType T = Parameter->getType();
11525     if (T->isDependentType() || !T.isPODType(Context))
11526       continue;
11527     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11528     if (Size > LangOpts.NumLargeByValueCopy)
11529       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11530           << Parameter->getDeclName() << Size;
11531   }
11532 }
11533
11534 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11535                                   SourceLocation NameLoc, IdentifierInfo *Name,
11536                                   QualType T, TypeSourceInfo *TSInfo,
11537                                   StorageClass SC) {
11538   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11539   if (getLangOpts().ObjCAutoRefCount &&
11540       T.getObjCLifetime() == Qualifiers::OCL_None &&
11541       T->isObjCLifetimeType()) {
11542
11543     Qualifiers::ObjCLifetime lifetime;
11544
11545     // Special cases for arrays:
11546     //   - if it's const, use __unsafe_unretained
11547     //   - otherwise, it's an error
11548     if (T->isArrayType()) {
11549       if (!T.isConstQualified()) {
11550         DelayedDiagnostics.add(
11551             sema::DelayedDiagnostic::makeForbiddenType(
11552             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11553       }
11554       lifetime = Qualifiers::OCL_ExplicitNone;
11555     } else {
11556       lifetime = T->getObjCARCImplicitLifetime();
11557     }
11558     T = Context.getLifetimeQualifiedType(T, lifetime);
11559   }
11560
11561   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11562                                          Context.getAdjustedParameterType(T),
11563                                          TSInfo, SC, nullptr);
11564
11565   // Parameters can not be abstract class types.
11566   // For record types, this is done by the AbstractClassUsageDiagnoser once
11567   // the class has been completely parsed.
11568   if (!CurContext->isRecord() &&
11569       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11570                              AbstractParamType))
11571     New->setInvalidDecl();
11572
11573   // Parameter declarators cannot be interface types. All ObjC objects are
11574   // passed by reference.
11575   if (T->isObjCObjectType()) {
11576     SourceLocation TypeEndLoc =
11577         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11578     Diag(NameLoc,
11579          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11580       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11581     T = Context.getObjCObjectPointerType(T);
11582     New->setType(T);
11583   }
11584
11585   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11586   // duration shall not be qualified by an address-space qualifier."
11587   // Since all parameters have automatic store duration, they can not have
11588   // an address space.
11589   if (T.getAddressSpace() != 0) {
11590     // OpenCL allows function arguments declared to be an array of a type
11591     // to be qualified with an address space.
11592     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11593       Diag(NameLoc, diag::err_arg_with_address_space);
11594       New->setInvalidDecl();
11595     }
11596   }
11597
11598   return New;
11599 }
11600
11601 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11602                                            SourceLocation LocAfterDecls) {
11603   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11604
11605   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11606   // for a K&R function.
11607   if (!FTI.hasPrototype) {
11608     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11609       --i;
11610       if (FTI.Params[i].Param == nullptr) {
11611         SmallString<256> Code;
11612         llvm::raw_svector_ostream(Code)
11613             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11614         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11615             << FTI.Params[i].Ident
11616             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11617
11618         // Implicitly declare the argument as type 'int' for lack of a better
11619         // type.
11620         AttributeFactory attrs;
11621         DeclSpec DS(attrs);
11622         const char* PrevSpec; // unused
11623         unsigned DiagID; // unused
11624         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11625                            DiagID, Context.getPrintingPolicy());
11626         // Use the identifier location for the type source range.
11627         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11628         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11629         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11630         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11631         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11632       }
11633     }
11634   }
11635 }
11636
11637 Decl *
11638 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11639                               MultiTemplateParamsArg TemplateParameterLists,
11640                               SkipBodyInfo *SkipBody) {
11641   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11642   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11643   Scope *ParentScope = FnBodyScope->getParent();
11644
11645   D.setFunctionDefinitionKind(FDK_Definition);
11646   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11647   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11648 }
11649
11650 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11651   Consumer.HandleInlineFunctionDefinition(D);
11652 }
11653
11654 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11655                              const FunctionDecl*& PossibleZeroParamPrototype) {
11656   // Don't warn about invalid declarations.
11657   if (FD->isInvalidDecl())
11658     return false;
11659
11660   // Or declarations that aren't global.
11661   if (!FD->isGlobal())
11662     return false;
11663
11664   // Don't warn about C++ member functions.
11665   if (isa<CXXMethodDecl>(FD))
11666     return false;
11667
11668   // Don't warn about 'main'.
11669   if (FD->isMain())
11670     return false;
11671
11672   // Don't warn about inline functions.
11673   if (FD->isInlined())
11674     return false;
11675
11676   // Don't warn about function templates.
11677   if (FD->getDescribedFunctionTemplate())
11678     return false;
11679
11680   // Don't warn about function template specializations.
11681   if (FD->isFunctionTemplateSpecialization())
11682     return false;
11683
11684   // Don't warn for OpenCL kernels.
11685   if (FD->hasAttr<OpenCLKernelAttr>())
11686     return false;
11687
11688   // Don't warn on explicitly deleted functions.
11689   if (FD->isDeleted())
11690     return false;
11691
11692   bool MissingPrototype = true;
11693   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11694        Prev; Prev = Prev->getPreviousDecl()) {
11695     // Ignore any declarations that occur in function or method
11696     // scope, because they aren't visible from the header.
11697     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11698       continue;
11699
11700     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11701     if (FD->getNumParams() == 0)
11702       PossibleZeroParamPrototype = Prev;
11703     break;
11704   }
11705
11706   return MissingPrototype;
11707 }
11708
11709 void
11710 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11711                                    const FunctionDecl *EffectiveDefinition,
11712                                    SkipBodyInfo *SkipBody) {
11713   const FunctionDecl *Definition = EffectiveDefinition;
11714   if (!Definition)
11715     if (!FD->isDefined(Definition))
11716       return;
11717
11718   if (canRedefineFunction(Definition, getLangOpts()))
11719     return;
11720
11721   // If we don't have a visible definition of the function, and it's inline or
11722   // a template, skip the new definition.
11723   if (SkipBody && !hasVisibleDefinition(Definition) &&
11724       (Definition->getFormalLinkage() == InternalLinkage ||
11725        Definition->isInlined() ||
11726        Definition->getDescribedFunctionTemplate() ||
11727        Definition->getNumTemplateParameterLists())) {
11728     SkipBody->ShouldSkip = true;
11729     if (auto *TD = Definition->getDescribedFunctionTemplate())
11730       makeMergedDefinitionVisible(TD, FD->getLocation());
11731     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11732                                 FD->getLocation());
11733     return;
11734   }
11735
11736   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11737       Definition->getStorageClass() == SC_Extern)
11738     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11739         << FD->getDeclName() << getLangOpts().CPlusPlus;
11740   else
11741     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11742
11743   Diag(Definition->getLocation(), diag::note_previous_definition);
11744   FD->setInvalidDecl();
11745 }
11746
11747 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11748                                    Sema &S) {
11749   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11750
11751   LambdaScopeInfo *LSI = S.PushLambdaScope();
11752   LSI->CallOperator = CallOperator;
11753   LSI->Lambda = LambdaClass;
11754   LSI->ReturnType = CallOperator->getReturnType();
11755   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11756
11757   if (LCD == LCD_None)
11758     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11759   else if (LCD == LCD_ByCopy)
11760     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11761   else if (LCD == LCD_ByRef)
11762     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11763   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11764
11765   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11766   LSI->Mutable = !CallOperator->isConst();
11767
11768   // Add the captures to the LSI so they can be noted as already
11769   // captured within tryCaptureVar.
11770   auto I = LambdaClass->field_begin();
11771   for (const auto &C : LambdaClass->captures()) {
11772     if (C.capturesVariable()) {
11773       VarDecl *VD = C.getCapturedVar();
11774       if (VD->isInitCapture())
11775         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11776       QualType CaptureType = VD->getType();
11777       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11778       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11779           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11780           /*EllipsisLoc*/C.isPackExpansion()
11781                          ? C.getEllipsisLoc() : SourceLocation(),
11782           CaptureType, /*Expr*/ nullptr);
11783
11784     } else if (C.capturesThis()) {
11785       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11786                               /*Expr*/ nullptr,
11787                               C.getCaptureKind() == LCK_StarThis);
11788     } else {
11789       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11790     }
11791     ++I;
11792   }
11793 }
11794
11795 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11796                                     SkipBodyInfo *SkipBody) {
11797   if (!D)
11798     return D;
11799   FunctionDecl *FD = nullptr;
11800
11801   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11802     FD = FunTmpl->getTemplatedDecl();
11803   else
11804     FD = cast<FunctionDecl>(D);
11805
11806   // Check for defining attributes before the check for redefinition.
11807   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
11808     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
11809     FD->dropAttr<AliasAttr>();
11810     FD->setInvalidDecl();
11811   }
11812   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
11813     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
11814     FD->dropAttr<IFuncAttr>();
11815     FD->setInvalidDecl();
11816   }
11817
11818   // See if this is a redefinition.
11819   if (!FD->isLateTemplateParsed()) {
11820     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11821
11822     // If we're skipping the body, we're done. Don't enter the scope.
11823     if (SkipBody && SkipBody->ShouldSkip)
11824       return D;
11825   }
11826
11827   // Mark this function as "will have a body eventually".  This lets users to
11828   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
11829   // this function.
11830   FD->setWillHaveBody();
11831
11832   // If we are instantiating a generic lambda call operator, push
11833   // a LambdaScopeInfo onto the function stack.  But use the information
11834   // that's already been calculated (ActOnLambdaExpr) to prime the current
11835   // LambdaScopeInfo.
11836   // When the template operator is being specialized, the LambdaScopeInfo,
11837   // has to be properly restored so that tryCaptureVariable doesn't try
11838   // and capture any new variables. In addition when calculating potential
11839   // captures during transformation of nested lambdas, it is necessary to
11840   // have the LSI properly restored.
11841   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11842     assert(inTemplateInstantiation() &&
11843            "There should be an active template instantiation on the stack "
11844            "when instantiating a generic lambda!");
11845     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11846   } else {
11847     // Enter a new function scope
11848     PushFunctionScope();
11849   }
11850
11851   // Builtin functions cannot be defined.
11852   if (unsigned BuiltinID = FD->getBuiltinID()) {
11853     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11854         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11855       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11856       FD->setInvalidDecl();
11857     }
11858   }
11859
11860   // The return type of a function definition must be complete
11861   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11862   QualType ResultType = FD->getReturnType();
11863   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11864       !FD->isInvalidDecl() &&
11865       RequireCompleteType(FD->getLocation(), ResultType,
11866                           diag::err_func_def_incomplete_result))
11867     FD->setInvalidDecl();
11868
11869   if (FnBodyScope)
11870     PushDeclContext(FnBodyScope, FD);
11871
11872   // Check the validity of our function parameters
11873   CheckParmsForFunctionDef(FD->parameters(),
11874                            /*CheckParameterNames=*/true);
11875
11876   // Add non-parameter declarations already in the function to the current
11877   // scope.
11878   if (FnBodyScope) {
11879     for (Decl *NPD : FD->decls()) {
11880       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
11881       if (!NonParmDecl)
11882         continue;
11883       assert(!isa<ParmVarDecl>(NonParmDecl) &&
11884              "parameters should not be in newly created FD yet");
11885
11886       // If the decl has a name, make it accessible in the current scope.
11887       if (NonParmDecl->getDeclName())
11888         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
11889
11890       // Similarly, dive into enums and fish their constants out, making them
11891       // accessible in this scope.
11892       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
11893         for (auto *EI : ED->enumerators())
11894           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11895       }
11896     }
11897   }
11898
11899   // Introduce our parameters into the function scope
11900   for (auto Param : FD->parameters()) {
11901     Param->setOwningFunction(FD);
11902
11903     // If this has an identifier, add it to the scope stack.
11904     if (Param->getIdentifier() && FnBodyScope) {
11905       CheckShadow(FnBodyScope, Param);
11906
11907       PushOnScopeChains(Param, FnBodyScope);
11908     }
11909   }
11910
11911   // Ensure that the function's exception specification is instantiated.
11912   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11913     ResolveExceptionSpec(D->getLocation(), FPT);
11914
11915   // dllimport cannot be applied to non-inline function definitions.
11916   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11917       !FD->isTemplateInstantiation()) {
11918     assert(!FD->hasAttr<DLLExportAttr>());
11919     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11920     FD->setInvalidDecl();
11921     return D;
11922   }
11923   // We want to attach documentation to original Decl (which might be
11924   // a function template).
11925   ActOnDocumentableDecl(D);
11926   if (getCurLexicalContext()->isObjCContainer() &&
11927       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11928       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11929     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11930
11931   return D;
11932 }
11933
11934 /// \brief Given the set of return statements within a function body,
11935 /// compute the variables that are subject to the named return value
11936 /// optimization.
11937 ///
11938 /// Each of the variables that is subject to the named return value
11939 /// optimization will be marked as NRVO variables in the AST, and any
11940 /// return statement that has a marked NRVO variable as its NRVO candidate can
11941 /// use the named return value optimization.
11942 ///
11943 /// This function applies a very simplistic algorithm for NRVO: if every return
11944 /// statement in the scope of a variable has the same NRVO candidate, that
11945 /// candidate is an NRVO variable.
11946 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11947   ReturnStmt **Returns = Scope->Returns.data();
11948
11949   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11950     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11951       if (!NRVOCandidate->isNRVOVariable())
11952         Returns[I]->setNRVOCandidate(nullptr);
11953     }
11954   }
11955 }
11956
11957 bool Sema::canDelayFunctionBody(const Declarator &D) {
11958   // We can't delay parsing the body of a constexpr function template (yet).
11959   if (D.getDeclSpec().isConstexprSpecified())
11960     return false;
11961
11962   // We can't delay parsing the body of a function template with a deduced
11963   // return type (yet).
11964   if (D.getDeclSpec().hasAutoTypeSpec()) {
11965     // If the placeholder introduces a non-deduced trailing return type,
11966     // we can still delay parsing it.
11967     if (D.getNumTypeObjects()) {
11968       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11969       if (Outer.Kind == DeclaratorChunk::Function &&
11970           Outer.Fun.hasTrailingReturnType()) {
11971         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11972         return Ty.isNull() || !Ty->isUndeducedType();
11973       }
11974     }
11975     return false;
11976   }
11977
11978   return true;
11979 }
11980
11981 bool Sema::canSkipFunctionBody(Decl *D) {
11982   // We cannot skip the body of a function (or function template) which is
11983   // constexpr, since we may need to evaluate its body in order to parse the
11984   // rest of the file.
11985   // We cannot skip the body of a function with an undeduced return type,
11986   // because any callers of that function need to know the type.
11987   if (const FunctionDecl *FD = D->getAsFunction())
11988     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11989       return false;
11990   return Consumer.shouldSkipFunctionBody(D);
11991 }
11992
11993 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11994   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11995     FD->setHasSkippedBody();
11996   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11997     MD->setHasSkippedBody();
11998   return Decl;
11999 }
12000
12001 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12002   return ActOnFinishFunctionBody(D, BodyArg, false);
12003 }
12004
12005 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12006                                     bool IsInstantiation) {
12007   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12008
12009   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12010   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12011
12012   if (getLangOpts().CoroutinesTS && getCurFunction()->CoroutinePromise)
12013     CheckCompletedCoroutineBody(FD, Body);
12014
12015   if (FD) {
12016     FD->setBody(Body);
12017
12018     if (getLangOpts().CPlusPlus14) {
12019       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12020           FD->getReturnType()->isUndeducedType()) {
12021         // If the function has a deduced result type but contains no 'return'
12022         // statements, the result type as written must be exactly 'auto', and
12023         // the deduced result type is 'void'.
12024         if (!FD->getReturnType()->getAs<AutoType>()) {
12025           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12026               << FD->getReturnType();
12027           FD->setInvalidDecl();
12028         } else {
12029           // Substitute 'void' for the 'auto' in the type.
12030           TypeLoc ResultType = getReturnTypeLoc(FD);
12031           Context.adjustDeducedFunctionResultType(
12032               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12033         }
12034       }
12035     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12036       // In C++11, we don't use 'auto' deduction rules for lambda call
12037       // operators because we don't support return type deduction.
12038       auto *LSI = getCurLambda();
12039       if (LSI->HasImplicitReturnType) {
12040         deduceClosureReturnType(*LSI);
12041
12042         // C++11 [expr.prim.lambda]p4:
12043         //   [...] if there are no return statements in the compound-statement
12044         //   [the deduced type is] the type void
12045         QualType RetType =
12046             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12047
12048         // Update the return type to the deduced type.
12049         const FunctionProtoType *Proto =
12050             FD->getType()->getAs<FunctionProtoType>();
12051         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12052                                             Proto->getExtProtoInfo()));
12053       }
12054     }
12055
12056     // The only way to be included in UndefinedButUsed is if there is an
12057     // ODR use before the definition. Avoid the expensive map lookup if this
12058     // is the first declaration.
12059     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
12060       if (!FD->isExternallyVisible())
12061         UndefinedButUsed.erase(FD);
12062       else if (FD->isInlined() &&
12063                !LangOpts.GNUInline &&
12064                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
12065         UndefinedButUsed.erase(FD);
12066     }
12067
12068     // If the function implicitly returns zero (like 'main') or is naked,
12069     // don't complain about missing return statements.
12070     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12071       WP.disableCheckFallThrough();
12072
12073     // MSVC permits the use of pure specifier (=0) on function definition,
12074     // defined at class scope, warn about this non-standard construct.
12075     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12076       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12077
12078     if (!FD->isInvalidDecl()) {
12079       // Don't diagnose unused parameters of defaulted or deleted functions.
12080       if (!FD->isDeleted() && !FD->isDefaulted())
12081         DiagnoseUnusedParameters(FD->parameters());
12082       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12083                                              FD->getReturnType(), FD);
12084
12085       // If this is a structor, we need a vtable.
12086       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12087         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12088       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12089         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12090
12091       // Try to apply the named return value optimization. We have to check
12092       // if we can do this here because lambdas keep return statements around
12093       // to deduce an implicit return type.
12094       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12095           !FD->isDependentContext())
12096         computeNRVO(Body, getCurFunction());
12097     }
12098
12099     // GNU warning -Wmissing-prototypes:
12100     //   Warn if a global function is defined without a previous
12101     //   prototype declaration. This warning is issued even if the
12102     //   definition itself provides a prototype. The aim is to detect
12103     //   global functions that fail to be declared in header files.
12104     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12105     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12106       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12107
12108       if (PossibleZeroParamPrototype) {
12109         // We found a declaration that is not a prototype,
12110         // but that could be a zero-parameter prototype
12111         if (TypeSourceInfo *TI =
12112                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12113           TypeLoc TL = TI->getTypeLoc();
12114           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12115             Diag(PossibleZeroParamPrototype->getLocation(),
12116                  diag::note_declaration_not_a_prototype)
12117                 << PossibleZeroParamPrototype
12118                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12119         }
12120       }
12121
12122       // GNU warning -Wstrict-prototypes
12123       //   Warn if K&R function is defined without a previous declaration.
12124       //   This warning is issued only if the definition itself does not provide
12125       //   a prototype. Only K&R definitions do not provide a prototype.
12126       //   An empty list in a function declarator that is part of a definition
12127       //   of that function specifies that the function has no parameters
12128       //   (C99 6.7.5.3p14)
12129       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12130           !LangOpts.CPlusPlus) {
12131         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12132         TypeLoc TL = TI->getTypeLoc();
12133         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12134         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1;
12135       }
12136     }
12137
12138     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12139       const CXXMethodDecl *KeyFunction;
12140       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12141           MD->isVirtual() &&
12142           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12143           MD == KeyFunction->getCanonicalDecl()) {
12144         // Update the key-function state if necessary for this ABI.
12145         if (FD->isInlined() &&
12146             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12147           Context.setNonKeyFunction(MD);
12148
12149           // If the newly-chosen key function is already defined, then we
12150           // need to mark the vtable as used retroactively.
12151           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12152           const FunctionDecl *Definition;
12153           if (KeyFunction && KeyFunction->isDefined(Definition))
12154             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12155         } else {
12156           // We just defined they key function; mark the vtable as used.
12157           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12158         }
12159       }
12160     }
12161
12162     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12163            "Function parsing confused");
12164   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12165     assert(MD == getCurMethodDecl() && "Method parsing confused");
12166     MD->setBody(Body);
12167     if (!MD->isInvalidDecl()) {
12168       DiagnoseUnusedParameters(MD->parameters());
12169       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12170                                              MD->getReturnType(), MD);
12171
12172       if (Body)
12173         computeNRVO(Body, getCurFunction());
12174     }
12175     if (getCurFunction()->ObjCShouldCallSuper) {
12176       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12177         << MD->getSelector().getAsString();
12178       getCurFunction()->ObjCShouldCallSuper = false;
12179     }
12180     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12181       const ObjCMethodDecl *InitMethod = nullptr;
12182       bool isDesignated =
12183           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12184       assert(isDesignated && InitMethod);
12185       (void)isDesignated;
12186
12187       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12188         auto IFace = MD->getClassInterface();
12189         if (!IFace)
12190           return false;
12191         auto SuperD = IFace->getSuperClass();
12192         if (!SuperD)
12193           return false;
12194         return SuperD->getIdentifier() ==
12195             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12196       };
12197       // Don't issue this warning for unavailable inits or direct subclasses
12198       // of NSObject.
12199       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12200         Diag(MD->getLocation(),
12201              diag::warn_objc_designated_init_missing_super_call);
12202         Diag(InitMethod->getLocation(),
12203              diag::note_objc_designated_init_marked_here);
12204       }
12205       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12206     }
12207     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12208       // Don't issue this warning for unavaialable inits.
12209       if (!MD->isUnavailable())
12210         Diag(MD->getLocation(),
12211              diag::warn_objc_secondary_init_missing_init_call);
12212       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12213     }
12214   } else {
12215     return nullptr;
12216   }
12217
12218   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12219     DiagnoseUnguardedAvailabilityViolations(dcl);
12220
12221   assert(!getCurFunction()->ObjCShouldCallSuper &&
12222          "This should only be set for ObjC methods, which should have been "
12223          "handled in the block above.");
12224
12225   // Verify and clean out per-function state.
12226   if (Body && (!FD || !FD->isDefaulted())) {
12227     // C++ constructors that have function-try-blocks can't have return
12228     // statements in the handlers of that block. (C++ [except.handle]p14)
12229     // Verify this.
12230     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12231       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12232
12233     // Verify that gotos and switch cases don't jump into scopes illegally.
12234     if (getCurFunction()->NeedsScopeChecking() &&
12235         !PP.isCodeCompletionEnabled())
12236       DiagnoseInvalidJumps(Body);
12237
12238     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12239       if (!Destructor->getParent()->isDependentType())
12240         CheckDestructor(Destructor);
12241
12242       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12243                                              Destructor->getParent());
12244     }
12245
12246     // If any errors have occurred, clear out any temporaries that may have
12247     // been leftover. This ensures that these temporaries won't be picked up for
12248     // deletion in some later function.
12249     if (getDiagnostics().hasErrorOccurred() ||
12250         getDiagnostics().getSuppressAllDiagnostics()) {
12251       DiscardCleanupsInEvaluationContext();
12252     }
12253     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12254         !isa<FunctionTemplateDecl>(dcl)) {
12255       // Since the body is valid, issue any analysis-based warnings that are
12256       // enabled.
12257       ActivePolicy = &WP;
12258     }
12259
12260     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12261         (!CheckConstexprFunctionDecl(FD) ||
12262          !CheckConstexprFunctionBody(FD, Body)))
12263       FD->setInvalidDecl();
12264
12265     if (FD && FD->hasAttr<NakedAttr>()) {
12266       for (const Stmt *S : Body->children()) {
12267         // Allow local register variables without initializer as they don't
12268         // require prologue.
12269         bool RegisterVariables = false;
12270         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12271           for (const auto *Decl : DS->decls()) {
12272             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12273               RegisterVariables =
12274                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12275               if (!RegisterVariables)
12276                 break;
12277             }
12278           }
12279         }
12280         if (RegisterVariables)
12281           continue;
12282         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12283           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12284           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12285           FD->setInvalidDecl();
12286           break;
12287         }
12288       }
12289     }
12290
12291     assert(ExprCleanupObjects.size() ==
12292                ExprEvalContexts.back().NumCleanupObjects &&
12293            "Leftover temporaries in function");
12294     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12295     assert(MaybeODRUseExprs.empty() &&
12296            "Leftover expressions for odr-use checking");
12297   }
12298
12299   if (!IsInstantiation)
12300     PopDeclContext();
12301
12302   PopFunctionScopeInfo(ActivePolicy, dcl);
12303   // If any errors have occurred, clear out any temporaries that may have
12304   // been leftover. This ensures that these temporaries won't be picked up for
12305   // deletion in some later function.
12306   if (getDiagnostics().hasErrorOccurred()) {
12307     DiscardCleanupsInEvaluationContext();
12308   }
12309
12310   return dcl;
12311 }
12312
12313 /// When we finish delayed parsing of an attribute, we must attach it to the
12314 /// relevant Decl.
12315 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12316                                        ParsedAttributes &Attrs) {
12317   // Always attach attributes to the underlying decl.
12318   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12319     D = TD->getTemplatedDecl();
12320   ProcessDeclAttributeList(S, D, Attrs.getList());
12321
12322   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12323     if (Method->isStatic())
12324       checkThisInStaticMemberFunctionAttributes(Method);
12325 }
12326
12327 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12328 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12329 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12330                                           IdentifierInfo &II, Scope *S) {
12331   // Before we produce a declaration for an implicitly defined
12332   // function, see whether there was a locally-scoped declaration of
12333   // this name as a function or variable. If so, use that
12334   // (non-visible) declaration, and complain about it.
12335   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12336     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12337     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12338     return ExternCPrev;
12339   }
12340
12341   // Extension in C99.  Legal in C90, but warn about it.
12342   unsigned diag_id;
12343   if (II.getName().startswith("__builtin_"))
12344     diag_id = diag::warn_builtin_unknown;
12345   else if (getLangOpts().C99)
12346     diag_id = diag::ext_implicit_function_decl;
12347   else
12348     diag_id = diag::warn_implicit_function_decl;
12349   Diag(Loc, diag_id) << &II;
12350
12351   // Because typo correction is expensive, only do it if the implicit
12352   // function declaration is going to be treated as an error.
12353   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12354     TypoCorrection Corrected;
12355     if (S &&
12356         (Corrected = CorrectTypo(
12357              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12358              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12359       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12360                    /*ErrorRecovery*/false);
12361   }
12362
12363   // Set a Declarator for the implicit definition: int foo();
12364   const char *Dummy;
12365   AttributeFactory attrFactory;
12366   DeclSpec DS(attrFactory);
12367   unsigned DiagID;
12368   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12369                                   Context.getPrintingPolicy());
12370   (void)Error; // Silence warning.
12371   assert(!Error && "Error setting up implicit decl!");
12372   SourceLocation NoLoc;
12373   Declarator D(DS, Declarator::BlockContext);
12374   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12375                                              /*IsAmbiguous=*/false,
12376                                              /*LParenLoc=*/NoLoc,
12377                                              /*Params=*/nullptr,
12378                                              /*NumParams=*/0,
12379                                              /*EllipsisLoc=*/NoLoc,
12380                                              /*RParenLoc=*/NoLoc,
12381                                              /*TypeQuals=*/0,
12382                                              /*RefQualifierIsLvalueRef=*/true,
12383                                              /*RefQualifierLoc=*/NoLoc,
12384                                              /*ConstQualifierLoc=*/NoLoc,
12385                                              /*VolatileQualifierLoc=*/NoLoc,
12386                                              /*RestrictQualifierLoc=*/NoLoc,
12387                                              /*MutableLoc=*/NoLoc,
12388                                              EST_None,
12389                                              /*ESpecRange=*/SourceRange(),
12390                                              /*Exceptions=*/nullptr,
12391                                              /*ExceptionRanges=*/nullptr,
12392                                              /*NumExceptions=*/0,
12393                                              /*NoexceptExpr=*/nullptr,
12394                                              /*ExceptionSpecTokens=*/nullptr,
12395                                              /*DeclsInPrototype=*/None,
12396                                              Loc, Loc, D),
12397                 DS.getAttributes(),
12398                 SourceLocation());
12399   D.SetIdentifier(&II, Loc);
12400
12401   // Insert this function into translation-unit scope.
12402
12403   DeclContext *PrevDC = CurContext;
12404   CurContext = Context.getTranslationUnitDecl();
12405
12406   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12407   FD->setImplicit();
12408
12409   CurContext = PrevDC;
12410
12411   AddKnownFunctionAttributes(FD);
12412
12413   return FD;
12414 }
12415
12416 /// \brief Adds any function attributes that we know a priori based on
12417 /// the declaration of this function.
12418 ///
12419 /// These attributes can apply both to implicitly-declared builtins
12420 /// (like __builtin___printf_chk) or to library-declared functions
12421 /// like NSLog or printf.
12422 ///
12423 /// We need to check for duplicate attributes both here and where user-written
12424 /// attributes are applied to declarations.
12425 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12426   if (FD->isInvalidDecl())
12427     return;
12428
12429   // If this is a built-in function, map its builtin attributes to
12430   // actual attributes.
12431   if (unsigned BuiltinID = FD->getBuiltinID()) {
12432     // Handle printf-formatting attributes.
12433     unsigned FormatIdx;
12434     bool HasVAListArg;
12435     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12436       if (!FD->hasAttr<FormatAttr>()) {
12437         const char *fmt = "printf";
12438         unsigned int NumParams = FD->getNumParams();
12439         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12440             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12441           fmt = "NSString";
12442         FD->addAttr(FormatAttr::CreateImplicit(Context,
12443                                                &Context.Idents.get(fmt),
12444                                                FormatIdx+1,
12445                                                HasVAListArg ? 0 : FormatIdx+2,
12446                                                FD->getLocation()));
12447       }
12448     }
12449     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12450                                              HasVAListArg)) {
12451      if (!FD->hasAttr<FormatAttr>())
12452        FD->addAttr(FormatAttr::CreateImplicit(Context,
12453                                               &Context.Idents.get("scanf"),
12454                                               FormatIdx+1,
12455                                               HasVAListArg ? 0 : FormatIdx+2,
12456                                               FD->getLocation()));
12457     }
12458
12459     // Mark const if we don't care about errno and that is the only
12460     // thing preventing the function from being const. This allows
12461     // IRgen to use LLVM intrinsics for such functions.
12462     if (!getLangOpts().MathErrno &&
12463         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12464       if (!FD->hasAttr<ConstAttr>())
12465         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12466     }
12467
12468     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12469         !FD->hasAttr<ReturnsTwiceAttr>())
12470       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12471                                          FD->getLocation()));
12472     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12473       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12474     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12475       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12476     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12477       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12478     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12479         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12480       // Add the appropriate attribute, depending on the CUDA compilation mode
12481       // and which target the builtin belongs to. For example, during host
12482       // compilation, aux builtins are __device__, while the rest are __host__.
12483       if (getLangOpts().CUDAIsDevice !=
12484           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12485         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12486       else
12487         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12488     }
12489   }
12490
12491   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12492   // throw, add an implicit nothrow attribute to any extern "C" function we come
12493   // across.
12494   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12495       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12496     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12497     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12498       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12499   }
12500
12501   IdentifierInfo *Name = FD->getIdentifier();
12502   if (!Name)
12503     return;
12504   if ((!getLangOpts().CPlusPlus &&
12505        FD->getDeclContext()->isTranslationUnit()) ||
12506       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12507        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12508        LinkageSpecDecl::lang_c)) {
12509     // Okay: this could be a libc/libm/Objective-C function we know
12510     // about.
12511   } else
12512     return;
12513
12514   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12515     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12516     // target-specific builtins, perhaps?
12517     if (!FD->hasAttr<FormatAttr>())
12518       FD->addAttr(FormatAttr::CreateImplicit(Context,
12519                                              &Context.Idents.get("printf"), 2,
12520                                              Name->isStr("vasprintf") ? 0 : 3,
12521                                              FD->getLocation()));
12522   }
12523
12524   if (Name->isStr("__CFStringMakeConstantString")) {
12525     // We already have a __builtin___CFStringMakeConstantString,
12526     // but builds that use -fno-constant-cfstrings don't go through that.
12527     if (!FD->hasAttr<FormatArgAttr>())
12528       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12529                                                 FD->getLocation()));
12530   }
12531 }
12532
12533 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12534                                     TypeSourceInfo *TInfo) {
12535   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12536   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12537
12538   if (!TInfo) {
12539     assert(D.isInvalidType() && "no declarator info for valid type");
12540     TInfo = Context.getTrivialTypeSourceInfo(T);
12541   }
12542
12543   // Scope manipulation handled by caller.
12544   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12545                                            D.getLocStart(),
12546                                            D.getIdentifierLoc(),
12547                                            D.getIdentifier(),
12548                                            TInfo);
12549
12550   // Bail out immediately if we have an invalid declaration.
12551   if (D.isInvalidType()) {
12552     NewTD->setInvalidDecl();
12553     return NewTD;
12554   }
12555
12556   if (D.getDeclSpec().isModulePrivateSpecified()) {
12557     if (CurContext->isFunctionOrMethod())
12558       Diag(NewTD->getLocation(), diag::err_module_private_local)
12559         << 2 << NewTD->getDeclName()
12560         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12561         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12562     else
12563       NewTD->setModulePrivate();
12564   }
12565
12566   // C++ [dcl.typedef]p8:
12567   //   If the typedef declaration defines an unnamed class (or
12568   //   enum), the first typedef-name declared by the declaration
12569   //   to be that class type (or enum type) is used to denote the
12570   //   class type (or enum type) for linkage purposes only.
12571   // We need to check whether the type was declared in the declaration.
12572   switch (D.getDeclSpec().getTypeSpecType()) {
12573   case TST_enum:
12574   case TST_struct:
12575   case TST_interface:
12576   case TST_union:
12577   case TST_class: {
12578     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12579     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12580     break;
12581   }
12582
12583   default:
12584     break;
12585   }
12586
12587   return NewTD;
12588 }
12589
12590 /// \brief Check that this is a valid underlying type for an enum declaration.
12591 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12592   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12593   QualType T = TI->getType();
12594
12595   if (T->isDependentType())
12596     return false;
12597
12598   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12599     if (BT->isInteger())
12600       return false;
12601
12602   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12603   return true;
12604 }
12605
12606 /// Check whether this is a valid redeclaration of a previous enumeration.
12607 /// \return true if the redeclaration was invalid.
12608 bool Sema::CheckEnumRedeclaration(
12609     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12610     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12611   bool IsFixed = !EnumUnderlyingTy.isNull();
12612
12613   if (IsScoped != Prev->isScoped()) {
12614     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12615       << Prev->isScoped();
12616     Diag(Prev->getLocation(), diag::note_previous_declaration);
12617     return true;
12618   }
12619
12620   if (IsFixed && Prev->isFixed()) {
12621     if (!EnumUnderlyingTy->isDependentType() &&
12622         !Prev->getIntegerType()->isDependentType() &&
12623         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12624                                         Prev->getIntegerType())) {
12625       // TODO: Highlight the underlying type of the redeclaration.
12626       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12627         << EnumUnderlyingTy << Prev->getIntegerType();
12628       Diag(Prev->getLocation(), diag::note_previous_declaration)
12629           << Prev->getIntegerTypeRange();
12630       return true;
12631     }
12632   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12633     ;
12634   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12635     ;
12636   } else if (IsFixed != Prev->isFixed()) {
12637     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12638       << Prev->isFixed();
12639     Diag(Prev->getLocation(), diag::note_previous_declaration);
12640     return true;
12641   }
12642
12643   return false;
12644 }
12645
12646 /// \brief Get diagnostic %select index for tag kind for
12647 /// redeclaration diagnostic message.
12648 /// WARNING: Indexes apply to particular diagnostics only!
12649 ///
12650 /// \returns diagnostic %select index.
12651 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12652   switch (Tag) {
12653   case TTK_Struct: return 0;
12654   case TTK_Interface: return 1;
12655   case TTK_Class:  return 2;
12656   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12657   }
12658 }
12659
12660 /// \brief Determine if tag kind is a class-key compatible with
12661 /// class for redeclaration (class, struct, or __interface).
12662 ///
12663 /// \returns true iff the tag kind is compatible.
12664 static bool isClassCompatTagKind(TagTypeKind Tag)
12665 {
12666   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12667 }
12668
12669 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12670                                              TagTypeKind TTK) {
12671   if (isa<TypedefDecl>(PrevDecl))
12672     return NTK_Typedef;
12673   else if (isa<TypeAliasDecl>(PrevDecl))
12674     return NTK_TypeAlias;
12675   else if (isa<ClassTemplateDecl>(PrevDecl))
12676     return NTK_Template;
12677   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12678     return NTK_TypeAliasTemplate;
12679   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12680     return NTK_TemplateTemplateArgument;
12681   switch (TTK) {
12682   case TTK_Struct:
12683   case TTK_Interface:
12684   case TTK_Class:
12685     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12686   case TTK_Union:
12687     return NTK_NonUnion;
12688   case TTK_Enum:
12689     return NTK_NonEnum;
12690   }
12691   llvm_unreachable("invalid TTK");
12692 }
12693
12694 /// \brief Determine whether a tag with a given kind is acceptable
12695 /// as a redeclaration of the given tag declaration.
12696 ///
12697 /// \returns true if the new tag kind is acceptable, false otherwise.
12698 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12699                                         TagTypeKind NewTag, bool isDefinition,
12700                                         SourceLocation NewTagLoc,
12701                                         const IdentifierInfo *Name) {
12702   // C++ [dcl.type.elab]p3:
12703   //   The class-key or enum keyword present in the
12704   //   elaborated-type-specifier shall agree in kind with the
12705   //   declaration to which the name in the elaborated-type-specifier
12706   //   refers. This rule also applies to the form of
12707   //   elaborated-type-specifier that declares a class-name or
12708   //   friend class since it can be construed as referring to the
12709   //   definition of the class. Thus, in any
12710   //   elaborated-type-specifier, the enum keyword shall be used to
12711   //   refer to an enumeration (7.2), the union class-key shall be
12712   //   used to refer to a union (clause 9), and either the class or
12713   //   struct class-key shall be used to refer to a class (clause 9)
12714   //   declared using the class or struct class-key.
12715   TagTypeKind OldTag = Previous->getTagKind();
12716   if (!isDefinition || !isClassCompatTagKind(NewTag))
12717     if (OldTag == NewTag)
12718       return true;
12719
12720   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12721     // Warn about the struct/class tag mismatch.
12722     bool isTemplate = false;
12723     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12724       isTemplate = Record->getDescribedClassTemplate();
12725
12726     if (inTemplateInstantiation()) {
12727       // In a template instantiation, do not offer fix-its for tag mismatches
12728       // since they usually mess up the template instead of fixing the problem.
12729       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12730         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12731         << getRedeclDiagFromTagKind(OldTag);
12732       return true;
12733     }
12734
12735     if (isDefinition) {
12736       // On definitions, check previous tags and issue a fix-it for each
12737       // one that doesn't match the current tag.
12738       if (Previous->getDefinition()) {
12739         // Don't suggest fix-its for redefinitions.
12740         return true;
12741       }
12742
12743       bool previousMismatch = false;
12744       for (auto I : Previous->redecls()) {
12745         if (I->getTagKind() != NewTag) {
12746           if (!previousMismatch) {
12747             previousMismatch = true;
12748             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12749               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12750               << getRedeclDiagFromTagKind(I->getTagKind());
12751           }
12752           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12753             << getRedeclDiagFromTagKind(NewTag)
12754             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12755                  TypeWithKeyword::getTagTypeKindName(NewTag));
12756         }
12757       }
12758       return true;
12759     }
12760
12761     // Check for a previous definition.  If current tag and definition
12762     // are same type, do nothing.  If no definition, but disagree with
12763     // with previous tag type, give a warning, but no fix-it.
12764     const TagDecl *Redecl = Previous->getDefinition() ?
12765                             Previous->getDefinition() : Previous;
12766     if (Redecl->getTagKind() == NewTag) {
12767       return true;
12768     }
12769
12770     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12771       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12772       << getRedeclDiagFromTagKind(OldTag);
12773     Diag(Redecl->getLocation(), diag::note_previous_use);
12774
12775     // If there is a previous definition, suggest a fix-it.
12776     if (Previous->getDefinition()) {
12777         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12778           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12779           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12780                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12781     }
12782
12783     return true;
12784   }
12785   return false;
12786 }
12787
12788 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12789 /// from an outer enclosing namespace or file scope inside a friend declaration.
12790 /// This should provide the commented out code in the following snippet:
12791 ///   namespace N {
12792 ///     struct X;
12793 ///     namespace M {
12794 ///       struct Y { friend struct /*N::*/ X; };
12795 ///     }
12796 ///   }
12797 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12798                                          SourceLocation NameLoc) {
12799   // While the decl is in a namespace, do repeated lookup of that name and see
12800   // if we get the same namespace back.  If we do not, continue until
12801   // translation unit scope, at which point we have a fully qualified NNS.
12802   SmallVector<IdentifierInfo *, 4> Namespaces;
12803   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12804   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12805     // This tag should be declared in a namespace, which can only be enclosed by
12806     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12807     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12808     if (!Namespace || Namespace->isAnonymousNamespace())
12809       return FixItHint();
12810     IdentifierInfo *II = Namespace->getIdentifier();
12811     Namespaces.push_back(II);
12812     NamedDecl *Lookup = SemaRef.LookupSingleName(
12813         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12814     if (Lookup == Namespace)
12815       break;
12816   }
12817
12818   // Once we have all the namespaces, reverse them to go outermost first, and
12819   // build an NNS.
12820   SmallString<64> Insertion;
12821   llvm::raw_svector_ostream OS(Insertion);
12822   if (DC->isTranslationUnit())
12823     OS << "::";
12824   std::reverse(Namespaces.begin(), Namespaces.end());
12825   for (auto *II : Namespaces)
12826     OS << II->getName() << "::";
12827   return FixItHint::CreateInsertion(NameLoc, Insertion);
12828 }
12829
12830 /// \brief Determine whether a tag originally declared in context \p OldDC can
12831 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12832 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12833 /// using-declaration).
12834 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12835                                          DeclContext *NewDC) {
12836   OldDC = OldDC->getRedeclContext();
12837   NewDC = NewDC->getRedeclContext();
12838
12839   if (OldDC->Equals(NewDC))
12840     return true;
12841
12842   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12843   // encloses the other).
12844   if (S.getLangOpts().MSVCCompat &&
12845       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12846     return true;
12847
12848   return false;
12849 }
12850
12851 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12852 /// former case, Name will be non-null.  In the later case, Name will be null.
12853 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12854 /// reference/declaration/definition of a tag.
12855 ///
12856 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12857 /// trailing-type-specifier) other than one in an alias-declaration.
12858 ///
12859 /// \param SkipBody If non-null, will be set to indicate if the caller should
12860 /// skip the definition of this tag and treat it as if it were a declaration.
12861 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12862                      SourceLocation KWLoc, CXXScopeSpec &SS,
12863                      IdentifierInfo *Name, SourceLocation NameLoc,
12864                      AttributeList *Attr, AccessSpecifier AS,
12865                      SourceLocation ModulePrivateLoc,
12866                      MultiTemplateParamsArg TemplateParameterLists,
12867                      bool &OwnedDecl, bool &IsDependent,
12868                      SourceLocation ScopedEnumKWLoc,
12869                      bool ScopedEnumUsesClassTag,
12870                      TypeResult UnderlyingType,
12871                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12872   // If this is not a definition, it must have a name.
12873   IdentifierInfo *OrigName = Name;
12874   assert((Name != nullptr || TUK == TUK_Definition) &&
12875          "Nameless record must be a definition!");
12876   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12877
12878   OwnedDecl = false;
12879   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12880   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12881
12882   // FIXME: Check member specializations more carefully.
12883   bool isMemberSpecialization = false;
12884   bool Invalid = false;
12885
12886   // We only need to do this matching if we have template parameters
12887   // or a scope specifier, which also conveniently avoids this work
12888   // for non-C++ cases.
12889   if (TemplateParameterLists.size() > 0 ||
12890       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12891     if (TemplateParameterList *TemplateParams =
12892             MatchTemplateParametersToScopeSpecifier(
12893                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12894                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
12895       if (Kind == TTK_Enum) {
12896         Diag(KWLoc, diag::err_enum_template);
12897         return nullptr;
12898       }
12899
12900       if (TemplateParams->size() > 0) {
12901         // This is a declaration or definition of a class template (which may
12902         // be a member of another template).
12903
12904         if (Invalid)
12905           return nullptr;
12906
12907         OwnedDecl = false;
12908         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12909                                                SS, Name, NameLoc, Attr,
12910                                                TemplateParams, AS,
12911                                                ModulePrivateLoc,
12912                                                /*FriendLoc*/SourceLocation(),
12913                                                TemplateParameterLists.size()-1,
12914                                                TemplateParameterLists.data(),
12915                                                SkipBody);
12916         return Result.get();
12917       } else {
12918         // The "template<>" header is extraneous.
12919         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12920           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12921         isMemberSpecialization = true;
12922       }
12923     }
12924   }
12925
12926   // Figure out the underlying type if this a enum declaration. We need to do
12927   // this early, because it's needed to detect if this is an incompatible
12928   // redeclaration.
12929   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12930   bool EnumUnderlyingIsImplicit = false;
12931
12932   if (Kind == TTK_Enum) {
12933     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12934       // No underlying type explicitly specified, or we failed to parse the
12935       // type, default to int.
12936       EnumUnderlying = Context.IntTy.getTypePtr();
12937     else if (UnderlyingType.get()) {
12938       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12939       // integral type; any cv-qualification is ignored.
12940       TypeSourceInfo *TI = nullptr;
12941       GetTypeFromParser(UnderlyingType.get(), &TI);
12942       EnumUnderlying = TI;
12943
12944       if (CheckEnumUnderlyingType(TI))
12945         // Recover by falling back to int.
12946         EnumUnderlying = Context.IntTy.getTypePtr();
12947
12948       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12949                                           UPPC_FixedUnderlyingType))
12950         EnumUnderlying = Context.IntTy.getTypePtr();
12951
12952     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12953       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12954         // Microsoft enums are always of int type.
12955         EnumUnderlying = Context.IntTy.getTypePtr();
12956         EnumUnderlyingIsImplicit = true;
12957       }
12958     }
12959   }
12960
12961   DeclContext *SearchDC = CurContext;
12962   DeclContext *DC = CurContext;
12963   bool isStdBadAlloc = false;
12964   bool isStdAlignValT = false;
12965
12966   RedeclarationKind Redecl = ForRedeclaration;
12967   if (TUK == TUK_Friend || TUK == TUK_Reference)
12968     Redecl = NotForRedeclaration;
12969
12970   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12971   if (Name && SS.isNotEmpty()) {
12972     // We have a nested-name tag ('struct foo::bar').
12973
12974     // Check for invalid 'foo::'.
12975     if (SS.isInvalid()) {
12976       Name = nullptr;
12977       goto CreateNewDecl;
12978     }
12979
12980     // If this is a friend or a reference to a class in a dependent
12981     // context, don't try to make a decl for it.
12982     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12983       DC = computeDeclContext(SS, false);
12984       if (!DC) {
12985         IsDependent = true;
12986         return nullptr;
12987       }
12988     } else {
12989       DC = computeDeclContext(SS, true);
12990       if (!DC) {
12991         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12992           << SS.getRange();
12993         return nullptr;
12994       }
12995     }
12996
12997     if (RequireCompleteDeclContext(SS, DC))
12998       return nullptr;
12999
13000     SearchDC = DC;
13001     // Look-up name inside 'foo::'.
13002     LookupQualifiedName(Previous, DC);
13003
13004     if (Previous.isAmbiguous())
13005       return nullptr;
13006
13007     if (Previous.empty()) {
13008       // Name lookup did not find anything. However, if the
13009       // nested-name-specifier refers to the current instantiation,
13010       // and that current instantiation has any dependent base
13011       // classes, we might find something at instantiation time: treat
13012       // this as a dependent elaborated-type-specifier.
13013       // But this only makes any sense for reference-like lookups.
13014       if (Previous.wasNotFoundInCurrentInstantiation() &&
13015           (TUK == TUK_Reference || TUK == TUK_Friend)) {
13016         IsDependent = true;
13017         return nullptr;
13018       }
13019
13020       // A tag 'foo::bar' must already exist.
13021       Diag(NameLoc, diag::err_not_tag_in_scope)
13022         << Kind << Name << DC << SS.getRange();
13023       Name = nullptr;
13024       Invalid = true;
13025       goto CreateNewDecl;
13026     }
13027   } else if (Name) {
13028     // C++14 [class.mem]p14:
13029     //   If T is the name of a class, then each of the following shall have a
13030     //   name different from T:
13031     //    -- every member of class T that is itself a type
13032     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13033         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13034       return nullptr;
13035
13036     // If this is a named struct, check to see if there was a previous forward
13037     // declaration or definition.
13038     // FIXME: We're looking into outer scopes here, even when we
13039     // shouldn't be. Doing so can result in ambiguities that we
13040     // shouldn't be diagnosing.
13041     LookupName(Previous, S);
13042
13043     // When declaring or defining a tag, ignore ambiguities introduced
13044     // by types using'ed into this scope.
13045     if (Previous.isAmbiguous() &&
13046         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13047       LookupResult::Filter F = Previous.makeFilter();
13048       while (F.hasNext()) {
13049         NamedDecl *ND = F.next();
13050         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13051                 SearchDC->getRedeclContext()))
13052           F.erase();
13053       }
13054       F.done();
13055     }
13056
13057     // C++11 [namespace.memdef]p3:
13058     //   If the name in a friend declaration is neither qualified nor
13059     //   a template-id and the declaration is a function or an
13060     //   elaborated-type-specifier, the lookup to determine whether
13061     //   the entity has been previously declared shall not consider
13062     //   any scopes outside the innermost enclosing namespace.
13063     //
13064     // MSVC doesn't implement the above rule for types, so a friend tag
13065     // declaration may be a redeclaration of a type declared in an enclosing
13066     // scope.  They do implement this rule for friend functions.
13067     //
13068     // Does it matter that this should be by scope instead of by
13069     // semantic context?
13070     if (!Previous.empty() && TUK == TUK_Friend) {
13071       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13072       LookupResult::Filter F = Previous.makeFilter();
13073       bool FriendSawTagOutsideEnclosingNamespace = false;
13074       while (F.hasNext()) {
13075         NamedDecl *ND = F.next();
13076         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13077         if (DC->isFileContext() &&
13078             !EnclosingNS->Encloses(ND->getDeclContext())) {
13079           if (getLangOpts().MSVCCompat)
13080             FriendSawTagOutsideEnclosingNamespace = true;
13081           else
13082             F.erase();
13083         }
13084       }
13085       F.done();
13086
13087       // Diagnose this MSVC extension in the easy case where lookup would have
13088       // unambiguously found something outside the enclosing namespace.
13089       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13090         NamedDecl *ND = Previous.getFoundDecl();
13091         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13092             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13093       }
13094     }
13095
13096     // Note:  there used to be some attempt at recovery here.
13097     if (Previous.isAmbiguous())
13098       return nullptr;
13099
13100     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13101       // FIXME: This makes sure that we ignore the contexts associated
13102       // with C structs, unions, and enums when looking for a matching
13103       // tag declaration or definition. See the similar lookup tweak
13104       // in Sema::LookupName; is there a better way to deal with this?
13105       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13106         SearchDC = SearchDC->getParent();
13107     }
13108   }
13109
13110   if (Previous.isSingleResult() &&
13111       Previous.getFoundDecl()->isTemplateParameter()) {
13112     // Maybe we will complain about the shadowed template parameter.
13113     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13114     // Just pretend that we didn't see the previous declaration.
13115     Previous.clear();
13116   }
13117
13118   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13119       DC->Equals(getStdNamespace())) {
13120     if (Name->isStr("bad_alloc")) {
13121       // This is a declaration of or a reference to "std::bad_alloc".
13122       isStdBadAlloc = true;
13123
13124       // If std::bad_alloc has been implicitly declared (but made invisible to
13125       // name lookup), fill in this implicit declaration as the previous
13126       // declaration, so that the declarations get chained appropriately.
13127       if (Previous.empty() && StdBadAlloc)
13128         Previous.addDecl(getStdBadAlloc());
13129     } else if (Name->isStr("align_val_t")) {
13130       isStdAlignValT = true;
13131       if (Previous.empty() && StdAlignValT)
13132         Previous.addDecl(getStdAlignValT());
13133     }
13134   }
13135
13136   // If we didn't find a previous declaration, and this is a reference
13137   // (or friend reference), move to the correct scope.  In C++, we
13138   // also need to do a redeclaration lookup there, just in case
13139   // there's a shadow friend decl.
13140   if (Name && Previous.empty() &&
13141       (TUK == TUK_Reference || TUK == TUK_Friend)) {
13142     if (Invalid) goto CreateNewDecl;
13143     assert(SS.isEmpty());
13144
13145     if (TUK == TUK_Reference) {
13146       // C++ [basic.scope.pdecl]p5:
13147       //   -- for an elaborated-type-specifier of the form
13148       //
13149       //          class-key identifier
13150       //
13151       //      if the elaborated-type-specifier is used in the
13152       //      decl-specifier-seq or parameter-declaration-clause of a
13153       //      function defined in namespace scope, the identifier is
13154       //      declared as a class-name in the namespace that contains
13155       //      the declaration; otherwise, except as a friend
13156       //      declaration, the identifier is declared in the smallest
13157       //      non-class, non-function-prototype scope that contains the
13158       //      declaration.
13159       //
13160       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13161       // C structs and unions.
13162       //
13163       // It is an error in C++ to declare (rather than define) an enum
13164       // type, including via an elaborated type specifier.  We'll
13165       // diagnose that later; for now, declare the enum in the same
13166       // scope as we would have picked for any other tag type.
13167       //
13168       // GNU C also supports this behavior as part of its incomplete
13169       // enum types extension, while GNU C++ does not.
13170       //
13171       // Find the context where we'll be declaring the tag.
13172       // FIXME: We would like to maintain the current DeclContext as the
13173       // lexical context,
13174       SearchDC = getTagInjectionContext(SearchDC);
13175
13176       // Find the scope where we'll be declaring the tag.
13177       S = getTagInjectionScope(S, getLangOpts());
13178     } else {
13179       assert(TUK == TUK_Friend);
13180       // C++ [namespace.memdef]p3:
13181       //   If a friend declaration in a non-local class first declares a
13182       //   class or function, the friend class or function is a member of
13183       //   the innermost enclosing namespace.
13184       SearchDC = SearchDC->getEnclosingNamespaceContext();
13185     }
13186
13187     // In C++, we need to do a redeclaration lookup to properly
13188     // diagnose some problems.
13189     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13190     // hidden declaration so that we don't get ambiguity errors when using a
13191     // type declared by an elaborated-type-specifier.  In C that is not correct
13192     // and we should instead merge compatible types found by lookup.
13193     if (getLangOpts().CPlusPlus) {
13194       Previous.setRedeclarationKind(ForRedeclaration);
13195       LookupQualifiedName(Previous, SearchDC);
13196     } else {
13197       Previous.setRedeclarationKind(ForRedeclaration);
13198       LookupName(Previous, S);
13199     }
13200   }
13201
13202   // If we have a known previous declaration to use, then use it.
13203   if (Previous.empty() && SkipBody && SkipBody->Previous)
13204     Previous.addDecl(SkipBody->Previous);
13205
13206   if (!Previous.empty()) {
13207     NamedDecl *PrevDecl = Previous.getFoundDecl();
13208     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13209
13210     // It's okay to have a tag decl in the same scope as a typedef
13211     // which hides a tag decl in the same scope.  Finding this
13212     // insanity with a redeclaration lookup can only actually happen
13213     // in C++.
13214     //
13215     // This is also okay for elaborated-type-specifiers, which is
13216     // technically forbidden by the current standard but which is
13217     // okay according to the likely resolution of an open issue;
13218     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13219     if (getLangOpts().CPlusPlus) {
13220       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13221         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13222           TagDecl *Tag = TT->getDecl();
13223           if (Tag->getDeclName() == Name &&
13224               Tag->getDeclContext()->getRedeclContext()
13225                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13226             PrevDecl = Tag;
13227             Previous.clear();
13228             Previous.addDecl(Tag);
13229             Previous.resolveKind();
13230           }
13231         }
13232       }
13233     }
13234
13235     // If this is a redeclaration of a using shadow declaration, it must
13236     // declare a tag in the same context. In MSVC mode, we allow a
13237     // redefinition if either context is within the other.
13238     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13239       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13240       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13241           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13242           !(OldTag && isAcceptableTagRedeclContext(
13243                           *this, OldTag->getDeclContext(), SearchDC))) {
13244         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13245         Diag(Shadow->getTargetDecl()->getLocation(),
13246              diag::note_using_decl_target);
13247         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13248             << 0;
13249         // Recover by ignoring the old declaration.
13250         Previous.clear();
13251         goto CreateNewDecl;
13252       }
13253     }
13254
13255     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13256       // If this is a use of a previous tag, or if the tag is already declared
13257       // in the same scope (so that the definition/declaration completes or
13258       // rementions the tag), reuse the decl.
13259       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13260           isDeclInScope(DirectPrevDecl, SearchDC, S,
13261                         SS.isNotEmpty() || isMemberSpecialization)) {
13262         // Make sure that this wasn't declared as an enum and now used as a
13263         // struct or something similar.
13264         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13265                                           TUK == TUK_Definition, KWLoc,
13266                                           Name)) {
13267           bool SafeToContinue
13268             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13269                Kind != TTK_Enum);
13270           if (SafeToContinue)
13271             Diag(KWLoc, diag::err_use_with_wrong_tag)
13272               << Name
13273               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13274                                               PrevTagDecl->getKindName());
13275           else
13276             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13277           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13278
13279           if (SafeToContinue)
13280             Kind = PrevTagDecl->getTagKind();
13281           else {
13282             // Recover by making this an anonymous redefinition.
13283             Name = nullptr;
13284             Previous.clear();
13285             Invalid = true;
13286           }
13287         }
13288
13289         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13290           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13291
13292           // If this is an elaborated-type-specifier for a scoped enumeration,
13293           // the 'class' keyword is not necessary and not permitted.
13294           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13295             if (ScopedEnum)
13296               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13297                 << PrevEnum->isScoped()
13298                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13299             return PrevTagDecl;
13300           }
13301
13302           QualType EnumUnderlyingTy;
13303           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13304             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13305           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13306             EnumUnderlyingTy = QualType(T, 0);
13307
13308           // All conflicts with previous declarations are recovered by
13309           // returning the previous declaration, unless this is a definition,
13310           // in which case we want the caller to bail out.
13311           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13312                                      ScopedEnum, EnumUnderlyingTy,
13313                                      EnumUnderlyingIsImplicit, PrevEnum))
13314             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13315         }
13316
13317         // C++11 [class.mem]p1:
13318         //   A member shall not be declared twice in the member-specification,
13319         //   except that a nested class or member class template can be declared
13320         //   and then later defined.
13321         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13322             S->isDeclScope(PrevDecl)) {
13323           Diag(NameLoc, diag::ext_member_redeclared);
13324           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13325         }
13326
13327         if (!Invalid) {
13328           // If this is a use, just return the declaration we found, unless
13329           // we have attributes.
13330           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13331             if (Attr) {
13332               // FIXME: Diagnose these attributes. For now, we create a new
13333               // declaration to hold them.
13334             } else if (TUK == TUK_Reference &&
13335                        (PrevTagDecl->getFriendObjectKind() ==
13336                             Decl::FOK_Undeclared ||
13337                         PP.getModuleContainingLocation(
13338                             PrevDecl->getLocation()) !=
13339                             PP.getModuleContainingLocation(KWLoc)) &&
13340                        SS.isEmpty()) {
13341               // This declaration is a reference to an existing entity, but
13342               // has different visibility from that entity: it either makes
13343               // a friend visible or it makes a type visible in a new module.
13344               // In either case, create a new declaration. We only do this if
13345               // the declaration would have meant the same thing if no prior
13346               // declaration were found, that is, if it was found in the same
13347               // scope where we would have injected a declaration.
13348               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13349                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13350                 return PrevTagDecl;
13351               // This is in the injected scope, create a new declaration in
13352               // that scope.
13353               S = getTagInjectionScope(S, getLangOpts());
13354             } else {
13355               return PrevTagDecl;
13356             }
13357           }
13358
13359           // Diagnose attempts to redefine a tag.
13360           if (TUK == TUK_Definition) {
13361             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13362               // If we're defining a specialization and the previous definition
13363               // is from an implicit instantiation, don't emit an error
13364               // here; we'll catch this in the general case below.
13365               bool IsExplicitSpecializationAfterInstantiation = false;
13366               if (isMemberSpecialization) {
13367                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13368                   IsExplicitSpecializationAfterInstantiation =
13369                     RD->getTemplateSpecializationKind() !=
13370                     TSK_ExplicitSpecialization;
13371                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13372                   IsExplicitSpecializationAfterInstantiation =
13373                     ED->getTemplateSpecializationKind() !=
13374                     TSK_ExplicitSpecialization;
13375               }
13376
13377               NamedDecl *Hidden = nullptr;
13378               if (SkipBody && getLangOpts().CPlusPlus &&
13379                   !hasVisibleDefinition(Def, &Hidden)) {
13380                 // There is a definition of this tag, but it is not visible. We
13381                 // explicitly make use of C++'s one definition rule here, and
13382                 // assume that this definition is identical to the hidden one
13383                 // we already have. Make the existing definition visible and
13384                 // use it in place of this one.
13385                 SkipBody->ShouldSkip = true;
13386                 makeMergedDefinitionVisible(Hidden, KWLoc);
13387                 return Def;
13388               } else if (!IsExplicitSpecializationAfterInstantiation) {
13389                 // A redeclaration in function prototype scope in C isn't
13390                 // visible elsewhere, so merely issue a warning.
13391                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13392                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13393                 else
13394                   Diag(NameLoc, diag::err_redefinition) << Name;
13395                 Diag(Def->getLocation(), diag::note_previous_definition);
13396                 // If this is a redefinition, recover by making this
13397                 // struct be anonymous, which will make any later
13398                 // references get the previous definition.
13399                 Name = nullptr;
13400                 Previous.clear();
13401                 Invalid = true;
13402               }
13403             } else {
13404               // If the type is currently being defined, complain
13405               // about a nested redefinition.
13406               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13407               if (TD->isBeingDefined()) {
13408                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13409                 Diag(PrevTagDecl->getLocation(),
13410                      diag::note_previous_definition);
13411                 Name = nullptr;
13412                 Previous.clear();
13413                 Invalid = true;
13414               }
13415             }
13416
13417             // Okay, this is definition of a previously declared or referenced
13418             // tag. We're going to create a new Decl for it.
13419           }
13420
13421           // Okay, we're going to make a redeclaration.  If this is some kind
13422           // of reference, make sure we build the redeclaration in the same DC
13423           // as the original, and ignore the current access specifier.
13424           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13425             SearchDC = PrevTagDecl->getDeclContext();
13426             AS = AS_none;
13427           }
13428         }
13429         // If we get here we have (another) forward declaration or we
13430         // have a definition.  Just create a new decl.
13431
13432       } else {
13433         // If we get here, this is a definition of a new tag type in a nested
13434         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13435         // new decl/type.  We set PrevDecl to NULL so that the entities
13436         // have distinct types.
13437         Previous.clear();
13438       }
13439       // If we get here, we're going to create a new Decl. If PrevDecl
13440       // is non-NULL, it's a definition of the tag declared by
13441       // PrevDecl. If it's NULL, we have a new definition.
13442
13443     // Otherwise, PrevDecl is not a tag, but was found with tag
13444     // lookup.  This is only actually possible in C++, where a few
13445     // things like templates still live in the tag namespace.
13446     } else {
13447       // Use a better diagnostic if an elaborated-type-specifier
13448       // found the wrong kind of type on the first
13449       // (non-redeclaration) lookup.
13450       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13451           !Previous.isForRedeclaration()) {
13452         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13453         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13454                                                        << Kind;
13455         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13456         Invalid = true;
13457
13458       // Otherwise, only diagnose if the declaration is in scope.
13459       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13460                                 SS.isNotEmpty() || isMemberSpecialization)) {
13461         // do nothing
13462
13463       // Diagnose implicit declarations introduced by elaborated types.
13464       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13465         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13466         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13467         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13468         Invalid = true;
13469
13470       // Otherwise it's a declaration.  Call out a particularly common
13471       // case here.
13472       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13473         unsigned Kind = 0;
13474         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13475         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13476           << Name << Kind << TND->getUnderlyingType();
13477         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13478         Invalid = true;
13479
13480       // Otherwise, diagnose.
13481       } else {
13482         // The tag name clashes with something else in the target scope,
13483         // issue an error and recover by making this tag be anonymous.
13484         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13485         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13486         Name = nullptr;
13487         Invalid = true;
13488       }
13489
13490       // The existing declaration isn't relevant to us; we're in a
13491       // new scope, so clear out the previous declaration.
13492       Previous.clear();
13493     }
13494   }
13495
13496 CreateNewDecl:
13497
13498   TagDecl *PrevDecl = nullptr;
13499   if (Previous.isSingleResult())
13500     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13501
13502   // If there is an identifier, use the location of the identifier as the
13503   // location of the decl, otherwise use the location of the struct/union
13504   // keyword.
13505   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13506
13507   // Otherwise, create a new declaration. If there is a previous
13508   // declaration of the same entity, the two will be linked via
13509   // PrevDecl.
13510   TagDecl *New;
13511
13512   bool IsForwardReference = false;
13513   if (Kind == TTK_Enum) {
13514     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13515     // enum X { A, B, C } D;    D should chain to X.
13516     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13517                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13518                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13519
13520     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13521       StdAlignValT = cast<EnumDecl>(New);
13522
13523     // If this is an undefined enum, warn.
13524     if (TUK != TUK_Definition && !Invalid) {
13525       TagDecl *Def;
13526       if (!EnumUnderlyingIsImplicit &&
13527           (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13528           cast<EnumDecl>(New)->isFixed()) {
13529         // C++0x: 7.2p2: opaque-enum-declaration.
13530         // Conflicts are diagnosed above. Do nothing.
13531       }
13532       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13533         Diag(Loc, diag::ext_forward_ref_enum_def)
13534           << New;
13535         Diag(Def->getLocation(), diag::note_previous_definition);
13536       } else {
13537         unsigned DiagID = diag::ext_forward_ref_enum;
13538         if (getLangOpts().MSVCCompat)
13539           DiagID = diag::ext_ms_forward_ref_enum;
13540         else if (getLangOpts().CPlusPlus)
13541           DiagID = diag::err_forward_ref_enum;
13542         Diag(Loc, DiagID);
13543
13544         // If this is a forward-declared reference to an enumeration, make a
13545         // note of it; we won't actually be introducing the declaration into
13546         // the declaration context.
13547         if (TUK == TUK_Reference)
13548           IsForwardReference = true;
13549       }
13550     }
13551
13552     if (EnumUnderlying) {
13553       EnumDecl *ED = cast<EnumDecl>(New);
13554       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13555         ED->setIntegerTypeSourceInfo(TI);
13556       else
13557         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13558       ED->setPromotionType(ED->getIntegerType());
13559     }
13560   } else {
13561     // struct/union/class
13562
13563     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13564     // struct X { int A; } D;    D should chain to X.
13565     if (getLangOpts().CPlusPlus) {
13566       // FIXME: Look for a way to use RecordDecl for simple structs.
13567       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13568                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13569
13570       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13571         StdBadAlloc = cast<CXXRecordDecl>(New);
13572     } else
13573       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13574                                cast_or_null<RecordDecl>(PrevDecl));
13575   }
13576
13577   // C++11 [dcl.type]p3:
13578   //   A type-specifier-seq shall not define a class or enumeration [...].
13579   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
13580     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13581       << Context.getTagDeclType(New);
13582     Invalid = true;
13583   }
13584
13585   // Maybe add qualifier info.
13586   if (SS.isNotEmpty()) {
13587     if (SS.isSet()) {
13588       // If this is either a declaration or a definition, check the
13589       // nested-name-specifier against the current context. We don't do this
13590       // for explicit specializations, because they have similar checking
13591       // (with more specific diagnostics) in the call to
13592       // CheckMemberSpecialization, below.
13593       if (!isMemberSpecialization &&
13594           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13595           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13596         Invalid = true;
13597
13598       New->setQualifierInfo(SS.getWithLocInContext(Context));
13599       if (TemplateParameterLists.size() > 0) {
13600         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13601       }
13602     }
13603     else
13604       Invalid = true;
13605   }
13606
13607   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13608     // Add alignment attributes if necessary; these attributes are checked when
13609     // the ASTContext lays out the structure.
13610     //
13611     // It is important for implementing the correct semantics that this
13612     // happen here (in act on tag decl). The #pragma pack stack is
13613     // maintained as a result of parser callbacks which can occur at
13614     // many points during the parsing of a struct declaration (because
13615     // the #pragma tokens are effectively skipped over during the
13616     // parsing of the struct).
13617     if (TUK == TUK_Definition) {
13618       AddAlignmentAttributesForRecord(RD);
13619       AddMsStructLayoutForRecord(RD);
13620     }
13621   }
13622
13623   if (ModulePrivateLoc.isValid()) {
13624     if (isMemberSpecialization)
13625       Diag(New->getLocation(), diag::err_module_private_specialization)
13626         << 2
13627         << FixItHint::CreateRemoval(ModulePrivateLoc);
13628     // __module_private__ does not apply to local classes. However, we only
13629     // diagnose this as an error when the declaration specifiers are
13630     // freestanding. Here, we just ignore the __module_private__.
13631     else if (!SearchDC->isFunctionOrMethod())
13632       New->setModulePrivate();
13633   }
13634
13635   // If this is a specialization of a member class (of a class template),
13636   // check the specialization.
13637   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
13638     Invalid = true;
13639
13640   // If we're declaring or defining a tag in function prototype scope in C,
13641   // note that this type can only be used within the function and add it to
13642   // the list of decls to inject into the function definition scope.
13643   if ((Name || Kind == TTK_Enum) &&
13644       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13645     if (getLangOpts().CPlusPlus) {
13646       // C++ [dcl.fct]p6:
13647       //   Types shall not be defined in return or parameter types.
13648       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13649         Diag(Loc, diag::err_type_defined_in_param_type)
13650             << Name;
13651         Invalid = true;
13652       }
13653     } else if (!PrevDecl) {
13654       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13655     }
13656   }
13657
13658   if (Invalid)
13659     New->setInvalidDecl();
13660
13661   // Set the lexical context. If the tag has a C++ scope specifier, the
13662   // lexical context will be different from the semantic context.
13663   New->setLexicalDeclContext(CurContext);
13664
13665   // Mark this as a friend decl if applicable.
13666   // In Microsoft mode, a friend declaration also acts as a forward
13667   // declaration so we always pass true to setObjectOfFriendDecl to make
13668   // the tag name visible.
13669   if (TUK == TUK_Friend)
13670     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13671
13672   // Set the access specifier.
13673   if (!Invalid && SearchDC->isRecord())
13674     SetMemberAccessSpecifier(New, PrevDecl, AS);
13675
13676   if (TUK == TUK_Definition)
13677     New->startDefinition();
13678
13679   if (Attr)
13680     ProcessDeclAttributeList(S, New, Attr);
13681   AddPragmaAttributes(S, New);
13682
13683   // If this has an identifier, add it to the scope stack.
13684   if (TUK == TUK_Friend) {
13685     // We might be replacing an existing declaration in the lookup tables;
13686     // if so, borrow its access specifier.
13687     if (PrevDecl)
13688       New->setAccess(PrevDecl->getAccess());
13689
13690     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13691     DC->makeDeclVisibleInContext(New);
13692     if (Name) // can be null along some error paths
13693       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13694         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13695   } else if (Name) {
13696     S = getNonFieldDeclScope(S);
13697     PushOnScopeChains(New, S, !IsForwardReference);
13698     if (IsForwardReference)
13699       SearchDC->makeDeclVisibleInContext(New);
13700   } else {
13701     CurContext->addDecl(New);
13702   }
13703
13704   // If this is the C FILE type, notify the AST context.
13705   if (IdentifierInfo *II = New->getIdentifier())
13706     if (!New->isInvalidDecl() &&
13707         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13708         II->isStr("FILE"))
13709       Context.setFILEDecl(New);
13710
13711   if (PrevDecl)
13712     mergeDeclAttributes(New, PrevDecl);
13713
13714   // If there's a #pragma GCC visibility in scope, set the visibility of this
13715   // record.
13716   AddPushedVisibilityAttribute(New);
13717
13718   OwnedDecl = true;
13719   // In C++, don't return an invalid declaration. We can't recover well from
13720   // the cases where we make the type anonymous.
13721   if (Invalid && getLangOpts().CPlusPlus) {
13722     if (New->isBeingDefined())
13723       if (auto RD = dyn_cast<RecordDecl>(New))
13724         RD->completeDefinition();
13725     return nullptr;
13726   } else {
13727     return New;
13728   }
13729 }
13730
13731 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13732   AdjustDeclIfTemplate(TagD);
13733   TagDecl *Tag = cast<TagDecl>(TagD);
13734
13735   // Enter the tag context.
13736   PushDeclContext(S, Tag);
13737
13738   ActOnDocumentableDecl(TagD);
13739
13740   // If there's a #pragma GCC visibility in scope, set the visibility of this
13741   // record.
13742   AddPushedVisibilityAttribute(Tag);
13743 }
13744
13745 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13746   assert(isa<ObjCContainerDecl>(IDecl) &&
13747          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13748   DeclContext *OCD = cast<DeclContext>(IDecl);
13749   assert(getContainingDC(OCD) == CurContext &&
13750       "The next DeclContext should be lexically contained in the current one.");
13751   CurContext = OCD;
13752   return IDecl;
13753 }
13754
13755 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13756                                            SourceLocation FinalLoc,
13757                                            bool IsFinalSpelledSealed,
13758                                            SourceLocation LBraceLoc) {
13759   AdjustDeclIfTemplate(TagD);
13760   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13761
13762   FieldCollector->StartClass();
13763
13764   if (!Record->getIdentifier())
13765     return;
13766
13767   if (FinalLoc.isValid())
13768     Record->addAttr(new (Context)
13769                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13770
13771   // C++ [class]p2:
13772   //   [...] The class-name is also inserted into the scope of the
13773   //   class itself; this is known as the injected-class-name. For
13774   //   purposes of access checking, the injected-class-name is treated
13775   //   as if it were a public member name.
13776   CXXRecordDecl *InjectedClassName
13777     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13778                             Record->getLocStart(), Record->getLocation(),
13779                             Record->getIdentifier(),
13780                             /*PrevDecl=*/nullptr,
13781                             /*DelayTypeCreation=*/true);
13782   Context.getTypeDeclType(InjectedClassName, Record);
13783   InjectedClassName->setImplicit();
13784   InjectedClassName->setAccess(AS_public);
13785   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13786       InjectedClassName->setDescribedClassTemplate(Template);
13787   PushOnScopeChains(InjectedClassName, S);
13788   assert(InjectedClassName->isInjectedClassName() &&
13789          "Broken injected-class-name");
13790 }
13791
13792 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13793                                     SourceRange BraceRange) {
13794   AdjustDeclIfTemplate(TagD);
13795   TagDecl *Tag = cast<TagDecl>(TagD);
13796   Tag->setBraceRange(BraceRange);
13797
13798   // Make sure we "complete" the definition even it is invalid.
13799   if (Tag->isBeingDefined()) {
13800     assert(Tag->isInvalidDecl() && "We should already have completed it");
13801     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13802       RD->completeDefinition();
13803   }
13804
13805   if (isa<CXXRecordDecl>(Tag)) {
13806     FieldCollector->FinishClass();
13807   }
13808
13809   // Exit this scope of this tag's definition.
13810   PopDeclContext();
13811
13812   if (getCurLexicalContext()->isObjCContainer() &&
13813       Tag->getDeclContext()->isFileContext())
13814     Tag->setTopLevelDeclInObjCContainer();
13815
13816   // Notify the consumer that we've defined a tag.
13817   if (!Tag->isInvalidDecl())
13818     Consumer.HandleTagDeclDefinition(Tag);
13819 }
13820
13821 void Sema::ActOnObjCContainerFinishDefinition() {
13822   // Exit this scope of this interface definition.
13823   PopDeclContext();
13824 }
13825
13826 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13827   assert(DC == CurContext && "Mismatch of container contexts");
13828   OriginalLexicalContext = DC;
13829   ActOnObjCContainerFinishDefinition();
13830 }
13831
13832 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13833   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13834   OriginalLexicalContext = nullptr;
13835 }
13836
13837 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13838   AdjustDeclIfTemplate(TagD);
13839   TagDecl *Tag = cast<TagDecl>(TagD);
13840   Tag->setInvalidDecl();
13841
13842   // Make sure we "complete" the definition even it is invalid.
13843   if (Tag->isBeingDefined()) {
13844     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13845       RD->completeDefinition();
13846   }
13847
13848   // We're undoing ActOnTagStartDefinition here, not
13849   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13850   // the FieldCollector.
13851
13852   PopDeclContext();
13853 }
13854
13855 // Note that FieldName may be null for anonymous bitfields.
13856 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13857                                 IdentifierInfo *FieldName,
13858                                 QualType FieldTy, bool IsMsStruct,
13859                                 Expr *BitWidth, bool *ZeroWidth) {
13860   // Default to true; that shouldn't confuse checks for emptiness
13861   if (ZeroWidth)
13862     *ZeroWidth = true;
13863
13864   // C99 6.7.2.1p4 - verify the field type.
13865   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13866   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13867     // Handle incomplete types with specific error.
13868     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13869       return ExprError();
13870     if (FieldName)
13871       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13872         << FieldName << FieldTy << BitWidth->getSourceRange();
13873     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13874       << FieldTy << BitWidth->getSourceRange();
13875   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13876                                              UPPC_BitFieldWidth))
13877     return ExprError();
13878
13879   // If the bit-width is type- or value-dependent, don't try to check
13880   // it now.
13881   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13882     return BitWidth;
13883
13884   llvm::APSInt Value;
13885   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13886   if (ICE.isInvalid())
13887     return ICE;
13888   BitWidth = ICE.get();
13889
13890   if (Value != 0 && ZeroWidth)
13891     *ZeroWidth = false;
13892
13893   // Zero-width bitfield is ok for anonymous field.
13894   if (Value == 0 && FieldName)
13895     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13896
13897   if (Value.isSigned() && Value.isNegative()) {
13898     if (FieldName)
13899       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13900                << FieldName << Value.toString(10);
13901     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13902       << Value.toString(10);
13903   }
13904
13905   if (!FieldTy->isDependentType()) {
13906     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13907     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13908     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13909
13910     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13911     // ABI.
13912     bool CStdConstraintViolation =
13913         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13914     bool MSBitfieldViolation =
13915         Value.ugt(TypeStorageSize) &&
13916         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13917     if (CStdConstraintViolation || MSBitfieldViolation) {
13918       unsigned DiagWidth =
13919           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13920       if (FieldName)
13921         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13922                << FieldName << (unsigned)Value.getZExtValue()
13923                << !CStdConstraintViolation << DiagWidth;
13924
13925       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13926              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13927              << DiagWidth;
13928     }
13929
13930     // Warn on types where the user might conceivably expect to get all
13931     // specified bits as value bits: that's all integral types other than
13932     // 'bool'.
13933     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13934       if (FieldName)
13935         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13936             << FieldName << (unsigned)Value.getZExtValue()
13937             << (unsigned)TypeWidth;
13938       else
13939         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13940             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13941     }
13942   }
13943
13944   return BitWidth;
13945 }
13946
13947 /// ActOnField - Each field of a C struct/union is passed into this in order
13948 /// to create a FieldDecl object for it.
13949 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13950                        Declarator &D, Expr *BitfieldWidth) {
13951   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13952                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13953                                /*InitStyle=*/ICIS_NoInit, AS_public);
13954   return Res;
13955 }
13956
13957 /// HandleField - Analyze a field of a C struct or a C++ data member.
13958 ///
13959 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13960                              SourceLocation DeclStart,
13961                              Declarator &D, Expr *BitWidth,
13962                              InClassInitStyle InitStyle,
13963                              AccessSpecifier AS) {
13964   if (D.isDecompositionDeclarator()) {
13965     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
13966     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
13967       << Decomp.getSourceRange();
13968     return nullptr;
13969   }
13970
13971   IdentifierInfo *II = D.getIdentifier();
13972   SourceLocation Loc = DeclStart;
13973   if (II) Loc = D.getIdentifierLoc();
13974
13975   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13976   QualType T = TInfo->getType();
13977   if (getLangOpts().CPlusPlus) {
13978     CheckExtraCXXDefaultArguments(D);
13979
13980     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13981                                         UPPC_DataMemberType)) {
13982       D.setInvalidType();
13983       T = Context.IntTy;
13984       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13985     }
13986   }
13987
13988   // TR 18037 does not allow fields to be declared with address spaces.
13989   if (T.getQualifiers().hasAddressSpace()) {
13990     Diag(Loc, diag::err_field_with_address_space);
13991     D.setInvalidType();
13992   }
13993
13994   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13995   // used as structure or union field: image, sampler, event or block types.
13996   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13997                           T->isSamplerT() || T->isBlockPointerType())) {
13998     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13999     D.setInvalidType();
14000   }
14001
14002   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14003
14004   if (D.getDeclSpec().isInlineSpecified())
14005     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14006         << getLangOpts().CPlusPlus1z;
14007   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14008     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14009          diag::err_invalid_thread)
14010       << DeclSpec::getSpecifierName(TSCS);
14011
14012   // Check to see if this name was declared as a member previously
14013   NamedDecl *PrevDecl = nullptr;
14014   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14015   LookupName(Previous, S);
14016   switch (Previous.getResultKind()) {
14017     case LookupResult::Found:
14018     case LookupResult::FoundUnresolvedValue:
14019       PrevDecl = Previous.getAsSingle<NamedDecl>();
14020       break;
14021
14022     case LookupResult::FoundOverloaded:
14023       PrevDecl = Previous.getRepresentativeDecl();
14024       break;
14025
14026     case LookupResult::NotFound:
14027     case LookupResult::NotFoundInCurrentInstantiation:
14028     case LookupResult::Ambiguous:
14029       break;
14030   }
14031   Previous.suppressDiagnostics();
14032
14033   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14034     // Maybe we will complain about the shadowed template parameter.
14035     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14036     // Just pretend that we didn't see the previous declaration.
14037     PrevDecl = nullptr;
14038   }
14039
14040   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14041     PrevDecl = nullptr;
14042
14043   bool Mutable
14044     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14045   SourceLocation TSSL = D.getLocStart();
14046   FieldDecl *NewFD
14047     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14048                      TSSL, AS, PrevDecl, &D);
14049
14050   if (NewFD->isInvalidDecl())
14051     Record->setInvalidDecl();
14052
14053   if (D.getDeclSpec().isModulePrivateSpecified())
14054     NewFD->setModulePrivate();
14055
14056   if (NewFD->isInvalidDecl() && PrevDecl) {
14057     // Don't introduce NewFD into scope; there's already something
14058     // with the same name in the same scope.
14059   } else if (II) {
14060     PushOnScopeChains(NewFD, S);
14061   } else
14062     Record->addDecl(NewFD);
14063
14064   return NewFD;
14065 }
14066
14067 /// \brief Build a new FieldDecl and check its well-formedness.
14068 ///
14069 /// This routine builds a new FieldDecl given the fields name, type,
14070 /// record, etc. \p PrevDecl should refer to any previous declaration
14071 /// with the same name and in the same scope as the field to be
14072 /// created.
14073 ///
14074 /// \returns a new FieldDecl.
14075 ///
14076 /// \todo The Declarator argument is a hack. It will be removed once
14077 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14078                                 TypeSourceInfo *TInfo,
14079                                 RecordDecl *Record, SourceLocation Loc,
14080                                 bool Mutable, Expr *BitWidth,
14081                                 InClassInitStyle InitStyle,
14082                                 SourceLocation TSSL,
14083                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14084                                 Declarator *D) {
14085   IdentifierInfo *II = Name.getAsIdentifierInfo();
14086   bool InvalidDecl = false;
14087   if (D) InvalidDecl = D->isInvalidType();
14088
14089   // If we receive a broken type, recover by assuming 'int' and
14090   // marking this declaration as invalid.
14091   if (T.isNull()) {
14092     InvalidDecl = true;
14093     T = Context.IntTy;
14094   }
14095
14096   QualType EltTy = Context.getBaseElementType(T);
14097   if (!EltTy->isDependentType()) {
14098     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14099       // Fields of incomplete type force their record to be invalid.
14100       Record->setInvalidDecl();
14101       InvalidDecl = true;
14102     } else {
14103       NamedDecl *Def;
14104       EltTy->isIncompleteType(&Def);
14105       if (Def && Def->isInvalidDecl()) {
14106         Record->setInvalidDecl();
14107         InvalidDecl = true;
14108       }
14109     }
14110   }
14111
14112   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14113   if (BitWidth && getLangOpts().OpenCL) {
14114     Diag(Loc, diag::err_opencl_bitfields);
14115     InvalidDecl = true;
14116   }
14117
14118   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14119   // than a variably modified type.
14120   if (!InvalidDecl && T->isVariablyModifiedType()) {
14121     bool SizeIsNegative;
14122     llvm::APSInt Oversized;
14123
14124     TypeSourceInfo *FixedTInfo =
14125       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14126                                                     SizeIsNegative,
14127                                                     Oversized);
14128     if (FixedTInfo) {
14129       Diag(Loc, diag::warn_illegal_constant_array_size);
14130       TInfo = FixedTInfo;
14131       T = FixedTInfo->getType();
14132     } else {
14133       if (SizeIsNegative)
14134         Diag(Loc, diag::err_typecheck_negative_array_size);
14135       else if (Oversized.getBoolValue())
14136         Diag(Loc, diag::err_array_too_large)
14137           << Oversized.toString(10);
14138       else
14139         Diag(Loc, diag::err_typecheck_field_variable_size);
14140       InvalidDecl = true;
14141     }
14142   }
14143
14144   // Fields can not have abstract class types
14145   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14146                                              diag::err_abstract_type_in_decl,
14147                                              AbstractFieldType))
14148     InvalidDecl = true;
14149
14150   bool ZeroWidth = false;
14151   if (InvalidDecl)
14152     BitWidth = nullptr;
14153   // If this is declared as a bit-field, check the bit-field.
14154   if (BitWidth) {
14155     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14156                               &ZeroWidth).get();
14157     if (!BitWidth) {
14158       InvalidDecl = true;
14159       BitWidth = nullptr;
14160       ZeroWidth = false;
14161     }
14162   }
14163
14164   // Check that 'mutable' is consistent with the type of the declaration.
14165   if (!InvalidDecl && Mutable) {
14166     unsigned DiagID = 0;
14167     if (T->isReferenceType())
14168       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14169                                         : diag::err_mutable_reference;
14170     else if (T.isConstQualified())
14171       DiagID = diag::err_mutable_const;
14172
14173     if (DiagID) {
14174       SourceLocation ErrLoc = Loc;
14175       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14176         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14177       Diag(ErrLoc, DiagID);
14178       if (DiagID != diag::ext_mutable_reference) {
14179         Mutable = false;
14180         InvalidDecl = true;
14181       }
14182     }
14183   }
14184
14185   // C++11 [class.union]p8 (DR1460):
14186   //   At most one variant member of a union may have a
14187   //   brace-or-equal-initializer.
14188   if (InitStyle != ICIS_NoInit)
14189     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14190
14191   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14192                                        BitWidth, Mutable, InitStyle);
14193   if (InvalidDecl)
14194     NewFD->setInvalidDecl();
14195
14196   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14197     Diag(Loc, diag::err_duplicate_member) << II;
14198     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14199     NewFD->setInvalidDecl();
14200   }
14201
14202   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14203     if (Record->isUnion()) {
14204       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14205         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14206         if (RDecl->getDefinition()) {
14207           // C++ [class.union]p1: An object of a class with a non-trivial
14208           // constructor, a non-trivial copy constructor, a non-trivial
14209           // destructor, or a non-trivial copy assignment operator
14210           // cannot be a member of a union, nor can an array of such
14211           // objects.
14212           if (CheckNontrivialField(NewFD))
14213             NewFD->setInvalidDecl();
14214         }
14215       }
14216
14217       // C++ [class.union]p1: If a union contains a member of reference type,
14218       // the program is ill-formed, except when compiling with MSVC extensions
14219       // enabled.
14220       if (EltTy->isReferenceType()) {
14221         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14222                                     diag::ext_union_member_of_reference_type :
14223                                     diag::err_union_member_of_reference_type)
14224           << NewFD->getDeclName() << EltTy;
14225         if (!getLangOpts().MicrosoftExt)
14226           NewFD->setInvalidDecl();
14227       }
14228     }
14229   }
14230
14231   // FIXME: We need to pass in the attributes given an AST
14232   // representation, not a parser representation.
14233   if (D) {
14234     // FIXME: The current scope is almost... but not entirely... correct here.
14235     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14236
14237     if (NewFD->hasAttrs())
14238       CheckAlignasUnderalignment(NewFD);
14239   }
14240
14241   // In auto-retain/release, infer strong retension for fields of
14242   // retainable type.
14243   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14244     NewFD->setInvalidDecl();
14245
14246   if (T.isObjCGCWeak())
14247     Diag(Loc, diag::warn_attribute_weak_on_field);
14248
14249   NewFD->setAccess(AS);
14250   return NewFD;
14251 }
14252
14253 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14254   assert(FD);
14255   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14256
14257   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14258     return false;
14259
14260   QualType EltTy = Context.getBaseElementType(FD->getType());
14261   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14262     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14263     if (RDecl->getDefinition()) {
14264       // We check for copy constructors before constructors
14265       // because otherwise we'll never get complaints about
14266       // copy constructors.
14267
14268       CXXSpecialMember member = CXXInvalid;
14269       // We're required to check for any non-trivial constructors. Since the
14270       // implicit default constructor is suppressed if there are any
14271       // user-declared constructors, we just need to check that there is a
14272       // trivial default constructor and a trivial copy constructor. (We don't
14273       // worry about move constructors here, since this is a C++98 check.)
14274       if (RDecl->hasNonTrivialCopyConstructor())
14275         member = CXXCopyConstructor;
14276       else if (!RDecl->hasTrivialDefaultConstructor())
14277         member = CXXDefaultConstructor;
14278       else if (RDecl->hasNonTrivialCopyAssignment())
14279         member = CXXCopyAssignment;
14280       else if (RDecl->hasNonTrivialDestructor())
14281         member = CXXDestructor;
14282
14283       if (member != CXXInvalid) {
14284         if (!getLangOpts().CPlusPlus11 &&
14285             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14286           // Objective-C++ ARC: it is an error to have a non-trivial field of
14287           // a union. However, system headers in Objective-C programs
14288           // occasionally have Objective-C lifetime objects within unions,
14289           // and rather than cause the program to fail, we make those
14290           // members unavailable.
14291           SourceLocation Loc = FD->getLocation();
14292           if (getSourceManager().isInSystemHeader(Loc)) {
14293             if (!FD->hasAttr<UnavailableAttr>())
14294               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14295                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14296             return false;
14297           }
14298         }
14299
14300         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14301                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14302                diag::err_illegal_union_or_anon_struct_member)
14303           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14304         DiagnoseNontrivial(RDecl, member);
14305         return !getLangOpts().CPlusPlus11;
14306       }
14307     }
14308   }
14309
14310   return false;
14311 }
14312
14313 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14314 ///  AST enum value.
14315 static ObjCIvarDecl::AccessControl
14316 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14317   switch (ivarVisibility) {
14318   default: llvm_unreachable("Unknown visitibility kind");
14319   case tok::objc_private: return ObjCIvarDecl::Private;
14320   case tok::objc_public: return ObjCIvarDecl::Public;
14321   case tok::objc_protected: return ObjCIvarDecl::Protected;
14322   case tok::objc_package: return ObjCIvarDecl::Package;
14323   }
14324 }
14325
14326 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14327 /// in order to create an IvarDecl object for it.
14328 Decl *Sema::ActOnIvar(Scope *S,
14329                                 SourceLocation DeclStart,
14330                                 Declarator &D, Expr *BitfieldWidth,
14331                                 tok::ObjCKeywordKind Visibility) {
14332
14333   IdentifierInfo *II = D.getIdentifier();
14334   Expr *BitWidth = (Expr*)BitfieldWidth;
14335   SourceLocation Loc = DeclStart;
14336   if (II) Loc = D.getIdentifierLoc();
14337
14338   // FIXME: Unnamed fields can be handled in various different ways, for
14339   // example, unnamed unions inject all members into the struct namespace!
14340
14341   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14342   QualType T = TInfo->getType();
14343
14344   if (BitWidth) {
14345     // 6.7.2.1p3, 6.7.2.1p4
14346     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14347     if (!BitWidth)
14348       D.setInvalidType();
14349   } else {
14350     // Not a bitfield.
14351
14352     // validate II.
14353
14354   }
14355   if (T->isReferenceType()) {
14356     Diag(Loc, diag::err_ivar_reference_type);
14357     D.setInvalidType();
14358   }
14359   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14360   // than a variably modified type.
14361   else if (T->isVariablyModifiedType()) {
14362     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14363     D.setInvalidType();
14364   }
14365
14366   // Get the visibility (access control) for this ivar.
14367   ObjCIvarDecl::AccessControl ac =
14368     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14369                                         : ObjCIvarDecl::None;
14370   // Must set ivar's DeclContext to its enclosing interface.
14371   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14372   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14373     return nullptr;
14374   ObjCContainerDecl *EnclosingContext;
14375   if (ObjCImplementationDecl *IMPDecl =
14376       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14377     if (LangOpts.ObjCRuntime.isFragile()) {
14378     // Case of ivar declared in an implementation. Context is that of its class.
14379       EnclosingContext = IMPDecl->getClassInterface();
14380       assert(EnclosingContext && "Implementation has no class interface!");
14381     }
14382     else
14383       EnclosingContext = EnclosingDecl;
14384   } else {
14385     if (ObjCCategoryDecl *CDecl =
14386         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14387       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14388         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14389         return nullptr;
14390       }
14391     }
14392     EnclosingContext = EnclosingDecl;
14393   }
14394
14395   // Construct the decl.
14396   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14397                                              DeclStart, Loc, II, T,
14398                                              TInfo, ac, (Expr *)BitfieldWidth);
14399
14400   if (II) {
14401     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14402                                            ForRedeclaration);
14403     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14404         && !isa<TagDecl>(PrevDecl)) {
14405       Diag(Loc, diag::err_duplicate_member) << II;
14406       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14407       NewID->setInvalidDecl();
14408     }
14409   }
14410
14411   // Process attributes attached to the ivar.
14412   ProcessDeclAttributes(S, NewID, D);
14413
14414   if (D.isInvalidType())
14415     NewID->setInvalidDecl();
14416
14417   // In ARC, infer 'retaining' for ivars of retainable type.
14418   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14419     NewID->setInvalidDecl();
14420
14421   if (D.getDeclSpec().isModulePrivateSpecified())
14422     NewID->setModulePrivate();
14423
14424   if (II) {
14425     // FIXME: When interfaces are DeclContexts, we'll need to add
14426     // these to the interface.
14427     S->AddDecl(NewID);
14428     IdResolver.AddDecl(NewID);
14429   }
14430
14431   if (LangOpts.ObjCRuntime.isNonFragile() &&
14432       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14433     Diag(Loc, diag::warn_ivars_in_interface);
14434
14435   return NewID;
14436 }
14437
14438 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14439 /// class and class extensions. For every class \@interface and class
14440 /// extension \@interface, if the last ivar is a bitfield of any type,
14441 /// then add an implicit `char :0` ivar to the end of that interface.
14442 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14443                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14444   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14445     return;
14446
14447   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14448   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14449
14450   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14451     return;
14452   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14453   if (!ID) {
14454     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14455       if (!CD->IsClassExtension())
14456         return;
14457     }
14458     // No need to add this to end of @implementation.
14459     else
14460       return;
14461   }
14462   // All conditions are met. Add a new bitfield to the tail end of ivars.
14463   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14464   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14465
14466   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14467                               DeclLoc, DeclLoc, nullptr,
14468                               Context.CharTy,
14469                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14470                                                                DeclLoc),
14471                               ObjCIvarDecl::Private, BW,
14472                               true);
14473   AllIvarDecls.push_back(Ivar);
14474 }
14475
14476 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14477                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14478                        SourceLocation RBrac, AttributeList *Attr) {
14479   assert(EnclosingDecl && "missing record or interface decl");
14480
14481   // If this is an Objective-C @implementation or category and we have
14482   // new fields here we should reset the layout of the interface since
14483   // it will now change.
14484   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14485     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14486     switch (DC->getKind()) {
14487     default: break;
14488     case Decl::ObjCCategory:
14489       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14490       break;
14491     case Decl::ObjCImplementation:
14492       Context.
14493         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14494       break;
14495     }
14496   }
14497
14498   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14499
14500   // Start counting up the number of named members; make sure to include
14501   // members of anonymous structs and unions in the total.
14502   unsigned NumNamedMembers = 0;
14503   if (Record) {
14504     for (const auto *I : Record->decls()) {
14505       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14506         if (IFD->getDeclName())
14507           ++NumNamedMembers;
14508     }
14509   }
14510
14511   // Verify that all the fields are okay.
14512   SmallVector<FieldDecl*, 32> RecFields;
14513
14514   bool ObjCFieldLifetimeErrReported = false;
14515   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14516        i != end; ++i) {
14517     FieldDecl *FD = cast<FieldDecl>(*i);
14518
14519     // Get the type for the field.
14520     const Type *FDTy = FD->getType().getTypePtr();
14521
14522     if (!FD->isAnonymousStructOrUnion()) {
14523       // Remember all fields written by the user.
14524       RecFields.push_back(FD);
14525     }
14526
14527     // If the field is already invalid for some reason, don't emit more
14528     // diagnostics about it.
14529     if (FD->isInvalidDecl()) {
14530       EnclosingDecl->setInvalidDecl();
14531       continue;
14532     }
14533
14534     // C99 6.7.2.1p2:
14535     //   A structure or union shall not contain a member with
14536     //   incomplete or function type (hence, a structure shall not
14537     //   contain an instance of itself, but may contain a pointer to
14538     //   an instance of itself), except that the last member of a
14539     //   structure with more than one named member may have incomplete
14540     //   array type; such a structure (and any union containing,
14541     //   possibly recursively, a member that is such a structure)
14542     //   shall not be a member of a structure or an element of an
14543     //   array.
14544     if (FDTy->isFunctionType()) {
14545       // Field declared as a function.
14546       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14547         << FD->getDeclName();
14548       FD->setInvalidDecl();
14549       EnclosingDecl->setInvalidDecl();
14550       continue;
14551     } else if (FDTy->isIncompleteArrayType() && Record &&
14552                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14553                 ((getLangOpts().MicrosoftExt ||
14554                   getLangOpts().CPlusPlus) &&
14555                  (i + 1 == Fields.end() || Record->isUnion())))) {
14556       // Flexible array member.
14557       // Microsoft and g++ is more permissive regarding flexible array.
14558       // It will accept flexible array in union and also
14559       // as the sole element of a struct/class.
14560       unsigned DiagID = 0;
14561       if (Record->isUnion())
14562         DiagID = getLangOpts().MicrosoftExt
14563                      ? diag::ext_flexible_array_union_ms
14564                      : getLangOpts().CPlusPlus
14565                            ? diag::ext_flexible_array_union_gnu
14566                            : diag::err_flexible_array_union;
14567       else if (NumNamedMembers < 1)
14568         DiagID = getLangOpts().MicrosoftExt
14569                      ? diag::ext_flexible_array_empty_aggregate_ms
14570                      : getLangOpts().CPlusPlus
14571                            ? diag::ext_flexible_array_empty_aggregate_gnu
14572                            : diag::err_flexible_array_empty_aggregate;
14573
14574       if (DiagID)
14575         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14576                                         << Record->getTagKind();
14577       // While the layout of types that contain virtual bases is not specified
14578       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14579       // virtual bases after the derived members.  This would make a flexible
14580       // array member declared at the end of an object not adjacent to the end
14581       // of the type.
14582       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14583         if (RD->getNumVBases() != 0)
14584           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14585             << FD->getDeclName() << Record->getTagKind();
14586       if (!getLangOpts().C99)
14587         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14588           << FD->getDeclName() << Record->getTagKind();
14589
14590       // If the element type has a non-trivial destructor, we would not
14591       // implicitly destroy the elements, so disallow it for now.
14592       //
14593       // FIXME: GCC allows this. We should probably either implicitly delete
14594       // the destructor of the containing class, or just allow this.
14595       QualType BaseElem = Context.getBaseElementType(FD->getType());
14596       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14597         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14598           << FD->getDeclName() << FD->getType();
14599         FD->setInvalidDecl();
14600         EnclosingDecl->setInvalidDecl();
14601         continue;
14602       }
14603       // Okay, we have a legal flexible array member at the end of the struct.
14604       Record->setHasFlexibleArrayMember(true);
14605     } else if (!FDTy->isDependentType() &&
14606                RequireCompleteType(FD->getLocation(), FD->getType(),
14607                                    diag::err_field_incomplete)) {
14608       // Incomplete type
14609       FD->setInvalidDecl();
14610       EnclosingDecl->setInvalidDecl();
14611       continue;
14612     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14613       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14614         // A type which contains a flexible array member is considered to be a
14615         // flexible array member.
14616         Record->setHasFlexibleArrayMember(true);
14617         if (!Record->isUnion()) {
14618           // If this is a struct/class and this is not the last element, reject
14619           // it.  Note that GCC supports variable sized arrays in the middle of
14620           // structures.
14621           if (i + 1 != Fields.end())
14622             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14623               << FD->getDeclName() << FD->getType();
14624           else {
14625             // We support flexible arrays at the end of structs in
14626             // other structs as an extension.
14627             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14628               << FD->getDeclName();
14629           }
14630         }
14631       }
14632       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14633           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14634                                  diag::err_abstract_type_in_decl,
14635                                  AbstractIvarType)) {
14636         // Ivars can not have abstract class types
14637         FD->setInvalidDecl();
14638       }
14639       if (Record && FDTTy->getDecl()->hasObjectMember())
14640         Record->setHasObjectMember(true);
14641       if (Record && FDTTy->getDecl()->hasVolatileMember())
14642         Record->setHasVolatileMember(true);
14643     } else if (FDTy->isObjCObjectType()) {
14644       /// A field cannot be an Objective-c object
14645       Diag(FD->getLocation(), diag::err_statically_allocated_object)
14646         << FixItHint::CreateInsertion(FD->getLocation(), "*");
14647       QualType T = Context.getObjCObjectPointerType(FD->getType());
14648       FD->setType(T);
14649     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
14650                Record && !ObjCFieldLifetimeErrReported &&
14651                (!getLangOpts().CPlusPlus || Record->isUnion())) {
14652       // It's an error in ARC or Weak if a field has lifetime.
14653       // We don't want to report this in a system header, though,
14654       // so we just make the field unavailable.
14655       // FIXME: that's really not sufficient; we need to make the type
14656       // itself invalid to, say, initialize or copy.
14657       QualType T = FD->getType();
14658       if (T.hasNonTrivialObjCLifetime()) {
14659         SourceLocation loc = FD->getLocation();
14660         if (getSourceManager().isInSystemHeader(loc)) {
14661           if (!FD->hasAttr<UnavailableAttr>()) {
14662             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14663                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14664           }
14665         } else {
14666           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14667             << T->isBlockPointerType() << Record->getTagKind();
14668         }
14669         ObjCFieldLifetimeErrReported = true;
14670       }
14671     } else if (getLangOpts().ObjC1 &&
14672                getLangOpts().getGC() != LangOptions::NonGC &&
14673                Record && !Record->hasObjectMember()) {
14674       if (FD->getType()->isObjCObjectPointerType() ||
14675           FD->getType().isObjCGCStrong())
14676         Record->setHasObjectMember(true);
14677       else if (Context.getAsArrayType(FD->getType())) {
14678         QualType BaseType = Context.getBaseElementType(FD->getType());
14679         if (BaseType->isRecordType() &&
14680             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14681           Record->setHasObjectMember(true);
14682         else if (BaseType->isObjCObjectPointerType() ||
14683                  BaseType.isObjCGCStrong())
14684                Record->setHasObjectMember(true);
14685       }
14686     }
14687     if (Record && FD->getType().isVolatileQualified())
14688       Record->setHasVolatileMember(true);
14689     // Keep track of the number of named members.
14690     if (FD->getIdentifier())
14691       ++NumNamedMembers;
14692   }
14693
14694   // Okay, we successfully defined 'Record'.
14695   if (Record) {
14696     bool Completed = false;
14697     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14698       if (!CXXRecord->isInvalidDecl()) {
14699         // Set access bits correctly on the directly-declared conversions.
14700         for (CXXRecordDecl::conversion_iterator
14701                I = CXXRecord->conversion_begin(),
14702                E = CXXRecord->conversion_end(); I != E; ++I)
14703           I.setAccess((*I)->getAccess());
14704       }
14705
14706       if (!CXXRecord->isDependentType()) {
14707         if (CXXRecord->hasUserDeclaredDestructor()) {
14708           // Adjust user-defined destructor exception spec.
14709           if (getLangOpts().CPlusPlus11)
14710             AdjustDestructorExceptionSpec(CXXRecord,
14711                                           CXXRecord->getDestructor());
14712         }
14713
14714         if (!CXXRecord->isInvalidDecl()) {
14715           // Add any implicitly-declared members to this class.
14716           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14717
14718           // If we have virtual base classes, we may end up finding multiple
14719           // final overriders for a given virtual function. Check for this
14720           // problem now.
14721           if (CXXRecord->getNumVBases()) {
14722             CXXFinalOverriderMap FinalOverriders;
14723             CXXRecord->getFinalOverriders(FinalOverriders);
14724
14725             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14726                                              MEnd = FinalOverriders.end();
14727                  M != MEnd; ++M) {
14728               for (OverridingMethods::iterator SO = M->second.begin(),
14729                                             SOEnd = M->second.end();
14730                    SO != SOEnd; ++SO) {
14731                 assert(SO->second.size() > 0 &&
14732                        "Virtual function without overridding functions?");
14733                 if (SO->second.size() == 1)
14734                   continue;
14735
14736                 // C++ [class.virtual]p2:
14737                 //   In a derived class, if a virtual member function of a base
14738                 //   class subobject has more than one final overrider the
14739                 //   program is ill-formed.
14740                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14741                   << (const NamedDecl *)M->first << Record;
14742                 Diag(M->first->getLocation(),
14743                      diag::note_overridden_virtual_function);
14744                 for (OverridingMethods::overriding_iterator
14745                           OM = SO->second.begin(),
14746                        OMEnd = SO->second.end();
14747                      OM != OMEnd; ++OM)
14748                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14749                     << (const NamedDecl *)M->first << OM->Method->getParent();
14750
14751                 Record->setInvalidDecl();
14752               }
14753             }
14754             CXXRecord->completeDefinition(&FinalOverriders);
14755             Completed = true;
14756           }
14757         }
14758       }
14759     }
14760
14761     if (!Completed)
14762       Record->completeDefinition();
14763
14764     // We may have deferred checking for a deleted destructor. Check now.
14765     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14766       auto *Dtor = CXXRecord->getDestructor();
14767       if (Dtor && Dtor->isImplicit() &&
14768           ShouldDeleteSpecialMember(Dtor, CXXDestructor))
14769         SetDeclDeleted(Dtor, CXXRecord->getLocation());
14770     }
14771
14772     if (Record->hasAttrs()) {
14773       CheckAlignasUnderalignment(Record);
14774
14775       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14776         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14777                                            IA->getRange(), IA->getBestCase(),
14778                                            IA->getSemanticSpelling());
14779     }
14780
14781     // Check if the structure/union declaration is a type that can have zero
14782     // size in C. For C this is a language extension, for C++ it may cause
14783     // compatibility problems.
14784     bool CheckForZeroSize;
14785     if (!getLangOpts().CPlusPlus) {
14786       CheckForZeroSize = true;
14787     } else {
14788       // For C++ filter out types that cannot be referenced in C code.
14789       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14790       CheckForZeroSize =
14791           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14792           !CXXRecord->isDependentType() &&
14793           CXXRecord->isCLike();
14794     }
14795     if (CheckForZeroSize) {
14796       bool ZeroSize = true;
14797       bool IsEmpty = true;
14798       unsigned NonBitFields = 0;
14799       for (RecordDecl::field_iterator I = Record->field_begin(),
14800                                       E = Record->field_end();
14801            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14802         IsEmpty = false;
14803         if (I->isUnnamedBitfield()) {
14804           if (I->getBitWidthValue(Context) > 0)
14805             ZeroSize = false;
14806         } else {
14807           ++NonBitFields;
14808           QualType FieldType = I->getType();
14809           if (FieldType->isIncompleteType() ||
14810               !Context.getTypeSizeInChars(FieldType).isZero())
14811             ZeroSize = false;
14812         }
14813       }
14814
14815       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14816       // allowed in C++, but warn if its declaration is inside
14817       // extern "C" block.
14818       if (ZeroSize) {
14819         Diag(RecLoc, getLangOpts().CPlusPlus ?
14820                          diag::warn_zero_size_struct_union_in_extern_c :
14821                          diag::warn_zero_size_struct_union_compat)
14822           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14823       }
14824
14825       // Structs without named members are extension in C (C99 6.7.2.1p7),
14826       // but are accepted by GCC.
14827       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14828         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14829                                diag::ext_no_named_members_in_struct_union)
14830           << Record->isUnion();
14831       }
14832     }
14833   } else {
14834     ObjCIvarDecl **ClsFields =
14835       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14836     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14837       ID->setEndOfDefinitionLoc(RBrac);
14838       // Add ivar's to class's DeclContext.
14839       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14840         ClsFields[i]->setLexicalDeclContext(ID);
14841         ID->addDecl(ClsFields[i]);
14842       }
14843       // Must enforce the rule that ivars in the base classes may not be
14844       // duplicates.
14845       if (ID->getSuperClass())
14846         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14847     } else if (ObjCImplementationDecl *IMPDecl =
14848                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14849       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14850       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14851         // Ivar declared in @implementation never belongs to the implementation.
14852         // Only it is in implementation's lexical context.
14853         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14854       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14855       IMPDecl->setIvarLBraceLoc(LBrac);
14856       IMPDecl->setIvarRBraceLoc(RBrac);
14857     } else if (ObjCCategoryDecl *CDecl =
14858                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14859       // case of ivars in class extension; all other cases have been
14860       // reported as errors elsewhere.
14861       // FIXME. Class extension does not have a LocEnd field.
14862       // CDecl->setLocEnd(RBrac);
14863       // Add ivar's to class extension's DeclContext.
14864       // Diagnose redeclaration of private ivars.
14865       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14866       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14867         if (IDecl) {
14868           if (const ObjCIvarDecl *ClsIvar =
14869               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14870             Diag(ClsFields[i]->getLocation(),
14871                  diag::err_duplicate_ivar_declaration);
14872             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14873             continue;
14874           }
14875           for (const auto *Ext : IDecl->known_extensions()) {
14876             if (const ObjCIvarDecl *ClsExtIvar
14877                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14878               Diag(ClsFields[i]->getLocation(),
14879                    diag::err_duplicate_ivar_declaration);
14880               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14881               continue;
14882             }
14883           }
14884         }
14885         ClsFields[i]->setLexicalDeclContext(CDecl);
14886         CDecl->addDecl(ClsFields[i]);
14887       }
14888       CDecl->setIvarLBraceLoc(LBrac);
14889       CDecl->setIvarRBraceLoc(RBrac);
14890     }
14891   }
14892
14893   if (Attr)
14894     ProcessDeclAttributeList(S, Record, Attr);
14895 }
14896
14897 /// \brief Determine whether the given integral value is representable within
14898 /// the given type T.
14899 static bool isRepresentableIntegerValue(ASTContext &Context,
14900                                         llvm::APSInt &Value,
14901                                         QualType T) {
14902   assert(T->isIntegralType(Context) && "Integral type required!");
14903   unsigned BitWidth = Context.getIntWidth(T);
14904
14905   if (Value.isUnsigned() || Value.isNonNegative()) {
14906     if (T->isSignedIntegerOrEnumerationType())
14907       --BitWidth;
14908     return Value.getActiveBits() <= BitWidth;
14909   }
14910   return Value.getMinSignedBits() <= BitWidth;
14911 }
14912
14913 // \brief Given an integral type, return the next larger integral type
14914 // (or a NULL type of no such type exists).
14915 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14916   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14917   // enum checking below.
14918   assert(T->isIntegralType(Context) && "Integral type required!");
14919   const unsigned NumTypes = 4;
14920   QualType SignedIntegralTypes[NumTypes] = {
14921     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14922   };
14923   QualType UnsignedIntegralTypes[NumTypes] = {
14924     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14925     Context.UnsignedLongLongTy
14926   };
14927
14928   unsigned BitWidth = Context.getTypeSize(T);
14929   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14930                                                         : UnsignedIntegralTypes;
14931   for (unsigned I = 0; I != NumTypes; ++I)
14932     if (Context.getTypeSize(Types[I]) > BitWidth)
14933       return Types[I];
14934
14935   return QualType();
14936 }
14937
14938 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14939                                           EnumConstantDecl *LastEnumConst,
14940                                           SourceLocation IdLoc,
14941                                           IdentifierInfo *Id,
14942                                           Expr *Val) {
14943   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14944   llvm::APSInt EnumVal(IntWidth);
14945   QualType EltTy;
14946
14947   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14948     Val = nullptr;
14949
14950   if (Val)
14951     Val = DefaultLvalueConversion(Val).get();
14952
14953   if (Val) {
14954     if (Enum->isDependentType() || Val->isTypeDependent())
14955       EltTy = Context.DependentTy;
14956     else {
14957       SourceLocation ExpLoc;
14958       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14959           !getLangOpts().MSVCCompat) {
14960         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14961         // constant-expression in the enumerator-definition shall be a converted
14962         // constant expression of the underlying type.
14963         EltTy = Enum->getIntegerType();
14964         ExprResult Converted =
14965           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14966                                            CCEK_Enumerator);
14967         if (Converted.isInvalid())
14968           Val = nullptr;
14969         else
14970           Val = Converted.get();
14971       } else if (!Val->isValueDependent() &&
14972                  !(Val = VerifyIntegerConstantExpression(Val,
14973                                                          &EnumVal).get())) {
14974         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14975       } else {
14976         if (Enum->isFixed()) {
14977           EltTy = Enum->getIntegerType();
14978
14979           // In Obj-C and Microsoft mode, require the enumeration value to be
14980           // representable in the underlying type of the enumeration. In C++11,
14981           // we perform a non-narrowing conversion as part of converted constant
14982           // expression checking.
14983           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14984             if (getLangOpts().MSVCCompat) {
14985               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14986               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14987             } else
14988               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14989           } else
14990             Val = ImpCastExprToType(Val, EltTy,
14991                                     EltTy->isBooleanType() ?
14992                                     CK_IntegralToBoolean : CK_IntegralCast)
14993                     .get();
14994         } else if (getLangOpts().CPlusPlus) {
14995           // C++11 [dcl.enum]p5:
14996           //   If the underlying type is not fixed, the type of each enumerator
14997           //   is the type of its initializing value:
14998           //     - If an initializer is specified for an enumerator, the
14999           //       initializing value has the same type as the expression.
15000           EltTy = Val->getType();
15001         } else {
15002           // C99 6.7.2.2p2:
15003           //   The expression that defines the value of an enumeration constant
15004           //   shall be an integer constant expression that has a value
15005           //   representable as an int.
15006
15007           // Complain if the value is not representable in an int.
15008           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15009             Diag(IdLoc, diag::ext_enum_value_not_int)
15010               << EnumVal.toString(10) << Val->getSourceRange()
15011               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15012           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15013             // Force the type of the expression to 'int'.
15014             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15015           }
15016           EltTy = Val->getType();
15017         }
15018       }
15019     }
15020   }
15021
15022   if (!Val) {
15023     if (Enum->isDependentType())
15024       EltTy = Context.DependentTy;
15025     else if (!LastEnumConst) {
15026       // C++0x [dcl.enum]p5:
15027       //   If the underlying type is not fixed, the type of each enumerator
15028       //   is the type of its initializing value:
15029       //     - If no initializer is specified for the first enumerator, the
15030       //       initializing value has an unspecified integral type.
15031       //
15032       // GCC uses 'int' for its unspecified integral type, as does
15033       // C99 6.7.2.2p3.
15034       if (Enum->isFixed()) {
15035         EltTy = Enum->getIntegerType();
15036       }
15037       else {
15038         EltTy = Context.IntTy;
15039       }
15040     } else {
15041       // Assign the last value + 1.
15042       EnumVal = LastEnumConst->getInitVal();
15043       ++EnumVal;
15044       EltTy = LastEnumConst->getType();
15045
15046       // Check for overflow on increment.
15047       if (EnumVal < LastEnumConst->getInitVal()) {
15048         // C++0x [dcl.enum]p5:
15049         //   If the underlying type is not fixed, the type of each enumerator
15050         //   is the type of its initializing value:
15051         //
15052         //     - Otherwise the type of the initializing value is the same as
15053         //       the type of the initializing value of the preceding enumerator
15054         //       unless the incremented value is not representable in that type,
15055         //       in which case the type is an unspecified integral type
15056         //       sufficient to contain the incremented value. If no such type
15057         //       exists, the program is ill-formed.
15058         QualType T = getNextLargerIntegralType(Context, EltTy);
15059         if (T.isNull() || Enum->isFixed()) {
15060           // There is no integral type larger enough to represent this
15061           // value. Complain, then allow the value to wrap around.
15062           EnumVal = LastEnumConst->getInitVal();
15063           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15064           ++EnumVal;
15065           if (Enum->isFixed())
15066             // When the underlying type is fixed, this is ill-formed.
15067             Diag(IdLoc, diag::err_enumerator_wrapped)
15068               << EnumVal.toString(10)
15069               << EltTy;
15070           else
15071             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15072               << EnumVal.toString(10);
15073         } else {
15074           EltTy = T;
15075         }
15076
15077         // Retrieve the last enumerator's value, extent that type to the
15078         // type that is supposed to be large enough to represent the incremented
15079         // value, then increment.
15080         EnumVal = LastEnumConst->getInitVal();
15081         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15082         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15083         ++EnumVal;
15084
15085         // If we're not in C++, diagnose the overflow of enumerator values,
15086         // which in C99 means that the enumerator value is not representable in
15087         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15088         // permits enumerator values that are representable in some larger
15089         // integral type.
15090         if (!getLangOpts().CPlusPlus && !T.isNull())
15091           Diag(IdLoc, diag::warn_enum_value_overflow);
15092       } else if (!getLangOpts().CPlusPlus &&
15093                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15094         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15095         Diag(IdLoc, diag::ext_enum_value_not_int)
15096           << EnumVal.toString(10) << 1;
15097       }
15098     }
15099   }
15100
15101   if (!EltTy->isDependentType()) {
15102     // Make the enumerator value match the signedness and size of the
15103     // enumerator's type.
15104     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15105     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15106   }
15107
15108   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15109                                   Val, EnumVal);
15110 }
15111
15112 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15113                                                 SourceLocation IILoc) {
15114   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15115       !getLangOpts().CPlusPlus)
15116     return SkipBodyInfo();
15117
15118   // We have an anonymous enum definition. Look up the first enumerator to
15119   // determine if we should merge the definition with an existing one and
15120   // skip the body.
15121   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15122                                          ForRedeclaration);
15123   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15124   if (!PrevECD)
15125     return SkipBodyInfo();
15126
15127   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15128   NamedDecl *Hidden;
15129   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15130     SkipBodyInfo Skip;
15131     Skip.Previous = Hidden;
15132     return Skip;
15133   }
15134
15135   return SkipBodyInfo();
15136 }
15137
15138 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15139                               SourceLocation IdLoc, IdentifierInfo *Id,
15140                               AttributeList *Attr,
15141                               SourceLocation EqualLoc, Expr *Val) {
15142   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15143   EnumConstantDecl *LastEnumConst =
15144     cast_or_null<EnumConstantDecl>(lastEnumConst);
15145
15146   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15147   // we find one that is.
15148   S = getNonFieldDeclScope(S);
15149
15150   // Verify that there isn't already something declared with this name in this
15151   // scope.
15152   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15153                                          ForRedeclaration);
15154   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15155     // Maybe we will complain about the shadowed template parameter.
15156     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15157     // Just pretend that we didn't see the previous declaration.
15158     PrevDecl = nullptr;
15159   }
15160
15161   // C++ [class.mem]p15:
15162   // If T is the name of a class, then each of the following shall have a name
15163   // different from T:
15164   // - every enumerator of every member of class T that is an unscoped
15165   // enumerated type
15166   if (!TheEnumDecl->isScoped())
15167     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15168                             DeclarationNameInfo(Id, IdLoc));
15169
15170   EnumConstantDecl *New =
15171     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15172   if (!New)
15173     return nullptr;
15174
15175   if (PrevDecl) {
15176     // When in C++, we may get a TagDecl with the same name; in this case the
15177     // enum constant will 'hide' the tag.
15178     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15179            "Received TagDecl when not in C++!");
15180     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15181         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15182       if (isa<EnumConstantDecl>(PrevDecl))
15183         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15184       else
15185         Diag(IdLoc, diag::err_redefinition) << Id;
15186       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15187       return nullptr;
15188     }
15189   }
15190
15191   // Process attributes.
15192   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15193   AddPragmaAttributes(S, New);
15194
15195   // Register this decl in the current scope stack.
15196   New->setAccess(TheEnumDecl->getAccess());
15197   PushOnScopeChains(New, S);
15198
15199   ActOnDocumentableDecl(New);
15200
15201   return New;
15202 }
15203
15204 // Returns true when the enum initial expression does not trigger the
15205 // duplicate enum warning.  A few common cases are exempted as follows:
15206 // Element2 = Element1
15207 // Element2 = Element1 + 1
15208 // Element2 = Element1 - 1
15209 // Where Element2 and Element1 are from the same enum.
15210 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15211   Expr *InitExpr = ECD->getInitExpr();
15212   if (!InitExpr)
15213     return true;
15214   InitExpr = InitExpr->IgnoreImpCasts();
15215
15216   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15217     if (!BO->isAdditiveOp())
15218       return true;
15219     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15220     if (!IL)
15221       return true;
15222     if (IL->getValue() != 1)
15223       return true;
15224
15225     InitExpr = BO->getLHS();
15226   }
15227
15228   // This checks if the elements are from the same enum.
15229   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15230   if (!DRE)
15231     return true;
15232
15233   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15234   if (!EnumConstant)
15235     return true;
15236
15237   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15238       Enum)
15239     return true;
15240
15241   return false;
15242 }
15243
15244 namespace {
15245 struct DupKey {
15246   int64_t val;
15247   bool isTombstoneOrEmptyKey;
15248   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15249     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15250 };
15251
15252 static DupKey GetDupKey(const llvm::APSInt& Val) {
15253   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15254                 false);
15255 }
15256
15257 struct DenseMapInfoDupKey {
15258   static DupKey getEmptyKey() { return DupKey(0, true); }
15259   static DupKey getTombstoneKey() { return DupKey(1, true); }
15260   static unsigned getHashValue(const DupKey Key) {
15261     return (unsigned)(Key.val * 37);
15262   }
15263   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15264     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15265            LHS.val == RHS.val;
15266   }
15267 };
15268 } // end anonymous namespace
15269
15270 // Emits a warning when an element is implicitly set a value that
15271 // a previous element has already been set to.
15272 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15273                                         EnumDecl *Enum,
15274                                         QualType EnumType) {
15275   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15276     return;
15277   // Avoid anonymous enums
15278   if (!Enum->getIdentifier())
15279     return;
15280
15281   // Only check for small enums.
15282   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15283     return;
15284
15285   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15286   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15287
15288   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15289   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15290           ValueToVectorMap;
15291
15292   DuplicatesVector DupVector;
15293   ValueToVectorMap EnumMap;
15294
15295   // Populate the EnumMap with all values represented by enum constants without
15296   // an initialier.
15297   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15298     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15299
15300     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15301     // this constant.  Skip this enum since it may be ill-formed.
15302     if (!ECD) {
15303       return;
15304     }
15305
15306     if (ECD->getInitExpr())
15307       continue;
15308
15309     DupKey Key = GetDupKey(ECD->getInitVal());
15310     DeclOrVector &Entry = EnumMap[Key];
15311
15312     // First time encountering this value.
15313     if (Entry.isNull())
15314       Entry = ECD;
15315   }
15316
15317   // Create vectors for any values that has duplicates.
15318   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15319     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15320     if (!ValidDuplicateEnum(ECD, Enum))
15321       continue;
15322
15323     DupKey Key = GetDupKey(ECD->getInitVal());
15324
15325     DeclOrVector& Entry = EnumMap[Key];
15326     if (Entry.isNull())
15327       continue;
15328
15329     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15330       // Ensure constants are different.
15331       if (D == ECD)
15332         continue;
15333
15334       // Create new vector and push values onto it.
15335       ECDVector *Vec = new ECDVector();
15336       Vec->push_back(D);
15337       Vec->push_back(ECD);
15338
15339       // Update entry to point to the duplicates vector.
15340       Entry = Vec;
15341
15342       // Store the vector somewhere we can consult later for quick emission of
15343       // diagnostics.
15344       DupVector.push_back(Vec);
15345       continue;
15346     }
15347
15348     ECDVector *Vec = Entry.get<ECDVector*>();
15349     // Make sure constants are not added more than once.
15350     if (*Vec->begin() == ECD)
15351       continue;
15352
15353     Vec->push_back(ECD);
15354   }
15355
15356   // Emit diagnostics.
15357   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15358                                   DupVectorEnd = DupVector.end();
15359        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15360     ECDVector *Vec = *DupVectorIter;
15361     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15362
15363     // Emit warning for one enum constant.
15364     ECDVector::iterator I = Vec->begin();
15365     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15366       << (*I)->getName() << (*I)->getInitVal().toString(10)
15367       << (*I)->getSourceRange();
15368     ++I;
15369
15370     // Emit one note for each of the remaining enum constants with
15371     // the same value.
15372     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15373       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15374         << (*I)->getName() << (*I)->getInitVal().toString(10)
15375         << (*I)->getSourceRange();
15376     delete Vec;
15377   }
15378 }
15379
15380 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15381                              bool AllowMask) const {
15382   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
15383   assert(ED->isCompleteDefinition() && "expected enum definition");
15384
15385   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15386   llvm::APInt &FlagBits = R.first->second;
15387
15388   if (R.second) {
15389     for (auto *E : ED->enumerators()) {
15390       const auto &EVal = E->getInitVal();
15391       // Only single-bit enumerators introduce new flag values.
15392       if (EVal.isPowerOf2())
15393         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15394     }
15395   }
15396
15397   // A value is in a flag enum if either its bits are a subset of the enum's
15398   // flag bits (the first condition) or we are allowing masks and the same is
15399   // true of its complement (the second condition). When masks are allowed, we
15400   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15401   //
15402   // While it's true that any value could be used as a mask, the assumption is
15403   // that a mask will have all of the insignificant bits set. Anything else is
15404   // likely a logic error.
15405   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15406   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15407 }
15408
15409 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15410                          Decl *EnumDeclX,
15411                          ArrayRef<Decl *> Elements,
15412                          Scope *S, AttributeList *Attr) {
15413   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15414   QualType EnumType = Context.getTypeDeclType(Enum);
15415
15416   if (Attr)
15417     ProcessDeclAttributeList(S, Enum, Attr);
15418
15419   if (Enum->isDependentType()) {
15420     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15421       EnumConstantDecl *ECD =
15422         cast_or_null<EnumConstantDecl>(Elements[i]);
15423       if (!ECD) continue;
15424
15425       ECD->setType(EnumType);
15426     }
15427
15428     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15429     return;
15430   }
15431
15432   // TODO: If the result value doesn't fit in an int, it must be a long or long
15433   // long value.  ISO C does not support this, but GCC does as an extension,
15434   // emit a warning.
15435   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15436   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15437   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15438
15439   // Verify that all the values are okay, compute the size of the values, and
15440   // reverse the list.
15441   unsigned NumNegativeBits = 0;
15442   unsigned NumPositiveBits = 0;
15443
15444   // Keep track of whether all elements have type int.
15445   bool AllElementsInt = true;
15446
15447   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15448     EnumConstantDecl *ECD =
15449       cast_or_null<EnumConstantDecl>(Elements[i]);
15450     if (!ECD) continue;  // Already issued a diagnostic.
15451
15452     const llvm::APSInt &InitVal = ECD->getInitVal();
15453
15454     // Keep track of the size of positive and negative values.
15455     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15456       NumPositiveBits = std::max(NumPositiveBits,
15457                                  (unsigned)InitVal.getActiveBits());
15458     else
15459       NumNegativeBits = std::max(NumNegativeBits,
15460                                  (unsigned)InitVal.getMinSignedBits());
15461
15462     // Keep track of whether every enum element has type int (very commmon).
15463     if (AllElementsInt)
15464       AllElementsInt = ECD->getType() == Context.IntTy;
15465   }
15466
15467   // Figure out the type that should be used for this enum.
15468   QualType BestType;
15469   unsigned BestWidth;
15470
15471   // C++0x N3000 [conv.prom]p3:
15472   //   An rvalue of an unscoped enumeration type whose underlying
15473   //   type is not fixed can be converted to an rvalue of the first
15474   //   of the following types that can represent all the values of
15475   //   the enumeration: int, unsigned int, long int, unsigned long
15476   //   int, long long int, or unsigned long long int.
15477   // C99 6.4.4.3p2:
15478   //   An identifier declared as an enumeration constant has type int.
15479   // The C99 rule is modified by a gcc extension
15480   QualType BestPromotionType;
15481
15482   bool Packed = Enum->hasAttr<PackedAttr>();
15483   // -fshort-enums is the equivalent to specifying the packed attribute on all
15484   // enum definitions.
15485   if (LangOpts.ShortEnums)
15486     Packed = true;
15487
15488   if (Enum->isFixed()) {
15489     BestType = Enum->getIntegerType();
15490     if (BestType->isPromotableIntegerType())
15491       BestPromotionType = Context.getPromotedIntegerType(BestType);
15492     else
15493       BestPromotionType = BestType;
15494
15495     BestWidth = Context.getIntWidth(BestType);
15496   }
15497   else if (NumNegativeBits) {
15498     // If there is a negative value, figure out the smallest integer type (of
15499     // int/long/longlong) that fits.
15500     // If it's packed, check also if it fits a char or a short.
15501     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15502       BestType = Context.SignedCharTy;
15503       BestWidth = CharWidth;
15504     } else if (Packed && NumNegativeBits <= ShortWidth &&
15505                NumPositiveBits < ShortWidth) {
15506       BestType = Context.ShortTy;
15507       BestWidth = ShortWidth;
15508     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15509       BestType = Context.IntTy;
15510       BestWidth = IntWidth;
15511     } else {
15512       BestWidth = Context.getTargetInfo().getLongWidth();
15513
15514       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15515         BestType = Context.LongTy;
15516       } else {
15517         BestWidth = Context.getTargetInfo().getLongLongWidth();
15518
15519         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15520           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15521         BestType = Context.LongLongTy;
15522       }
15523     }
15524     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15525   } else {
15526     // If there is no negative value, figure out the smallest type that fits
15527     // all of the enumerator values.
15528     // If it's packed, check also if it fits a char or a short.
15529     if (Packed && NumPositiveBits <= CharWidth) {
15530       BestType = Context.UnsignedCharTy;
15531       BestPromotionType = Context.IntTy;
15532       BestWidth = CharWidth;
15533     } else if (Packed && NumPositiveBits <= ShortWidth) {
15534       BestType = Context.UnsignedShortTy;
15535       BestPromotionType = Context.IntTy;
15536       BestWidth = ShortWidth;
15537     } else if (NumPositiveBits <= IntWidth) {
15538       BestType = Context.UnsignedIntTy;
15539       BestWidth = IntWidth;
15540       BestPromotionType
15541         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15542                            ? Context.UnsignedIntTy : Context.IntTy;
15543     } else if (NumPositiveBits <=
15544                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15545       BestType = Context.UnsignedLongTy;
15546       BestPromotionType
15547         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15548                            ? Context.UnsignedLongTy : Context.LongTy;
15549     } else {
15550       BestWidth = Context.getTargetInfo().getLongLongWidth();
15551       assert(NumPositiveBits <= BestWidth &&
15552              "How could an initializer get larger than ULL?");
15553       BestType = Context.UnsignedLongLongTy;
15554       BestPromotionType
15555         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15556                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15557     }
15558   }
15559
15560   // Loop over all of the enumerator constants, changing their types to match
15561   // the type of the enum if needed.
15562   for (auto *D : Elements) {
15563     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15564     if (!ECD) continue;  // Already issued a diagnostic.
15565
15566     // Standard C says the enumerators have int type, but we allow, as an
15567     // extension, the enumerators to be larger than int size.  If each
15568     // enumerator value fits in an int, type it as an int, otherwise type it the
15569     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15570     // that X has type 'int', not 'unsigned'.
15571
15572     // Determine whether the value fits into an int.
15573     llvm::APSInt InitVal = ECD->getInitVal();
15574
15575     // If it fits into an integer type, force it.  Otherwise force it to match
15576     // the enum decl type.
15577     QualType NewTy;
15578     unsigned NewWidth;
15579     bool NewSign;
15580     if (!getLangOpts().CPlusPlus &&
15581         !Enum->isFixed() &&
15582         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15583       NewTy = Context.IntTy;
15584       NewWidth = IntWidth;
15585       NewSign = true;
15586     } else if (ECD->getType() == BestType) {
15587       // Already the right type!
15588       if (getLangOpts().CPlusPlus)
15589         // C++ [dcl.enum]p4: Following the closing brace of an
15590         // enum-specifier, each enumerator has the type of its
15591         // enumeration.
15592         ECD->setType(EnumType);
15593       continue;
15594     } else {
15595       NewTy = BestType;
15596       NewWidth = BestWidth;
15597       NewSign = BestType->isSignedIntegerOrEnumerationType();
15598     }
15599
15600     // Adjust the APSInt value.
15601     InitVal = InitVal.extOrTrunc(NewWidth);
15602     InitVal.setIsSigned(NewSign);
15603     ECD->setInitVal(InitVal);
15604
15605     // Adjust the Expr initializer and type.
15606     if (ECD->getInitExpr() &&
15607         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15608       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15609                                                 CK_IntegralCast,
15610                                                 ECD->getInitExpr(),
15611                                                 /*base paths*/ nullptr,
15612                                                 VK_RValue));
15613     if (getLangOpts().CPlusPlus)
15614       // C++ [dcl.enum]p4: Following the closing brace of an
15615       // enum-specifier, each enumerator has the type of its
15616       // enumeration.
15617       ECD->setType(EnumType);
15618     else
15619       ECD->setType(NewTy);
15620   }
15621
15622   Enum->completeDefinition(BestType, BestPromotionType,
15623                            NumPositiveBits, NumNegativeBits);
15624
15625   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15626
15627   if (Enum->isClosedFlag()) {
15628     for (Decl *D : Elements) {
15629       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15630       if (!ECD) continue;  // Already issued a diagnostic.
15631
15632       llvm::APSInt InitVal = ECD->getInitVal();
15633       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15634           !IsValueInFlagEnum(Enum, InitVal, true))
15635         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15636           << ECD << Enum;
15637     }
15638   }
15639
15640   // Now that the enum type is defined, ensure it's not been underaligned.
15641   if (Enum->hasAttrs())
15642     CheckAlignasUnderalignment(Enum);
15643 }
15644
15645 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15646                                   SourceLocation StartLoc,
15647                                   SourceLocation EndLoc) {
15648   StringLiteral *AsmString = cast<StringLiteral>(expr);
15649
15650   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15651                                                    AsmString, StartLoc,
15652                                                    EndLoc);
15653   CurContext->addDecl(New);
15654   return New;
15655 }
15656
15657 static void checkModuleImportContext(Sema &S, Module *M,
15658                                      SourceLocation ImportLoc, DeclContext *DC,
15659                                      bool FromInclude = false) {
15660   SourceLocation ExternCLoc;
15661
15662   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15663     switch (LSD->getLanguage()) {
15664     case LinkageSpecDecl::lang_c:
15665       if (ExternCLoc.isInvalid())
15666         ExternCLoc = LSD->getLocStart();
15667       break;
15668     case LinkageSpecDecl::lang_cxx:
15669       break;
15670     }
15671     DC = LSD->getParent();
15672   }
15673
15674   while (isa<LinkageSpecDecl>(DC))
15675     DC = DC->getParent();
15676
15677   if (!isa<TranslationUnitDecl>(DC)) {
15678     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15679                           ? diag::ext_module_import_not_at_top_level_noop
15680                           : diag::err_module_import_not_at_top_level_fatal)
15681         << M->getFullModuleName() << DC;
15682     S.Diag(cast<Decl>(DC)->getLocStart(),
15683            diag::note_module_import_not_at_top_level) << DC;
15684   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15685     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15686       << M->getFullModuleName();
15687     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
15688   }
15689 }
15690
15691 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
15692                                            SourceLocation ModuleLoc,
15693                                            ModuleDeclKind MDK,
15694                                            ModuleIdPath Path) {
15695   // A module implementation unit requires that we are not compiling a module
15696   // of any kind. A module interface unit requires that we are not compiling a
15697   // module map.
15698   switch (getLangOpts().getCompilingModule()) {
15699   case LangOptions::CMK_None:
15700     // It's OK to compile a module interface as a normal translation unit.
15701     break;
15702
15703   case LangOptions::CMK_ModuleInterface:
15704     if (MDK != ModuleDeclKind::Implementation)
15705       break;
15706
15707     // We were asked to compile a module interface unit but this is a module
15708     // implementation unit. That indicates the 'export' is missing.
15709     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
15710       << FixItHint::CreateInsertion(ModuleLoc, "export ");
15711     break;
15712
15713   case LangOptions::CMK_ModuleMap:
15714     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
15715     return nullptr;
15716   }
15717
15718   // FIXME: Create a ModuleDecl and return it.
15719
15720   // FIXME: Most of this work should be done by the preprocessor rather than
15721   // here, in order to support macro import.
15722
15723   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
15724   // modules, the dots here are just another character that can appear in a
15725   // module name.
15726   std::string ModuleName;
15727   for (auto &Piece : Path) {
15728     if (!ModuleName.empty())
15729       ModuleName += ".";
15730     ModuleName += Piece.first->getName();
15731   }
15732
15733   // If a module name was explicitly specified on the command line, it must be
15734   // correct.
15735   if (!getLangOpts().CurrentModule.empty() &&
15736       getLangOpts().CurrentModule != ModuleName) {
15737     Diag(Path.front().second, diag::err_current_module_name_mismatch)
15738         << SourceRange(Path.front().second, Path.back().second)
15739         << getLangOpts().CurrentModule;
15740     return nullptr;
15741   }
15742   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
15743
15744   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
15745
15746   switch (MDK) {
15747   case ModuleDeclKind::Module: {
15748     // FIXME: Check we're not in a submodule.
15749
15750     // We can't have parsed or imported a definition of this module or parsed a
15751     // module map defining it already.
15752     if (auto *M = Map.findModule(ModuleName)) {
15753       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
15754       if (M->DefinitionLoc.isValid())
15755         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
15756       else if (const auto *FE = M->getASTFile())
15757         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
15758             << FE->getName();
15759       return nullptr;
15760     }
15761
15762     // Create a Module for the module that we're defining.
15763     Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
15764     assert(Mod && "module creation should not fail");
15765
15766     // Enter the semantic scope of the module.
15767     ActOnModuleBegin(ModuleLoc, Mod);
15768     return nullptr;
15769   }
15770
15771   case ModuleDeclKind::Partition:
15772     // FIXME: Check we are in a submodule of the named module.
15773     return nullptr;
15774
15775   case ModuleDeclKind::Implementation:
15776     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
15777         PP.getIdentifierInfo(ModuleName), Path[0].second);
15778
15779     DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
15780     if (Import.isInvalid())
15781       return nullptr;
15782     return ConvertDeclToDeclGroup(Import.get());
15783   }
15784
15785   llvm_unreachable("unexpected module decl kind");
15786 }
15787
15788 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
15789                                    SourceLocation ImportLoc,
15790                                    ModuleIdPath Path) {
15791   Module *Mod =
15792       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15793                                    /*IsIncludeDirective=*/false);
15794   if (!Mod)
15795     return true;
15796
15797   VisibleModules.setVisible(Mod, ImportLoc);
15798
15799   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15800
15801   // FIXME: we should support importing a submodule within a different submodule
15802   // of the same top-level module. Until we do, make it an error rather than
15803   // silently ignoring the import.
15804   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
15805   // warn on a redundant import of the current module?
15806   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
15807       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
15808     Diag(ImportLoc, getLangOpts().isCompilingModule()
15809                         ? diag::err_module_self_import
15810                         : diag::err_module_import_in_implementation)
15811         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15812
15813   SmallVector<SourceLocation, 2> IdentifierLocs;
15814   Module *ModCheck = Mod;
15815   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15816     // If we've run out of module parents, just drop the remaining identifiers.
15817     // We need the length to be consistent.
15818     if (!ModCheck)
15819       break;
15820     ModCheck = ModCheck->Parent;
15821
15822     IdentifierLocs.push_back(Path[I].second);
15823   }
15824
15825   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15826   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
15827                                           Mod, IdentifierLocs);
15828   if (!ModuleScopes.empty())
15829     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
15830   TU->addDecl(Import);
15831   return Import;
15832 }
15833
15834 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15835   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15836   BuildModuleInclude(DirectiveLoc, Mod);
15837 }
15838
15839 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15840   // Determine whether we're in the #include buffer for a module. The #includes
15841   // in that buffer do not qualify as module imports; they're just an
15842   // implementation detail of us building the module.
15843   //
15844   // FIXME: Should we even get ActOnModuleInclude calls for those?
15845   bool IsInModuleIncludes =
15846       TUKind == TU_Module &&
15847       getSourceManager().isWrittenInMainFile(DirectiveLoc);
15848
15849   bool ShouldAddImport = !IsInModuleIncludes;
15850
15851   // If this module import was due to an inclusion directive, create an
15852   // implicit import declaration to capture it in the AST.
15853   if (ShouldAddImport) {
15854     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15855     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15856                                                      DirectiveLoc, Mod,
15857                                                      DirectiveLoc);
15858     if (!ModuleScopes.empty())
15859       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
15860     TU->addDecl(ImportD);
15861     Consumer.HandleImplicitImportDecl(ImportD);
15862   }
15863
15864   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15865   VisibleModules.setVisible(Mod, DirectiveLoc);
15866 }
15867
15868 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15869   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15870
15871   ModuleScopes.push_back({});
15872   ModuleScopes.back().Module = Mod;
15873   if (getLangOpts().ModulesLocalVisibility)
15874     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
15875
15876   VisibleModules.setVisible(Mod, DirectiveLoc);
15877 }
15878
15879 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) {
15880   if (getLangOpts().ModulesLocalVisibility) {
15881     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
15882     // Leaving a module hides namespace names, so our visible namespace cache
15883     // is now out of date.
15884     VisibleNamespaceCache.clear();
15885   }
15886
15887   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
15888          "left the wrong module scope");
15889   ModuleScopes.pop_back();
15890
15891   // We got to the end of processing a #include of a local module. Create an
15892   // ImportDecl as we would for an imported module.
15893   FileID File = getSourceManager().getFileID(EofLoc);
15894   assert(File != getSourceManager().getMainFileID() &&
15895          "end of submodule in main source file");
15896   SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File);
15897   BuildModuleInclude(DirectiveLoc, Mod);
15898 }
15899
15900 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15901                                                       Module *Mod) {
15902   // Bail if we're not allowed to implicitly import a module here.
15903   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15904     return;
15905
15906   // Create the implicit import declaration.
15907   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15908   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15909                                                    Loc, Mod, Loc);
15910   TU->addDecl(ImportD);
15911   Consumer.HandleImplicitImportDecl(ImportD);
15912
15913   // Make the module visible.
15914   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15915   VisibleModules.setVisible(Mod, Loc);
15916 }
15917
15918 /// We have parsed the start of an export declaration, including the '{'
15919 /// (if present).
15920 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
15921                                  SourceLocation LBraceLoc) {
15922   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
15923
15924   // C++ Modules TS draft:
15925   //   An export-declaration shall appear in the purview of a module other than
15926   //   the global module.
15927   if (ModuleScopes.empty() || !ModuleScopes.back().Module ||
15928       ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit)
15929     Diag(ExportLoc, diag::err_export_not_in_module_interface);
15930
15931   //   An export-declaration [...] shall not contain more than one
15932   //   export keyword.
15933   //
15934   // The intent here is that an export-declaration cannot appear within another
15935   // export-declaration.
15936   if (D->isExported())
15937     Diag(ExportLoc, diag::err_export_within_export);
15938
15939   CurContext->addDecl(D);
15940   PushDeclContext(S, D);
15941   return D;
15942 }
15943
15944 /// Complete the definition of an export declaration.
15945 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
15946   auto *ED = cast<ExportDecl>(D);
15947   if (RBraceLoc.isValid())
15948     ED->setRBraceLoc(RBraceLoc);
15949
15950   // FIXME: Diagnose export of internal-linkage declaration (including
15951   // anonymous namespace).
15952
15953   PopDeclContext();
15954   return D;
15955 }
15956
15957 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15958                                       IdentifierInfo* AliasName,
15959                                       SourceLocation PragmaLoc,
15960                                       SourceLocation NameLoc,
15961                                       SourceLocation AliasNameLoc) {
15962   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15963                                          LookupOrdinaryName);
15964   AsmLabelAttr *Attr =
15965       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15966
15967   // If a declaration that:
15968   // 1) declares a function or a variable
15969   // 2) has external linkage
15970   // already exists, add a label attribute to it.
15971   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15972     if (isDeclExternC(PrevDecl))
15973       PrevDecl->addAttr(Attr);
15974     else
15975       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15976           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15977   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15978   } else
15979     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15980 }
15981
15982 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15983                              SourceLocation PragmaLoc,
15984                              SourceLocation NameLoc) {
15985   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15986
15987   if (PrevDecl) {
15988     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15989   } else {
15990     (void)WeakUndeclaredIdentifiers.insert(
15991       std::pair<IdentifierInfo*,WeakInfo>
15992         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15993   }
15994 }
15995
15996 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15997                                 IdentifierInfo* AliasName,
15998                                 SourceLocation PragmaLoc,
15999                                 SourceLocation NameLoc,
16000                                 SourceLocation AliasNameLoc) {
16001   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16002                                     LookupOrdinaryName);
16003   WeakInfo W = WeakInfo(Name, NameLoc);
16004
16005   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16006     if (!PrevDecl->hasAttr<AliasAttr>())
16007       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16008         DeclApplyPragmaWeak(TUScope, ND, W);
16009   } else {
16010     (void)WeakUndeclaredIdentifiers.insert(
16011       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16012   }
16013 }
16014
16015 Decl *Sema::getObjCDeclContext() const {
16016   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
16017 }