1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Parse/ParseDiagnostic.h"
37 #include "clang/Sema/CXXFieldCollector.h"
38 #include "clang/Sema/DeclSpec.h"
39 #include "clang/Sema/DelayedDiagnostic.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68                        bool AllowTemplates=false)
69       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70         AllowClassTemplates(AllowTemplates) {
71     WantExpressionKeywords = false;
72     WantCXXNamedCasts = false;
73     WantRemainingKeywords = false;
74   }
75 
76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80       return (IsType || AllowedTemplate) &&
81              (AllowInvalidDecl || !ND->isInvalidDecl());
82     }
83     return !WantClassName && candidate.isKeyword();
84   }
85 
86  private:
87   bool AllowInvalidDecl;
88   bool WantClassName;
89   bool AllowClassTemplates;
90 };
91 
92 }
93 
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96   switch (Kind) {
97   // FIXME: Take into account the current language when deciding whether a
98   // token kind is a valid type specifier
99   case tok::kw_short:
100   case tok::kw_long:
101   case tok::kw___int64:
102   case tok::kw___int128:
103   case tok::kw_signed:
104   case tok::kw_unsigned:
105   case tok::kw_void:
106   case tok::kw_char:
107   case tok::kw_int:
108   case tok::kw_half:
109   case tok::kw_float:
110   case tok::kw_double:
111   case tok::kw_wchar_t:
112   case tok::kw_bool:
113   case tok::kw___underlying_type:
114     return true;
115 
116   case tok::annot_typename:
117   case tok::kw_char16_t:
118   case tok::kw_char32_t:
119   case tok::kw_typeof:
120   case tok::annot_decltype:
121   case tok::kw_decltype:
122     return getLangOpts().CPlusPlus;
123 
124   default:
125     break;
126   }
127 
128   return false;
129 }
130 
131 namespace {
132 enum class UnqualifiedTypeNameLookupResult {
133   NotFound,
134   FoundNonType,
135   FoundType
136 };
137 } // namespace
138 
139 /// \brief Tries to perform unqualified lookup of the type decls in bases for
140 /// dependent class.
141 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
142 /// type decl, \a FoundType if only type decls are found.
143 static UnqualifiedTypeNameLookupResult
144 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
145                                 SourceLocation NameLoc,
146                                 const CXXRecordDecl *RD) {
147   if (!RD->hasDefinition())
148     return UnqualifiedTypeNameLookupResult::NotFound;
149   // Look for type decls in base classes.
150   UnqualifiedTypeNameLookupResult FoundTypeDecl =
151       UnqualifiedTypeNameLookupResult::NotFound;
152   for (const auto &Base : RD->bases()) {
153     const CXXRecordDecl *BaseRD = nullptr;
154     if (auto *BaseTT = Base.getType()->getAs<TagType>())
155       BaseRD = BaseTT->getAsCXXRecordDecl();
156     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
157       // Look for type decls in dependent base classes that have known primary
158       // templates.
159       if (!TST || !TST->isDependentType())
160         continue;
161       auto *TD = TST->getTemplateName().getAsTemplateDecl();
162       if (!TD)
163         continue;
164       auto *BasePrimaryTemplate =
165           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
166       if (!BasePrimaryTemplate)
167         continue;
168       BaseRD = BasePrimaryTemplate;
169     }
170     if (BaseRD) {
171       for (NamedDecl *ND : BaseRD->lookup(&II)) {
172         if (!isa<TypeDecl>(ND))
173           return UnqualifiedTypeNameLookupResult::FoundNonType;
174         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
175       }
176       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
177         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
178         case UnqualifiedTypeNameLookupResult::FoundNonType:
179           return UnqualifiedTypeNameLookupResult::FoundNonType;
180         case UnqualifiedTypeNameLookupResult::FoundType:
181           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
182           break;
183         case UnqualifiedTypeNameLookupResult::NotFound:
184           break;
185         }
186       }
187     }
188   }
189 
190   return FoundTypeDecl;
191 }
192 
193 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
194                                                       const IdentifierInfo &II,
195                                                       SourceLocation NameLoc) {
196   // Lookup in the parent class template context, if any.
197   const CXXRecordDecl *RD = nullptr;
198   UnqualifiedTypeNameLookupResult FoundTypeDecl =
199       UnqualifiedTypeNameLookupResult::NotFound;
200   for (DeclContext *DC = S.CurContext;
201        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
202        DC = DC->getParent()) {
203     // Look for type decls in dependent base classes that have known primary
204     // templates.
205     RD = dyn_cast<CXXRecordDecl>(DC);
206     if (RD && RD->getDescribedClassTemplate())
207       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
208   }
209   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
210     return ParsedType();
211 
212   // We found some types in dependent base classes.  Recover as if the user
213   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
214   // lookup during template instantiation.
215   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
216 
217   ASTContext &Context = S.Context;
218   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
219                                           cast<Type>(Context.getRecordType(RD)));
220   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
221 
222   CXXScopeSpec SS;
223   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
224 
225   TypeLocBuilder Builder;
226   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
227   DepTL.setNameLoc(NameLoc);
228   DepTL.setElaboratedKeywordLoc(SourceLocation());
229   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
230   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
231 }
232 
233 /// \brief If the identifier refers to a type name within this scope,
234 /// return the declaration of that type.
235 ///
236 /// This routine performs ordinary name lookup of the identifier II
237 /// within the given scope, with optional C++ scope specifier SS, to
238 /// determine whether the name refers to a type. If so, returns an
239 /// opaque pointer (actually a QualType) corresponding to that
240 /// type. Otherwise, returns NULL.
241 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
242                              Scope *S, CXXScopeSpec *SS,
243                              bool isClassName, bool HasTrailingDot,
244                              ParsedType ObjectTypePtr,
245                              bool IsCtorOrDtorName,
246                              bool WantNontrivialTypeSourceInfo,
247                              IdentifierInfo **CorrectedII) {
248   // Determine where we will perform name lookup.
249   DeclContext *LookupCtx = nullptr;
250   if (ObjectTypePtr) {
251     QualType ObjectType = ObjectTypePtr.get();
252     if (ObjectType->isRecordType())
253       LookupCtx = computeDeclContext(ObjectType);
254   } else if (SS && SS->isNotEmpty()) {
255     LookupCtx = computeDeclContext(*SS, false);
256 
257     if (!LookupCtx) {
258       if (isDependentScopeSpecifier(*SS)) {
259         // C++ [temp.res]p3:
260         //   A qualified-id that refers to a type and in which the
261         //   nested-name-specifier depends on a template-parameter (14.6.2)
262         //   shall be prefixed by the keyword typename to indicate that the
263         //   qualified-id denotes a type, forming an
264         //   elaborated-type-specifier (7.1.5.3).
265         //
266         // We therefore do not perform any name lookup if the result would
267         // refer to a member of an unknown specialization.
268         if (!isClassName && !IsCtorOrDtorName)
269           return ParsedType();
270 
271         // We know from the grammar that this name refers to a type,
272         // so build a dependent node to describe the type.
273         if (WantNontrivialTypeSourceInfo)
274           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
275 
276         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
277         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
278                                        II, NameLoc);
279         return ParsedType::make(T);
280       }
281 
282       return ParsedType();
283     }
284 
285     if (!LookupCtx->isDependentContext() &&
286         RequireCompleteDeclContext(*SS, LookupCtx))
287       return ParsedType();
288   }
289 
290   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
291   // lookup for class-names.
292   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
293                                       LookupOrdinaryName;
294   LookupResult Result(*this, &II, NameLoc, Kind);
295   if (LookupCtx) {
296     // Perform "qualified" name lookup into the declaration context we
297     // computed, which is either the type of the base of a member access
298     // expression or the declaration context associated with a prior
299     // nested-name-specifier.
300     LookupQualifiedName(Result, LookupCtx);
301 
302     if (ObjectTypePtr && Result.empty()) {
303       // C++ [basic.lookup.classref]p3:
304       //   If the unqualified-id is ~type-name, the type-name is looked up
305       //   in the context of the entire postfix-expression. If the type T of
306       //   the object expression is of a class type C, the type-name is also
307       //   looked up in the scope of class C. At least one of the lookups shall
308       //   find a name that refers to (possibly cv-qualified) T.
309       LookupName(Result, S);
310     }
311   } else {
312     // Perform unqualified name lookup.
313     LookupName(Result, S);
314 
315     // For unqualified lookup in a class template in MSVC mode, look into
316     // dependent base classes where the primary class template is known.
317     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
318       if (ParsedType TypeInBase =
319               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
320         return TypeInBase;
321     }
322   }
323 
324   NamedDecl *IIDecl = nullptr;
325   switch (Result.getResultKind()) {
326   case LookupResult::NotFound:
327   case LookupResult::NotFoundInCurrentInstantiation:
328     if (CorrectedII) {
329       TypoCorrection Correction = CorrectTypo(
330           Result.getLookupNameInfo(), Kind, S, SS,
331           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
332           CTK_ErrorRecovery);
333       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
334       TemplateTy Template;
335       bool MemberOfUnknownSpecialization;
336       UnqualifiedId TemplateName;
337       TemplateName.setIdentifier(NewII, NameLoc);
338       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
339       CXXScopeSpec NewSS, *NewSSPtr = SS;
340       if (SS && NNS) {
341         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
342         NewSSPtr = &NewSS;
343       }
344       if (Correction && (NNS || NewII != &II) &&
345           // Ignore a correction to a template type as the to-be-corrected
346           // identifier is not a template (typo correction for template names
347           // is handled elsewhere).
348           !(getLangOpts().CPlusPlus && NewSSPtr &&
349             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
350                            false, Template, MemberOfUnknownSpecialization))) {
351         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
352                                     isClassName, HasTrailingDot, ObjectTypePtr,
353                                     IsCtorOrDtorName,
354                                     WantNontrivialTypeSourceInfo);
355         if (Ty) {
356           diagnoseTypo(Correction,
357                        PDiag(diag::err_unknown_type_or_class_name_suggest)
358                          << Result.getLookupName() << isClassName);
359           if (SS && NNS)
360             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
361           *CorrectedII = NewII;
362           return Ty;
363         }
364       }
365     }
366     // If typo correction failed or was not performed, fall through
367   case LookupResult::FoundOverloaded:
368   case LookupResult::FoundUnresolvedValue:
369     Result.suppressDiagnostics();
370     return ParsedType();
371 
372   case LookupResult::Ambiguous:
373     // Recover from type-hiding ambiguities by hiding the type.  We'll
374     // do the lookup again when looking for an object, and we can
375     // diagnose the error then.  If we don't do this, then the error
376     // about hiding the type will be immediately followed by an error
377     // that only makes sense if the identifier was treated like a type.
378     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
379       Result.suppressDiagnostics();
380       return ParsedType();
381     }
382 
383     // Look to see if we have a type anywhere in the list of results.
384     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
385          Res != ResEnd; ++Res) {
386       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
387         if (!IIDecl ||
388             (*Res)->getLocation().getRawEncoding() <
389               IIDecl->getLocation().getRawEncoding())
390           IIDecl = *Res;
391       }
392     }
393 
394     if (!IIDecl) {
395       // None of the entities we found is a type, so there is no way
396       // to even assume that the result is a type. In this case, don't
397       // complain about the ambiguity. The parser will either try to
398       // perform this lookup again (e.g., as an object name), which
399       // will produce the ambiguity, or will complain that it expected
400       // a type name.
401       Result.suppressDiagnostics();
402       return ParsedType();
403     }
404 
405     // We found a type within the ambiguous lookup; diagnose the
406     // ambiguity and then return that type. This might be the right
407     // answer, or it might not be, but it suppresses any attempt to
408     // perform the name lookup again.
409     break;
410 
411   case LookupResult::Found:
412     IIDecl = Result.getFoundDecl();
413     break;
414   }
415 
416   assert(IIDecl && "Didn't find decl");
417 
418   QualType T;
419   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
420     DiagnoseUseOfDecl(IIDecl, NameLoc);
421 
422     T = Context.getTypeDeclType(TD);
423     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
424 
425     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
426     // constructor or destructor name (in such a case, the scope specifier
427     // will be attached to the enclosing Expr or Decl node).
428     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
429       if (WantNontrivialTypeSourceInfo) {
430         // Construct a type with type-source information.
431         TypeLocBuilder Builder;
432         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
433 
434         T = getElaboratedType(ETK_None, *SS, T);
435         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
436         ElabTL.setElaboratedKeywordLoc(SourceLocation());
437         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
438         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
439       } else {
440         T = getElaboratedType(ETK_None, *SS, T);
441       }
442     }
443   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
444     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
445     if (!HasTrailingDot)
446       T = Context.getObjCInterfaceType(IDecl);
447   }
448 
449   if (T.isNull()) {
450     // If it's not plausibly a type, suppress diagnostics.
451     Result.suppressDiagnostics();
452     return ParsedType();
453   }
454   return ParsedType::make(T);
455 }
456 
457 // Builds a fake NNS for the given decl context.
458 static NestedNameSpecifier *
459 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
460   for (;; DC = DC->getLookupParent()) {
461     DC = DC->getPrimaryContext();
462     auto *ND = dyn_cast<NamespaceDecl>(DC);
463     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
464       return NestedNameSpecifier::Create(Context, nullptr, ND);
465     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
466       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
467                                          RD->getTypeForDecl());
468     else if (isa<TranslationUnitDecl>(DC))
469       return NestedNameSpecifier::GlobalSpecifier(Context);
470   }
471   llvm_unreachable("something isn't in TU scope?");
472 }
473 
474 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
475                                                 SourceLocation NameLoc) {
476   // Accepting an undeclared identifier as a default argument for a template
477   // type parameter is a Microsoft extension.
478   Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
479 
480   // Build a fake DependentNameType that will perform lookup into CurContext at
481   // instantiation time.  The name specifier isn't dependent, so template
482   // instantiation won't transform it.  It will retry the lookup, however.
483   NestedNameSpecifier *NNS =
484       synthesizeCurrentNestedNameSpecifier(Context, CurContext);
485   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
486 
487   // Build type location information.  We synthesized the qualifier, so we have
488   // to build a fake NestedNameSpecifierLoc.
489   NestedNameSpecifierLocBuilder NNSLocBuilder;
490   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
491   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
492 
493   TypeLocBuilder Builder;
494   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
495   DepTL.setNameLoc(NameLoc);
496   DepTL.setElaboratedKeywordLoc(SourceLocation());
497   DepTL.setQualifierLoc(QualifierLoc);
498   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
499 }
500 
501 /// isTagName() - This method is called *for error recovery purposes only*
502 /// to determine if the specified name is a valid tag name ("struct foo").  If
503 /// so, this returns the TST for the tag corresponding to it (TST_enum,
504 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
505 /// cases in C where the user forgot to specify the tag.
506 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
507   // Do a tag name lookup in this scope.
508   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
509   LookupName(R, S, false);
510   R.suppressDiagnostics();
511   if (R.getResultKind() == LookupResult::Found)
512     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
513       switch (TD->getTagKind()) {
514       case TTK_Struct: return DeclSpec::TST_struct;
515       case TTK_Interface: return DeclSpec::TST_interface;
516       case TTK_Union:  return DeclSpec::TST_union;
517       case TTK_Class:  return DeclSpec::TST_class;
518       case TTK_Enum:   return DeclSpec::TST_enum;
519       }
520     }
521 
522   return DeclSpec::TST_unspecified;
523 }
524 
525 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
526 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
527 /// then downgrade the missing typename error to a warning.
528 /// This is needed for MSVC compatibility; Example:
529 /// @code
530 /// template<class T> class A {
531 /// public:
532 ///   typedef int TYPE;
533 /// };
534 /// template<class T> class B : public A<T> {
535 /// public:
536 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
537 /// };
538 /// @endcode
539 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
540   if (CurContext->isRecord()) {
541     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
542       return true;
543 
544     const Type *Ty = SS->getScopeRep()->getAsType();
545 
546     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
547     for (const auto &Base : RD->bases())
548       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
549         return true;
550     return S->isFunctionPrototypeScope();
551   }
552   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
553 }
554 
555 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
556                                    SourceLocation IILoc,
557                                    Scope *S,
558                                    CXXScopeSpec *SS,
559                                    ParsedType &SuggestedType,
560                                    bool AllowClassTemplates) {
561   // We don't have anything to suggest (yet).
562   SuggestedType = ParsedType();
563 
564   // There may have been a typo in the name of the type. Look up typo
565   // results, in case we have something that we can suggest.
566   if (TypoCorrection Corrected =
567           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
568                       llvm::make_unique<TypeNameValidatorCCC>(
569                           false, false, AllowClassTemplates),
570                       CTK_ErrorRecovery)) {
571     if (Corrected.isKeyword()) {
572       // We corrected to a keyword.
573       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
574       II = Corrected.getCorrectionAsIdentifierInfo();
575     } else {
576       // We found a similarly-named type or interface; suggest that.
577       if (!SS || !SS->isSet()) {
578         diagnoseTypo(Corrected,
579                      PDiag(diag::err_unknown_typename_suggest) << II);
580       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
581         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
582         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
583                                 II->getName().equals(CorrectedStr);
584         diagnoseTypo(Corrected,
585                      PDiag(diag::err_unknown_nested_typename_suggest)
586                        << II << DC << DroppedSpecifier << SS->getRange());
587       } else {
588         llvm_unreachable("could not have corrected a typo here");
589       }
590 
591       CXXScopeSpec tmpSS;
592       if (Corrected.getCorrectionSpecifier())
593         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
594                           SourceRange(IILoc));
595       SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
596                                   IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
597                                   false, ParsedType(),
598                                   /*IsCtorOrDtorName=*/false,
599                                   /*NonTrivialTypeSourceInfo=*/true);
600     }
601     return;
602   }
603 
604   if (getLangOpts().CPlusPlus) {
605     // See if II is a class template that the user forgot to pass arguments to.
606     UnqualifiedId Name;
607     Name.setIdentifier(II, IILoc);
608     CXXScopeSpec EmptySS;
609     TemplateTy TemplateResult;
610     bool MemberOfUnknownSpecialization;
611     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
612                        Name, ParsedType(), true, TemplateResult,
613                        MemberOfUnknownSpecialization) == TNK_Type_template) {
614       TemplateName TplName = TemplateResult.get();
615       Diag(IILoc, diag::err_template_missing_args) << TplName;
616       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
617         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
618           << TplDecl->getTemplateParameters()->getSourceRange();
619       }
620       return;
621     }
622   }
623 
624   // FIXME: Should we move the logic that tries to recover from a missing tag
625   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
626 
627   if (!SS || (!SS->isSet() && !SS->isInvalid()))
628     Diag(IILoc, diag::err_unknown_typename) << II;
629   else if (DeclContext *DC = computeDeclContext(*SS, false))
630     Diag(IILoc, diag::err_typename_nested_not_found)
631       << II << DC << SS->getRange();
632   else if (isDependentScopeSpecifier(*SS)) {
633     unsigned DiagID = diag::err_typename_missing;
634     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
635       DiagID = diag::ext_typename_missing;
636 
637     Diag(SS->getRange().getBegin(), DiagID)
638       << SS->getScopeRep() << II->getName()
639       << SourceRange(SS->getRange().getBegin(), IILoc)
640       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
641     SuggestedType = ActOnTypenameType(S, SourceLocation(),
642                                       *SS, *II, IILoc).get();
643   } else {
644     assert(SS && SS->isInvalid() &&
645            "Invalid scope specifier has already been diagnosed");
646   }
647 }
648 
649 /// \brief Determine whether the given result set contains either a type name
650 /// or
651 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
652   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
653                        NextToken.is(tok::less);
654 
655   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
656     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
657       return true;
658 
659     if (CheckTemplate && isa<TemplateDecl>(*I))
660       return true;
661   }
662 
663   return false;
664 }
665 
666 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
667                                     Scope *S, CXXScopeSpec &SS,
668                                     IdentifierInfo *&Name,
669                                     SourceLocation NameLoc) {
670   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
671   SemaRef.LookupParsedName(R, S, &SS);
672   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
673     StringRef FixItTagName;
674     switch (Tag->getTagKind()) {
675       case TTK_Class:
676         FixItTagName = "class ";
677         break;
678 
679       case TTK_Enum:
680         FixItTagName = "enum ";
681         break;
682 
683       case TTK_Struct:
684         FixItTagName = "struct ";
685         break;
686 
687       case TTK_Interface:
688         FixItTagName = "__interface ";
689         break;
690 
691       case TTK_Union:
692         FixItTagName = "union ";
693         break;
694     }
695 
696     StringRef TagName = FixItTagName.drop_back();
697     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
698       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
699       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
700 
701     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
702          I != IEnd; ++I)
703       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
704         << Name << TagName;
705 
706     // Replace lookup results with just the tag decl.
707     Result.clear(Sema::LookupTagName);
708     SemaRef.LookupParsedName(Result, S, &SS);
709     return true;
710   }
711 
712   return false;
713 }
714 
715 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
716 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
717                                   QualType T, SourceLocation NameLoc) {
718   ASTContext &Context = S.Context;
719 
720   TypeLocBuilder Builder;
721   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
722 
723   T = S.getElaboratedType(ETK_None, SS, T);
724   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
725   ElabTL.setElaboratedKeywordLoc(SourceLocation());
726   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
727   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
728 }
729 
730 Sema::NameClassification
731 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
732                    SourceLocation NameLoc, const Token &NextToken,
733                    bool IsAddressOfOperand,
734                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
735   DeclarationNameInfo NameInfo(Name, NameLoc);
736   ObjCMethodDecl *CurMethod = getCurMethodDecl();
737 
738   if (NextToken.is(tok::coloncolon)) {
739     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
740                                 QualType(), false, SS, nullptr, false);
741   }
742 
743   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
744   LookupParsedName(Result, S, &SS, !CurMethod);
745 
746   // For unqualified lookup in a class template in MSVC mode, look into
747   // dependent base classes where the primary class template is known.
748   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
749     if (ParsedType TypeInBase =
750             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
751       return TypeInBase;
752   }
753 
754   // Perform lookup for Objective-C instance variables (including automatically
755   // synthesized instance variables), if we're in an Objective-C method.
756   // FIXME: This lookup really, really needs to be folded in to the normal
757   // unqualified lookup mechanism.
758   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
759     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
760     if (E.get() || E.isInvalid())
761       return E;
762   }
763 
764   bool SecondTry = false;
765   bool IsFilteredTemplateName = false;
766 
767 Corrected:
768   switch (Result.getResultKind()) {
769   case LookupResult::NotFound:
770     // If an unqualified-id is followed by a '(', then we have a function
771     // call.
772     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
773       // In C++, this is an ADL-only call.
774       // FIXME: Reference?
775       if (getLangOpts().CPlusPlus)
776         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
777 
778       // C90 6.3.2.2:
779       //   If the expression that precedes the parenthesized argument list in a
780       //   function call consists solely of an identifier, and if no
781       //   declaration is visible for this identifier, the identifier is
782       //   implicitly declared exactly as if, in the innermost block containing
783       //   the function call, the declaration
784       //
785       //     extern int identifier ();
786       //
787       //   appeared.
788       //
789       // We also allow this in C99 as an extension.
790       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
791         Result.addDecl(D);
792         Result.resolveKind();
793         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
794       }
795     }
796 
797     // In C, we first see whether there is a tag type by the same name, in
798     // which case it's likely that the user just forget to write "enum",
799     // "struct", or "union".
800     if (!getLangOpts().CPlusPlus && !SecondTry &&
801         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
802       break;
803     }
804 
805     // Perform typo correction to determine if there is another name that is
806     // close to this name.
807     if (!SecondTry && CCC) {
808       SecondTry = true;
809       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
810                                                  Result.getLookupKind(), S,
811                                                  &SS, std::move(CCC),
812                                                  CTK_ErrorRecovery)) {
813         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
814         unsigned QualifiedDiag = diag::err_no_member_suggest;
815 
816         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
817         NamedDecl *UnderlyingFirstDecl
818           = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
819         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
820             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
821           UnqualifiedDiag = diag::err_no_template_suggest;
822           QualifiedDiag = diag::err_no_member_template_suggest;
823         } else if (UnderlyingFirstDecl &&
824                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
825                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
826                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
827           UnqualifiedDiag = diag::err_unknown_typename_suggest;
828           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
829         }
830 
831         if (SS.isEmpty()) {
832           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
833         } else {// FIXME: is this even reachable? Test it.
834           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
835           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
836                                   Name->getName().equals(CorrectedStr);
837           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
838                                     << Name << computeDeclContext(SS, false)
839                                     << DroppedSpecifier << SS.getRange());
840         }
841 
842         // Update the name, so that the caller has the new name.
843         Name = Corrected.getCorrectionAsIdentifierInfo();
844 
845         // Typo correction corrected to a keyword.
846         if (Corrected.isKeyword())
847           return Name;
848 
849         // Also update the LookupResult...
850         // FIXME: This should probably go away at some point
851         Result.clear();
852         Result.setLookupName(Corrected.getCorrection());
853         if (FirstDecl)
854           Result.addDecl(FirstDecl);
855 
856         // If we found an Objective-C instance variable, let
857         // LookupInObjCMethod build the appropriate expression to
858         // reference the ivar.
859         // FIXME: This is a gross hack.
860         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
861           Result.clear();
862           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
863           return E;
864         }
865 
866         goto Corrected;
867       }
868     }
869 
870     // We failed to correct; just fall through and let the parser deal with it.
871     Result.suppressDiagnostics();
872     return NameClassification::Unknown();
873 
874   case LookupResult::NotFoundInCurrentInstantiation: {
875     // We performed name lookup into the current instantiation, and there were
876     // dependent bases, so we treat this result the same way as any other
877     // dependent nested-name-specifier.
878 
879     // C++ [temp.res]p2:
880     //   A name used in a template declaration or definition and that is
881     //   dependent on a template-parameter is assumed not to name a type
882     //   unless the applicable name lookup finds a type name or the name is
883     //   qualified by the keyword typename.
884     //
885     // FIXME: If the next token is '<', we might want to ask the parser to
886     // perform some heroics to see if we actually have a
887     // template-argument-list, which would indicate a missing 'template'
888     // keyword here.
889     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
890                                       NameInfo, IsAddressOfOperand,
891                                       /*TemplateArgs=*/nullptr);
892   }
893 
894   case LookupResult::Found:
895   case LookupResult::FoundOverloaded:
896   case LookupResult::FoundUnresolvedValue:
897     break;
898 
899   case LookupResult::Ambiguous:
900     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
901         hasAnyAcceptableTemplateNames(Result)) {
902       // C++ [temp.local]p3:
903       //   A lookup that finds an injected-class-name (10.2) can result in an
904       //   ambiguity in certain cases (for example, if it is found in more than
905       //   one base class). If all of the injected-class-names that are found
906       //   refer to specializations of the same class template, and if the name
907       //   is followed by a template-argument-list, the reference refers to the
908       //   class template itself and not a specialization thereof, and is not
909       //   ambiguous.
910       //
911       // This filtering can make an ambiguous result into an unambiguous one,
912       // so try again after filtering out template names.
913       FilterAcceptableTemplateNames(Result);
914       if (!Result.isAmbiguous()) {
915         IsFilteredTemplateName = true;
916         break;
917       }
918     }
919 
920     // Diagnose the ambiguity and return an error.
921     return NameClassification::Error();
922   }
923 
924   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
925       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
926     // C++ [temp.names]p3:
927     //   After name lookup (3.4) finds that a name is a template-name or that
928     //   an operator-function-id or a literal- operator-id refers to a set of
929     //   overloaded functions any member of which is a function template if
930     //   this is followed by a <, the < is always taken as the delimiter of a
931     //   template-argument-list and never as the less-than operator.
932     if (!IsFilteredTemplateName)
933       FilterAcceptableTemplateNames(Result);
934 
935     if (!Result.empty()) {
936       bool IsFunctionTemplate;
937       bool IsVarTemplate;
938       TemplateName Template;
939       if (Result.end() - Result.begin() > 1) {
940         IsFunctionTemplate = true;
941         Template = Context.getOverloadedTemplateName(Result.begin(),
942                                                      Result.end());
943       } else {
944         TemplateDecl *TD
945           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
946         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
947         IsVarTemplate = isa<VarTemplateDecl>(TD);
948 
949         if (SS.isSet() && !SS.isInvalid())
950           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
951                                                     /*TemplateKeyword=*/false,
952                                                       TD);
953         else
954           Template = TemplateName(TD);
955       }
956 
957       if (IsFunctionTemplate) {
958         // Function templates always go through overload resolution, at which
959         // point we'll perform the various checks (e.g., accessibility) we need
960         // to based on which function we selected.
961         Result.suppressDiagnostics();
962 
963         return NameClassification::FunctionTemplate(Template);
964       }
965 
966       return IsVarTemplate ? NameClassification::VarTemplate(Template)
967                            : NameClassification::TypeTemplate(Template);
968     }
969   }
970 
971   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
972   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
973     DiagnoseUseOfDecl(Type, NameLoc);
974     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
975     QualType T = Context.getTypeDeclType(Type);
976     if (SS.isNotEmpty())
977       return buildNestedType(*this, SS, T, NameLoc);
978     return ParsedType::make(T);
979   }
980 
981   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
982   if (!Class) {
983     // FIXME: It's unfortunate that we don't have a Type node for handling this.
984     if (ObjCCompatibleAliasDecl *Alias =
985             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
986       Class = Alias->getClassInterface();
987   }
988 
989   if (Class) {
990     DiagnoseUseOfDecl(Class, NameLoc);
991 
992     if (NextToken.is(tok::period)) {
993       // Interface. <something> is parsed as a property reference expression.
994       // Just return "unknown" as a fall-through for now.
995       Result.suppressDiagnostics();
996       return NameClassification::Unknown();
997     }
998 
999     QualType T = Context.getObjCInterfaceType(Class);
1000     return ParsedType::make(T);
1001   }
1002 
1003   // We can have a type template here if we're classifying a template argument.
1004   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1005     return NameClassification::TypeTemplate(
1006         TemplateName(cast<TemplateDecl>(FirstDecl)));
1007 
1008   // Check for a tag type hidden by a non-type decl in a few cases where it
1009   // seems likely a type is wanted instead of the non-type that was found.
1010   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1011   if ((NextToken.is(tok::identifier) ||
1012        (NextIsOp &&
1013         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1014       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1015     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1016     DiagnoseUseOfDecl(Type, NameLoc);
1017     QualType T = Context.getTypeDeclType(Type);
1018     if (SS.isNotEmpty())
1019       return buildNestedType(*this, SS, T, NameLoc);
1020     return ParsedType::make(T);
1021   }
1022 
1023   if (FirstDecl->isCXXClassMember())
1024     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1025                                            nullptr);
1026 
1027   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1028   return BuildDeclarationNameExpr(SS, Result, ADL);
1029 }
1030 
1031 // Determines the context to return to after temporarily entering a
1032 // context.  This depends in an unnecessarily complicated way on the
1033 // exact ordering of callbacks from the parser.
1034 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1035 
1036   // Functions defined inline within classes aren't parsed until we've
1037   // finished parsing the top-level class, so the top-level class is
1038   // the context we'll need to return to.
1039   // A Lambda call operator whose parent is a class must not be treated
1040   // as an inline member function.  A Lambda can be used legally
1041   // either as an in-class member initializer or a default argument.  These
1042   // are parsed once the class has been marked complete and so the containing
1043   // context would be the nested class (when the lambda is defined in one);
1044   // If the class is not complete, then the lambda is being used in an
1045   // ill-formed fashion (such as to specify the width of a bit-field, or
1046   // in an array-bound) - in which case we still want to return the
1047   // lexically containing DC (which could be a nested class).
1048   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1049     DC = DC->getLexicalParent();
1050 
1051     // A function not defined within a class will always return to its
1052     // lexical context.
1053     if (!isa<CXXRecordDecl>(DC))
1054       return DC;
1055 
1056     // A C++ inline method/friend is parsed *after* the topmost class
1057     // it was declared in is fully parsed ("complete");  the topmost
1058     // class is the context we need to return to.
1059     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1060       DC = RD;
1061 
1062     // Return the declaration context of the topmost class the inline method is
1063     // declared in.
1064     return DC;
1065   }
1066 
1067   return DC->getLexicalParent();
1068 }
1069 
1070 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1071   assert(getContainingDC(DC) == CurContext &&
1072       "The next DeclContext should be lexically contained in the current one.");
1073   CurContext = DC;
1074   S->setEntity(DC);
1075 }
1076 
1077 void Sema::PopDeclContext() {
1078   assert(CurContext && "DeclContext imbalance!");
1079 
1080   CurContext = getContainingDC(CurContext);
1081   assert(CurContext && "Popped translation unit!");
1082 }
1083 
1084 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1085                                                                     Decl *D) {
1086   // Unlike PushDeclContext, the context to which we return is not necessarily
1087   // the containing DC of TD, because the new context will be some pre-existing
1088   // TagDecl definition instead of a fresh one.
1089   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1090   CurContext = cast<TagDecl>(D)->getDefinition();
1091   assert(CurContext && "skipping definition of undefined tag");
1092   // Start lookups from the parent of the current context; we don't want to look
1093   // into the pre-existing complete definition.
1094   S->setEntity(CurContext->getLookupParent());
1095   return Result;
1096 }
1097 
1098 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1099   CurContext = static_cast<decltype(CurContext)>(Context);
1100 }
1101 
1102 /// EnterDeclaratorContext - Used when we must lookup names in the context
1103 /// of a declarator's nested name specifier.
1104 ///
1105 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1106   // C++0x [basic.lookup.unqual]p13:
1107   //   A name used in the definition of a static data member of class
1108   //   X (after the qualified-id of the static member) is looked up as
1109   //   if the name was used in a member function of X.
1110   // C++0x [basic.lookup.unqual]p14:
1111   //   If a variable member of a namespace is defined outside of the
1112   //   scope of its namespace then any name used in the definition of
1113   //   the variable member (after the declarator-id) is looked up as
1114   //   if the definition of the variable member occurred in its
1115   //   namespace.
1116   // Both of these imply that we should push a scope whose context
1117   // is the semantic context of the declaration.  We can't use
1118   // PushDeclContext here because that context is not necessarily
1119   // lexically contained in the current context.  Fortunately,
1120   // the containing scope should have the appropriate information.
1121 
1122   assert(!S->getEntity() && "scope already has entity");
1123 
1124 #ifndef NDEBUG
1125   Scope *Ancestor = S->getParent();
1126   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1127   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1128 #endif
1129 
1130   CurContext = DC;
1131   S->setEntity(DC);
1132 }
1133 
1134 void Sema::ExitDeclaratorContext(Scope *S) {
1135   assert(S->getEntity() == CurContext && "Context imbalance!");
1136 
1137   // Switch back to the lexical context.  The safety of this is
1138   // enforced by an assert in EnterDeclaratorContext.
1139   Scope *Ancestor = S->getParent();
1140   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1141   CurContext = Ancestor->getEntity();
1142 
1143   // We don't need to do anything with the scope, which is going to
1144   // disappear.
1145 }
1146 
1147 
1148 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1149   // We assume that the caller has already called
1150   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1151   FunctionDecl *FD = D->getAsFunction();
1152   if (!FD)
1153     return;
1154 
1155   // Same implementation as PushDeclContext, but enters the context
1156   // from the lexical parent, rather than the top-level class.
1157   assert(CurContext == FD->getLexicalParent() &&
1158     "The next DeclContext should be lexically contained in the current one.");
1159   CurContext = FD;
1160   S->setEntity(CurContext);
1161 
1162   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1163     ParmVarDecl *Param = FD->getParamDecl(P);
1164     // If the parameter has an identifier, then add it to the scope
1165     if (Param->getIdentifier()) {
1166       S->AddDecl(Param);
1167       IdResolver.AddDecl(Param);
1168     }
1169   }
1170 }
1171 
1172 
1173 void Sema::ActOnExitFunctionContext() {
1174   // Same implementation as PopDeclContext, but returns to the lexical parent,
1175   // rather than the top-level class.
1176   assert(CurContext && "DeclContext imbalance!");
1177   CurContext = CurContext->getLexicalParent();
1178   assert(CurContext && "Popped translation unit!");
1179 }
1180 
1181 
1182 /// \brief Determine whether we allow overloading of the function
1183 /// PrevDecl with another declaration.
1184 ///
1185 /// This routine determines whether overloading is possible, not
1186 /// whether some new function is actually an overload. It will return
1187 /// true in C++ (where we can always provide overloads) or, as an
1188 /// extension, in C when the previous function is already an
1189 /// overloaded function declaration or has the "overloadable"
1190 /// attribute.
1191 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1192                                        ASTContext &Context) {
1193   if (Context.getLangOpts().CPlusPlus)
1194     return true;
1195 
1196   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1197     return true;
1198 
1199   return (Previous.getResultKind() == LookupResult::Found
1200           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1201 }
1202 
1203 /// Add this decl to the scope shadowed decl chains.
1204 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1205   // Move up the scope chain until we find the nearest enclosing
1206   // non-transparent context. The declaration will be introduced into this
1207   // scope.
1208   while (S->getEntity() && S->getEntity()->isTransparentContext())
1209     S = S->getParent();
1210 
1211   // Add scoped declarations into their context, so that they can be
1212   // found later. Declarations without a context won't be inserted
1213   // into any context.
1214   if (AddToContext)
1215     CurContext->addDecl(D);
1216 
1217   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1218   // are function-local declarations.
1219   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1220       !D->getDeclContext()->getRedeclContext()->Equals(
1221         D->getLexicalDeclContext()->getRedeclContext()) &&
1222       !D->getLexicalDeclContext()->isFunctionOrMethod())
1223     return;
1224 
1225   // Template instantiations should also not be pushed into scope.
1226   if (isa<FunctionDecl>(D) &&
1227       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1228     return;
1229 
1230   // If this replaces anything in the current scope,
1231   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1232                                IEnd = IdResolver.end();
1233   for (; I != IEnd; ++I) {
1234     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1235       S->RemoveDecl(*I);
1236       IdResolver.RemoveDecl(*I);
1237 
1238       // Should only need to replace one decl.
1239       break;
1240     }
1241   }
1242 
1243   S->AddDecl(D);
1244 
1245   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1246     // Implicitly-generated labels may end up getting generated in an order that
1247     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1248     // the label at the appropriate place in the identifier chain.
1249     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1250       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1251       if (IDC == CurContext) {
1252         if (!S->isDeclScope(*I))
1253           continue;
1254       } else if (IDC->Encloses(CurContext))
1255         break;
1256     }
1257 
1258     IdResolver.InsertDeclAfter(I, D);
1259   } else {
1260     IdResolver.AddDecl(D);
1261   }
1262 }
1263 
1264 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1265   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1266     TUScope->AddDecl(D);
1267 }
1268 
1269 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1270                          bool AllowInlineNamespace) {
1271   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1272 }
1273 
1274 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1275   DeclContext *TargetDC = DC->getPrimaryContext();
1276   do {
1277     if (DeclContext *ScopeDC = S->getEntity())
1278       if (ScopeDC->getPrimaryContext() == TargetDC)
1279         return S;
1280   } while ((S = S->getParent()));
1281 
1282   return nullptr;
1283 }
1284 
1285 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1286                                             DeclContext*,
1287                                             ASTContext&);
1288 
1289 /// Filters out lookup results that don't fall within the given scope
1290 /// as determined by isDeclInScope.
1291 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1292                                 bool ConsiderLinkage,
1293                                 bool AllowInlineNamespace) {
1294   LookupResult::Filter F = R.makeFilter();
1295   while (F.hasNext()) {
1296     NamedDecl *D = F.next();
1297 
1298     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1299       continue;
1300 
1301     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1302       continue;
1303 
1304     F.erase();
1305   }
1306 
1307   F.done();
1308 }
1309 
1310 static bool isUsingDecl(NamedDecl *D) {
1311   return isa<UsingShadowDecl>(D) ||
1312          isa<UnresolvedUsingTypenameDecl>(D) ||
1313          isa<UnresolvedUsingValueDecl>(D);
1314 }
1315 
1316 /// Removes using shadow declarations from the lookup results.
1317 static void RemoveUsingDecls(LookupResult &R) {
1318   LookupResult::Filter F = R.makeFilter();
1319   while (F.hasNext())
1320     if (isUsingDecl(F.next()))
1321       F.erase();
1322 
1323   F.done();
1324 }
1325 
1326 /// \brief Check for this common pattern:
1327 /// @code
1328 /// class S {
1329 ///   S(const S&); // DO NOT IMPLEMENT
1330 ///   void operator=(const S&); // DO NOT IMPLEMENT
1331 /// };
1332 /// @endcode
1333 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1334   // FIXME: Should check for private access too but access is set after we get
1335   // the decl here.
1336   if (D->doesThisDeclarationHaveABody())
1337     return false;
1338 
1339   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1340     return CD->isCopyConstructor();
1341   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1342     return Method->isCopyAssignmentOperator();
1343   return false;
1344 }
1345 
1346 // We need this to handle
1347 //
1348 // typedef struct {
1349 //   void *foo() { return 0; }
1350 // } A;
1351 //
1352 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1353 // for example. If 'A', foo will have external linkage. If we have '*A',
1354 // foo will have no linkage. Since we can't know until we get to the end
1355 // of the typedef, this function finds out if D might have non-external linkage.
1356 // Callers should verify at the end of the TU if it D has external linkage or
1357 // not.
1358 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1359   const DeclContext *DC = D->getDeclContext();
1360   while (!DC->isTranslationUnit()) {
1361     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1362       if (!RD->hasNameForLinkage())
1363         return true;
1364     }
1365     DC = DC->getParent();
1366   }
1367 
1368   return !D->isExternallyVisible();
1369 }
1370 
1371 // FIXME: This needs to be refactored; some other isInMainFile users want
1372 // these semantics.
1373 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1374   if (S.TUKind != TU_Complete)
1375     return false;
1376   return S.SourceMgr.isInMainFile(Loc);
1377 }
1378 
1379 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1380   assert(D);
1381 
1382   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1383     return false;
1384 
1385   // Ignore all entities declared within templates, and out-of-line definitions
1386   // of members of class templates.
1387   if (D->getDeclContext()->isDependentContext() ||
1388       D->getLexicalDeclContext()->isDependentContext())
1389     return false;
1390 
1391   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1392     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1393       return false;
1394 
1395     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1396       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1397         return false;
1398     } else {
1399       // 'static inline' functions are defined in headers; don't warn.
1400       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1401         return false;
1402     }
1403 
1404     if (FD->doesThisDeclarationHaveABody() &&
1405         Context.DeclMustBeEmitted(FD))
1406       return false;
1407   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1408     // Constants and utility variables are defined in headers with internal
1409     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1410     // like "inline".)
1411     if (!isMainFileLoc(*this, VD->getLocation()))
1412       return false;
1413 
1414     if (Context.DeclMustBeEmitted(VD))
1415       return false;
1416 
1417     if (VD->isStaticDataMember() &&
1418         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1419       return false;
1420   } else {
1421     return false;
1422   }
1423 
1424   // Only warn for unused decls internal to the translation unit.
1425   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1426   // for inline functions defined in the main source file, for instance.
1427   return mightHaveNonExternalLinkage(D);
1428 }
1429 
1430 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1431   if (!D)
1432     return;
1433 
1434   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1435     const FunctionDecl *First = FD->getFirstDecl();
1436     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1437       return; // First should already be in the vector.
1438   }
1439 
1440   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1441     const VarDecl *First = VD->getFirstDecl();
1442     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1443       return; // First should already be in the vector.
1444   }
1445 
1446   if (ShouldWarnIfUnusedFileScopedDecl(D))
1447     UnusedFileScopedDecls.push_back(D);
1448 }
1449 
1450 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1451   if (D->isInvalidDecl())
1452     return false;
1453 
1454   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1455       D->hasAttr<ObjCPreciseLifetimeAttr>())
1456     return false;
1457 
1458   if (isa<LabelDecl>(D))
1459     return true;
1460 
1461   // Except for labels, we only care about unused decls that are local to
1462   // functions.
1463   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1464   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1465     // For dependent types, the diagnostic is deferred.
1466     WithinFunction =
1467         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1468   if (!WithinFunction)
1469     return false;
1470 
1471   if (isa<TypedefNameDecl>(D))
1472     return true;
1473 
1474   // White-list anything that isn't a local variable.
1475   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1476     return false;
1477 
1478   // Types of valid local variables should be complete, so this should succeed.
1479   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1480 
1481     // White-list anything with an __attribute__((unused)) type.
1482     QualType Ty = VD->getType();
1483 
1484     // Only look at the outermost level of typedef.
1485     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1486       if (TT->getDecl()->hasAttr<UnusedAttr>())
1487         return false;
1488     }
1489 
1490     // If we failed to complete the type for some reason, or if the type is
1491     // dependent, don't diagnose the variable.
1492     if (Ty->isIncompleteType() || Ty->isDependentType())
1493       return false;
1494 
1495     if (const TagType *TT = Ty->getAs<TagType>()) {
1496       const TagDecl *Tag = TT->getDecl();
1497       if (Tag->hasAttr<UnusedAttr>())
1498         return false;
1499 
1500       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1501         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1502           return false;
1503 
1504         if (const Expr *Init = VD->getInit()) {
1505           if (const ExprWithCleanups *Cleanups =
1506                   dyn_cast<ExprWithCleanups>(Init))
1507             Init = Cleanups->getSubExpr();
1508           const CXXConstructExpr *Construct =
1509             dyn_cast<CXXConstructExpr>(Init);
1510           if (Construct && !Construct->isElidable()) {
1511             CXXConstructorDecl *CD = Construct->getConstructor();
1512             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1513               return false;
1514           }
1515         }
1516       }
1517     }
1518 
1519     // TODO: __attribute__((unused)) templates?
1520   }
1521 
1522   return true;
1523 }
1524 
1525 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1526                                      FixItHint &Hint) {
1527   if (isa<LabelDecl>(D)) {
1528     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1529                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1530     if (AfterColon.isInvalid())
1531       return;
1532     Hint = FixItHint::CreateRemoval(CharSourceRange::
1533                                     getCharRange(D->getLocStart(), AfterColon));
1534   }
1535   return;
1536 }
1537 
1538 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1539   if (D->getTypeForDecl()->isDependentType())
1540     return;
1541 
1542   for (auto *TmpD : D->decls()) {
1543     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1544       DiagnoseUnusedDecl(T);
1545     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1546       DiagnoseUnusedNestedTypedefs(R);
1547   }
1548 }
1549 
1550 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1551 /// unless they are marked attr(unused).
1552 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1553   if (!ShouldDiagnoseUnusedDecl(D))
1554     return;
1555 
1556   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1557     // typedefs can be referenced later on, so the diagnostics are emitted
1558     // at end-of-translation-unit.
1559     UnusedLocalTypedefNameCandidates.insert(TD);
1560     return;
1561   }
1562 
1563   FixItHint Hint;
1564   GenerateFixForUnusedDecl(D, Context, Hint);
1565 
1566   unsigned DiagID;
1567   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1568     DiagID = diag::warn_unused_exception_param;
1569   else if (isa<LabelDecl>(D))
1570     DiagID = diag::warn_unused_label;
1571   else
1572     DiagID = diag::warn_unused_variable;
1573 
1574   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1575 }
1576 
1577 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1578   // Verify that we have no forward references left.  If so, there was a goto
1579   // or address of a label taken, but no definition of it.  Label fwd
1580   // definitions are indicated with a null substmt which is also not a resolved
1581   // MS inline assembly label name.
1582   bool Diagnose = false;
1583   if (L->isMSAsmLabel())
1584     Diagnose = !L->isResolvedMSAsmLabel();
1585   else
1586     Diagnose = L->getStmt() == nullptr;
1587   if (Diagnose)
1588     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1589 }
1590 
1591 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1592   S->mergeNRVOIntoParent();
1593 
1594   if (S->decl_empty()) return;
1595   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1596          "Scope shouldn't contain decls!");
1597 
1598   for (auto *TmpD : S->decls()) {
1599     assert(TmpD && "This decl didn't get pushed??");
1600 
1601     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1602     NamedDecl *D = cast<NamedDecl>(TmpD);
1603 
1604     if (!D->getDeclName()) continue;
1605 
1606     // Diagnose unused variables in this scope.
1607     if (!S->hasUnrecoverableErrorOccurred()) {
1608       DiagnoseUnusedDecl(D);
1609       if (const auto *RD = dyn_cast<RecordDecl>(D))
1610         DiagnoseUnusedNestedTypedefs(RD);
1611     }
1612 
1613     // If this was a forward reference to a label, verify it was defined.
1614     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1615       CheckPoppedLabel(LD, *this);
1616 
1617     // Remove this name from our lexical scope.
1618     IdResolver.RemoveDecl(D);
1619   }
1620 }
1621 
1622 /// \brief Look for an Objective-C class in the translation unit.
1623 ///
1624 /// \param Id The name of the Objective-C class we're looking for. If
1625 /// typo-correction fixes this name, the Id will be updated
1626 /// to the fixed name.
1627 ///
1628 /// \param IdLoc The location of the name in the translation unit.
1629 ///
1630 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1631 /// if there is no class with the given name.
1632 ///
1633 /// \returns The declaration of the named Objective-C class, or NULL if the
1634 /// class could not be found.
1635 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1636                                               SourceLocation IdLoc,
1637                                               bool DoTypoCorrection) {
1638   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1639   // creation from this context.
1640   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1641 
1642   if (!IDecl && DoTypoCorrection) {
1643     // Perform typo correction at the given location, but only if we
1644     // find an Objective-C class name.
1645     if (TypoCorrection C = CorrectTypo(
1646             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1647             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1648             CTK_ErrorRecovery)) {
1649       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1650       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1651       Id = IDecl->getIdentifier();
1652     }
1653   }
1654   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1655   // This routine must always return a class definition, if any.
1656   if (Def && Def->getDefinition())
1657       Def = Def->getDefinition();
1658   return Def;
1659 }
1660 
1661 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1662 /// from S, where a non-field would be declared. This routine copes
1663 /// with the difference between C and C++ scoping rules in structs and
1664 /// unions. For example, the following code is well-formed in C but
1665 /// ill-formed in C++:
1666 /// @code
1667 /// struct S6 {
1668 ///   enum { BAR } e;
1669 /// };
1670 ///
1671 /// void test_S6() {
1672 ///   struct S6 a;
1673 ///   a.e = BAR;
1674 /// }
1675 /// @endcode
1676 /// For the declaration of BAR, this routine will return a different
1677 /// scope. The scope S will be the scope of the unnamed enumeration
1678 /// within S6. In C++, this routine will return the scope associated
1679 /// with S6, because the enumeration's scope is a transparent
1680 /// context but structures can contain non-field names. In C, this
1681 /// routine will return the translation unit scope, since the
1682 /// enumeration's scope is a transparent context and structures cannot
1683 /// contain non-field names.
1684 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1685   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1686          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1687          (S->isClassScope() && !getLangOpts().CPlusPlus))
1688     S = S->getParent();
1689   return S;
1690 }
1691 
1692 /// \brief Looks up the declaration of "struct objc_super" and
1693 /// saves it for later use in building builtin declaration of
1694 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1695 /// pre-existing declaration exists no action takes place.
1696 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1697                                         IdentifierInfo *II) {
1698   if (!II->isStr("objc_msgSendSuper"))
1699     return;
1700   ASTContext &Context = ThisSema.Context;
1701 
1702   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1703                       SourceLocation(), Sema::LookupTagName);
1704   ThisSema.LookupName(Result, S);
1705   if (Result.getResultKind() == LookupResult::Found)
1706     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1707       Context.setObjCSuperType(Context.getTagDeclType(TD));
1708 }
1709 
1710 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1711   switch (Error) {
1712   case ASTContext::GE_None:
1713     return "";
1714   case ASTContext::GE_Missing_stdio:
1715     return "stdio.h";
1716   case ASTContext::GE_Missing_setjmp:
1717     return "setjmp.h";
1718   case ASTContext::GE_Missing_ucontext:
1719     return "ucontext.h";
1720   }
1721   llvm_unreachable("unhandled error kind");
1722 }
1723 
1724 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1725 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1726 /// if we're creating this built-in in anticipation of redeclaring the
1727 /// built-in.
1728 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1729                                      Scope *S, bool ForRedeclaration,
1730                                      SourceLocation Loc) {
1731   LookupPredefedObjCSuperType(*this, S, II);
1732 
1733   ASTContext::GetBuiltinTypeError Error;
1734   QualType R = Context.GetBuiltinType(ID, Error);
1735   if (Error) {
1736     if (ForRedeclaration)
1737       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1738           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1739     return nullptr;
1740   }
1741 
1742   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1743     Diag(Loc, diag::ext_implicit_lib_function_decl)
1744         << Context.BuiltinInfo.getName(ID) << R;
1745     if (Context.BuiltinInfo.getHeaderName(ID) &&
1746         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1747       Diag(Loc, diag::note_include_header_or_declare)
1748           << Context.BuiltinInfo.getHeaderName(ID)
1749           << Context.BuiltinInfo.getName(ID);
1750   }
1751 
1752   DeclContext *Parent = Context.getTranslationUnitDecl();
1753   if (getLangOpts().CPlusPlus) {
1754     LinkageSpecDecl *CLinkageDecl =
1755         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1756                                 LinkageSpecDecl::lang_c, false);
1757     CLinkageDecl->setImplicit();
1758     Parent->addDecl(CLinkageDecl);
1759     Parent = CLinkageDecl;
1760   }
1761 
1762   FunctionDecl *New = FunctionDecl::Create(Context,
1763                                            Parent,
1764                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1765                                            SC_Extern,
1766                                            false,
1767                                            R->isFunctionProtoType());
1768   New->setImplicit();
1769 
1770   // Create Decl objects for each parameter, adding them to the
1771   // FunctionDecl.
1772   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1773     SmallVector<ParmVarDecl*, 16> Params;
1774     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1775       ParmVarDecl *parm =
1776           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1777                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1778                               SC_None, nullptr);
1779       parm->setScopeInfo(0, i);
1780       Params.push_back(parm);
1781     }
1782     New->setParams(Params);
1783   }
1784 
1785   AddKnownFunctionAttributes(New);
1786   RegisterLocallyScopedExternCDecl(New, S);
1787 
1788   // TUScope is the translation-unit scope to insert this function into.
1789   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1790   // relate Scopes to DeclContexts, and probably eliminate CurContext
1791   // entirely, but we're not there yet.
1792   DeclContext *SavedContext = CurContext;
1793   CurContext = Parent;
1794   PushOnScopeChains(New, TUScope);
1795   CurContext = SavedContext;
1796   return New;
1797 }
1798 
1799 /// Typedef declarations don't have linkage, but they still denote the same
1800 /// entity if their types are the same.
1801 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1802 /// isSameEntity.
1803 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1804                                                      TypedefNameDecl *Decl,
1805                                                      LookupResult &Previous) {
1806   // This is only interesting when modules are enabled.
1807   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1808     return;
1809 
1810   // Empty sets are uninteresting.
1811   if (Previous.empty())
1812     return;
1813 
1814   LookupResult::Filter Filter = Previous.makeFilter();
1815   while (Filter.hasNext()) {
1816     NamedDecl *Old = Filter.next();
1817 
1818     // Non-hidden declarations are never ignored.
1819     if (S.isVisible(Old))
1820       continue;
1821 
1822     // Declarations of the same entity are not ignored, even if they have
1823     // different linkages.
1824     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1825       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1826                                 Decl->getUnderlyingType()))
1827         continue;
1828 
1829       // If both declarations give a tag declaration a typedef name for linkage
1830       // purposes, then they declare the same entity.
1831       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1832           Decl->getAnonDeclWithTypedefName())
1833         continue;
1834     }
1835 
1836     if (!Old->isExternallyVisible())
1837       Filter.erase();
1838   }
1839 
1840   Filter.done();
1841 }
1842 
1843 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1844   QualType OldType;
1845   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1846     OldType = OldTypedef->getUnderlyingType();
1847   else
1848     OldType = Context.getTypeDeclType(Old);
1849   QualType NewType = New->getUnderlyingType();
1850 
1851   if (NewType->isVariablyModifiedType()) {
1852     // Must not redefine a typedef with a variably-modified type.
1853     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1854     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1855       << Kind << NewType;
1856     if (Old->getLocation().isValid())
1857       Diag(Old->getLocation(), diag::note_previous_definition);
1858     New->setInvalidDecl();
1859     return true;
1860   }
1861 
1862   if (OldType != NewType &&
1863       !OldType->isDependentType() &&
1864       !NewType->isDependentType() &&
1865       !Context.hasSameType(OldType, NewType)) {
1866     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1867     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1868       << Kind << NewType << OldType;
1869     if (Old->getLocation().isValid())
1870       Diag(Old->getLocation(), diag::note_previous_definition);
1871     New->setInvalidDecl();
1872     return true;
1873   }
1874   return false;
1875 }
1876 
1877 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1878 /// same name and scope as a previous declaration 'Old'.  Figure out
1879 /// how to resolve this situation, merging decls or emitting
1880 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1881 ///
1882 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1883   // If the new decl is known invalid already, don't bother doing any
1884   // merging checks.
1885   if (New->isInvalidDecl()) return;
1886 
1887   // Allow multiple definitions for ObjC built-in typedefs.
1888   // FIXME: Verify the underlying types are equivalent!
1889   if (getLangOpts().ObjC1) {
1890     const IdentifierInfo *TypeID = New->getIdentifier();
1891     switch (TypeID->getLength()) {
1892     default: break;
1893     case 2:
1894       {
1895         if (!TypeID->isStr("id"))
1896           break;
1897         QualType T = New->getUnderlyingType();
1898         if (!T->isPointerType())
1899           break;
1900         if (!T->isVoidPointerType()) {
1901           QualType PT = T->getAs<PointerType>()->getPointeeType();
1902           if (!PT->isStructureType())
1903             break;
1904         }
1905         Context.setObjCIdRedefinitionType(T);
1906         // Install the built-in type for 'id', ignoring the current definition.
1907         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1908         return;
1909       }
1910     case 5:
1911       if (!TypeID->isStr("Class"))
1912         break;
1913       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1914       // Install the built-in type for 'Class', ignoring the current definition.
1915       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1916       return;
1917     case 3:
1918       if (!TypeID->isStr("SEL"))
1919         break;
1920       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1921       // Install the built-in type for 'SEL', ignoring the current definition.
1922       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1923       return;
1924     }
1925     // Fall through - the typedef name was not a builtin type.
1926   }
1927 
1928   // Verify the old decl was also a type.
1929   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1930   if (!Old) {
1931     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1932       << New->getDeclName();
1933 
1934     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1935     if (OldD->getLocation().isValid())
1936       Diag(OldD->getLocation(), diag::note_previous_definition);
1937 
1938     return New->setInvalidDecl();
1939   }
1940 
1941   // If the old declaration is invalid, just give up here.
1942   if (Old->isInvalidDecl())
1943     return New->setInvalidDecl();
1944 
1945   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1946     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
1947     auto *NewTag = New->getAnonDeclWithTypedefName();
1948     NamedDecl *Hidden = nullptr;
1949     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
1950         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
1951         !hasVisibleDefinition(OldTag, &Hidden)) {
1952       // There is a definition of this tag, but it is not visible. Use it
1953       // instead of our tag.
1954       New->setTypeForDecl(OldTD->getTypeForDecl());
1955       if (OldTD->isModed())
1956         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
1957                                     OldTD->getUnderlyingType());
1958       else
1959         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
1960 
1961       // Make the old tag definition visible.
1962       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
1963     }
1964   }
1965 
1966   // If the typedef types are not identical, reject them in all languages and
1967   // with any extensions enabled.
1968   if (isIncompatibleTypedef(Old, New))
1969     return;
1970 
1971   // The types match.  Link up the redeclaration chain and merge attributes if
1972   // the old declaration was a typedef.
1973   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1974     New->setPreviousDecl(Typedef);
1975     mergeDeclAttributes(New, Old);
1976   }
1977 
1978   if (getLangOpts().MicrosoftExt)
1979     return;
1980 
1981   if (getLangOpts().CPlusPlus) {
1982     // C++ [dcl.typedef]p2:
1983     //   In a given non-class scope, a typedef specifier can be used to
1984     //   redefine the name of any type declared in that scope to refer
1985     //   to the type to which it already refers.
1986     if (!isa<CXXRecordDecl>(CurContext))
1987       return;
1988 
1989     // C++0x [dcl.typedef]p4:
1990     //   In a given class scope, a typedef specifier can be used to redefine
1991     //   any class-name declared in that scope that is not also a typedef-name
1992     //   to refer to the type to which it already refers.
1993     //
1994     // This wording came in via DR424, which was a correction to the
1995     // wording in DR56, which accidentally banned code like:
1996     //
1997     //   struct S {
1998     //     typedef struct A { } A;
1999     //   };
2000     //
2001     // in the C++03 standard. We implement the C++0x semantics, which
2002     // allow the above but disallow
2003     //
2004     //   struct S {
2005     //     typedef int I;
2006     //     typedef int I;
2007     //   };
2008     //
2009     // since that was the intent of DR56.
2010     if (!isa<TypedefNameDecl>(Old))
2011       return;
2012 
2013     Diag(New->getLocation(), diag::err_redefinition)
2014       << New->getDeclName();
2015     Diag(Old->getLocation(), diag::note_previous_definition);
2016     return New->setInvalidDecl();
2017   }
2018 
2019   // Modules always permit redefinition of typedefs, as does C11.
2020   if (getLangOpts().Modules || getLangOpts().C11)
2021     return;
2022 
2023   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2024   // is normally mapped to an error, but can be controlled with
2025   // -Wtypedef-redefinition.  If either the original or the redefinition is
2026   // in a system header, don't emit this for compatibility with GCC.
2027   if (getDiagnostics().getSuppressSystemWarnings() &&
2028       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2029        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2030     return;
2031 
2032   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2033     << New->getDeclName();
2034   Diag(Old->getLocation(), diag::note_previous_definition);
2035 }
2036 
2037 /// DeclhasAttr - returns true if decl Declaration already has the target
2038 /// attribute.
2039 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2040   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2041   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2042   for (const auto *i : D->attrs())
2043     if (i->getKind() == A->getKind()) {
2044       if (Ann) {
2045         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2046           return true;
2047         continue;
2048       }
2049       // FIXME: Don't hardcode this check
2050       if (OA && isa<OwnershipAttr>(i))
2051         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2052       return true;
2053     }
2054 
2055   return false;
2056 }
2057 
2058 static bool isAttributeTargetADefinition(Decl *D) {
2059   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2060     return VD->isThisDeclarationADefinition();
2061   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2062     return TD->isCompleteDefinition() || TD->isBeingDefined();
2063   return true;
2064 }
2065 
2066 /// Merge alignment attributes from \p Old to \p New, taking into account the
2067 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2068 ///
2069 /// \return \c true if any attributes were added to \p New.
2070 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2071   // Look for alignas attributes on Old, and pick out whichever attribute
2072   // specifies the strictest alignment requirement.
2073   AlignedAttr *OldAlignasAttr = nullptr;
2074   AlignedAttr *OldStrictestAlignAttr = nullptr;
2075   unsigned OldAlign = 0;
2076   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2077     // FIXME: We have no way of representing inherited dependent alignments
2078     // in a case like:
2079     //   template<int A, int B> struct alignas(A) X;
2080     //   template<int A, int B> struct alignas(B) X {};
2081     // For now, we just ignore any alignas attributes which are not on the
2082     // definition in such a case.
2083     if (I->isAlignmentDependent())
2084       return false;
2085 
2086     if (I->isAlignas())
2087       OldAlignasAttr = I;
2088 
2089     unsigned Align = I->getAlignment(S.Context);
2090     if (Align > OldAlign) {
2091       OldAlign = Align;
2092       OldStrictestAlignAttr = I;
2093     }
2094   }
2095 
2096   // Look for alignas attributes on New.
2097   AlignedAttr *NewAlignasAttr = nullptr;
2098   unsigned NewAlign = 0;
2099   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2100     if (I->isAlignmentDependent())
2101       return false;
2102 
2103     if (I->isAlignas())
2104       NewAlignasAttr = I;
2105 
2106     unsigned Align = I->getAlignment(S.Context);
2107     if (Align > NewAlign)
2108       NewAlign = Align;
2109   }
2110 
2111   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2112     // Both declarations have 'alignas' attributes. We require them to match.
2113     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2114     // fall short. (If two declarations both have alignas, they must both match
2115     // every definition, and so must match each other if there is a definition.)
2116 
2117     // If either declaration only contains 'alignas(0)' specifiers, then it
2118     // specifies the natural alignment for the type.
2119     if (OldAlign == 0 || NewAlign == 0) {
2120       QualType Ty;
2121       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2122         Ty = VD->getType();
2123       else
2124         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2125 
2126       if (OldAlign == 0)
2127         OldAlign = S.Context.getTypeAlign(Ty);
2128       if (NewAlign == 0)
2129         NewAlign = S.Context.getTypeAlign(Ty);
2130     }
2131 
2132     if (OldAlign != NewAlign) {
2133       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2134         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2135         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2136       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2137     }
2138   }
2139 
2140   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2141     // C++11 [dcl.align]p6:
2142     //   if any declaration of an entity has an alignment-specifier,
2143     //   every defining declaration of that entity shall specify an
2144     //   equivalent alignment.
2145     // C11 6.7.5/7:
2146     //   If the definition of an object does not have an alignment
2147     //   specifier, any other declaration of that object shall also
2148     //   have no alignment specifier.
2149     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2150       << OldAlignasAttr;
2151     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2152       << OldAlignasAttr;
2153   }
2154 
2155   bool AnyAdded = false;
2156 
2157   // Ensure we have an attribute representing the strictest alignment.
2158   if (OldAlign > NewAlign) {
2159     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2160     Clone->setInherited(true);
2161     New->addAttr(Clone);
2162     AnyAdded = true;
2163   }
2164 
2165   // Ensure we have an alignas attribute if the old declaration had one.
2166   if (OldAlignasAttr && !NewAlignasAttr &&
2167       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2168     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2169     Clone->setInherited(true);
2170     New->addAttr(Clone);
2171     AnyAdded = true;
2172   }
2173 
2174   return AnyAdded;
2175 }
2176 
2177 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2178                                const InheritableAttr *Attr, bool Override) {
2179   InheritableAttr *NewAttr = nullptr;
2180   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2181   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2182     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2183                                       AA->getIntroduced(), AA->getDeprecated(),
2184                                       AA->getObsoleted(), AA->getUnavailable(),
2185                                       AA->getMessage(), Override,
2186                                       AttrSpellingListIndex);
2187   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2188     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2189                                     AttrSpellingListIndex);
2190   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2191     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2192                                         AttrSpellingListIndex);
2193   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2194     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2195                                    AttrSpellingListIndex);
2196   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2197     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2198                                    AttrSpellingListIndex);
2199   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2200     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2201                                 FA->getFormatIdx(), FA->getFirstArg(),
2202                                 AttrSpellingListIndex);
2203   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2204     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2205                                  AttrSpellingListIndex);
2206   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2207     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2208                                        AttrSpellingListIndex,
2209                                        IA->getSemanticSpelling());
2210   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2211     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2212                                       &S.Context.Idents.get(AA->getSpelling()),
2213                                       AttrSpellingListIndex);
2214   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2215     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2216   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2217     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2218   else if (isa<AlignedAttr>(Attr))
2219     // AlignedAttrs are handled separately, because we need to handle all
2220     // such attributes on a declaration at the same time.
2221     NewAttr = nullptr;
2222   else if (isa<DeprecatedAttr>(Attr) && Override)
2223     NewAttr = nullptr;
2224   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2225     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2226 
2227   if (NewAttr) {
2228     NewAttr->setInherited(true);
2229     D->addAttr(NewAttr);
2230     return true;
2231   }
2232 
2233   return false;
2234 }
2235 
2236 static const Decl *getDefinition(const Decl *D) {
2237   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2238     return TD->getDefinition();
2239   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2240     const VarDecl *Def = VD->getDefinition();
2241     if (Def)
2242       return Def;
2243     return VD->getActingDefinition();
2244   }
2245   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2246     const FunctionDecl* Def;
2247     if (FD->isDefined(Def))
2248       return Def;
2249   }
2250   return nullptr;
2251 }
2252 
2253 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2254   for (const auto *Attribute : D->attrs())
2255     if (Attribute->getKind() == Kind)
2256       return true;
2257   return false;
2258 }
2259 
2260 /// checkNewAttributesAfterDef - If we already have a definition, check that
2261 /// there are no new attributes in this declaration.
2262 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2263   if (!New->hasAttrs())
2264     return;
2265 
2266   const Decl *Def = getDefinition(Old);
2267   if (!Def || Def == New)
2268     return;
2269 
2270   AttrVec &NewAttributes = New->getAttrs();
2271   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2272     const Attr *NewAttribute = NewAttributes[I];
2273 
2274     if (isa<AliasAttr>(NewAttribute)) {
2275       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2276         Sema::SkipBodyInfo SkipBody;
2277         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2278 
2279         // If we're skipping this definition, drop the "alias" attribute.
2280         if (SkipBody.ShouldSkip) {
2281           NewAttributes.erase(NewAttributes.begin() + I);
2282           --E;
2283           continue;
2284         }
2285       } else {
2286         VarDecl *VD = cast<VarDecl>(New);
2287         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2288                                 VarDecl::TentativeDefinition
2289                             ? diag::err_alias_after_tentative
2290                             : diag::err_redefinition;
2291         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2292         S.Diag(Def->getLocation(), diag::note_previous_definition);
2293         VD->setInvalidDecl();
2294       }
2295       ++I;
2296       continue;
2297     }
2298 
2299     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2300       // Tentative definitions are only interesting for the alias check above.
2301       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2302         ++I;
2303         continue;
2304       }
2305     }
2306 
2307     if (hasAttribute(Def, NewAttribute->getKind())) {
2308       ++I;
2309       continue; // regular attr merging will take care of validating this.
2310     }
2311 
2312     if (isa<C11NoReturnAttr>(NewAttribute)) {
2313       // C's _Noreturn is allowed to be added to a function after it is defined.
2314       ++I;
2315       continue;
2316     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2317       if (AA->isAlignas()) {
2318         // C++11 [dcl.align]p6:
2319         //   if any declaration of an entity has an alignment-specifier,
2320         //   every defining declaration of that entity shall specify an
2321         //   equivalent alignment.
2322         // C11 6.7.5/7:
2323         //   If the definition of an object does not have an alignment
2324         //   specifier, any other declaration of that object shall also
2325         //   have no alignment specifier.
2326         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2327           << AA;
2328         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2329           << AA;
2330         NewAttributes.erase(NewAttributes.begin() + I);
2331         --E;
2332         continue;
2333       }
2334     }
2335 
2336     S.Diag(NewAttribute->getLocation(),
2337            diag::warn_attribute_precede_definition);
2338     S.Diag(Def->getLocation(), diag::note_previous_definition);
2339     NewAttributes.erase(NewAttributes.begin() + I);
2340     --E;
2341   }
2342 }
2343 
2344 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2345 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2346                                AvailabilityMergeKind AMK) {
2347   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2348     UsedAttr *NewAttr = OldAttr->clone(Context);
2349     NewAttr->setInherited(true);
2350     New->addAttr(NewAttr);
2351   }
2352 
2353   if (!Old->hasAttrs() && !New->hasAttrs())
2354     return;
2355 
2356   // attributes declared post-definition are currently ignored
2357   checkNewAttributesAfterDef(*this, New, Old);
2358 
2359   if (!Old->hasAttrs())
2360     return;
2361 
2362   bool foundAny = New->hasAttrs();
2363 
2364   // Ensure that any moving of objects within the allocated map is done before
2365   // we process them.
2366   if (!foundAny) New->setAttrs(AttrVec());
2367 
2368   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2369     bool Override = false;
2370     // Ignore deprecated/unavailable/availability attributes if requested.
2371     if (isa<DeprecatedAttr>(I) ||
2372         isa<UnavailableAttr>(I) ||
2373         isa<AvailabilityAttr>(I)) {
2374       switch (AMK) {
2375       case AMK_None:
2376         continue;
2377 
2378       case AMK_Redeclaration:
2379         break;
2380 
2381       case AMK_Override:
2382         Override = true;
2383         break;
2384       }
2385     }
2386 
2387     // Already handled.
2388     if (isa<UsedAttr>(I))
2389       continue;
2390 
2391     if (mergeDeclAttribute(*this, New, I, Override))
2392       foundAny = true;
2393   }
2394 
2395   if (mergeAlignedAttrs(*this, New, Old))
2396     foundAny = true;
2397 
2398   if (!foundAny) New->dropAttrs();
2399 }
2400 
2401 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2402 /// to the new one.
2403 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2404                                      const ParmVarDecl *oldDecl,
2405                                      Sema &S) {
2406   // C++11 [dcl.attr.depend]p2:
2407   //   The first declaration of a function shall specify the
2408   //   carries_dependency attribute for its declarator-id if any declaration
2409   //   of the function specifies the carries_dependency attribute.
2410   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2411   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2412     S.Diag(CDA->getLocation(),
2413            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2414     // Find the first declaration of the parameter.
2415     // FIXME: Should we build redeclaration chains for function parameters?
2416     const FunctionDecl *FirstFD =
2417       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2418     const ParmVarDecl *FirstVD =
2419       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2420     S.Diag(FirstVD->getLocation(),
2421            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2422   }
2423 
2424   if (!oldDecl->hasAttrs())
2425     return;
2426 
2427   bool foundAny = newDecl->hasAttrs();
2428 
2429   // Ensure that any moving of objects within the allocated map is
2430   // done before we process them.
2431   if (!foundAny) newDecl->setAttrs(AttrVec());
2432 
2433   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2434     if (!DeclHasAttr(newDecl, I)) {
2435       InheritableAttr *newAttr =
2436         cast<InheritableParamAttr>(I->clone(S.Context));
2437       newAttr->setInherited(true);
2438       newDecl->addAttr(newAttr);
2439       foundAny = true;
2440     }
2441   }
2442 
2443   if (!foundAny) newDecl->dropAttrs();
2444 }
2445 
2446 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2447                                 const ParmVarDecl *OldParam,
2448                                 Sema &S) {
2449   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2450     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2451       if (*Oldnullability != *Newnullability) {
2452         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2453           << DiagNullabilityKind(
2454                *Newnullability,
2455                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2456                 != 0))
2457           << DiagNullabilityKind(
2458                *Oldnullability,
2459                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2460                 != 0));
2461         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2462       }
2463     } else {
2464       QualType NewT = NewParam->getType();
2465       NewT = S.Context.getAttributedType(
2466                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2467                          NewT, NewT);
2468       NewParam->setType(NewT);
2469     }
2470   }
2471 }
2472 
2473 namespace {
2474 
2475 /// Used in MergeFunctionDecl to keep track of function parameters in
2476 /// C.
2477 struct GNUCompatibleParamWarning {
2478   ParmVarDecl *OldParm;
2479   ParmVarDecl *NewParm;
2480   QualType PromotedType;
2481 };
2482 
2483 }
2484 
2485 /// getSpecialMember - get the special member enum for a method.
2486 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2487   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2488     if (Ctor->isDefaultConstructor())
2489       return Sema::CXXDefaultConstructor;
2490 
2491     if (Ctor->isCopyConstructor())
2492       return Sema::CXXCopyConstructor;
2493 
2494     if (Ctor->isMoveConstructor())
2495       return Sema::CXXMoveConstructor;
2496   } else if (isa<CXXDestructorDecl>(MD)) {
2497     return Sema::CXXDestructor;
2498   } else if (MD->isCopyAssignmentOperator()) {
2499     return Sema::CXXCopyAssignment;
2500   } else if (MD->isMoveAssignmentOperator()) {
2501     return Sema::CXXMoveAssignment;
2502   }
2503 
2504   return Sema::CXXInvalid;
2505 }
2506 
2507 // Determine whether the previous declaration was a definition, implicit
2508 // declaration, or a declaration.
2509 template <typename T>
2510 static std::pair<diag::kind, SourceLocation>
2511 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2512   diag::kind PrevDiag;
2513   SourceLocation OldLocation = Old->getLocation();
2514   if (Old->isThisDeclarationADefinition())
2515     PrevDiag = diag::note_previous_definition;
2516   else if (Old->isImplicit()) {
2517     PrevDiag = diag::note_previous_implicit_declaration;
2518     if (OldLocation.isInvalid())
2519       OldLocation = New->getLocation();
2520   } else
2521     PrevDiag = diag::note_previous_declaration;
2522   return std::make_pair(PrevDiag, OldLocation);
2523 }
2524 
2525 /// canRedefineFunction - checks if a function can be redefined. Currently,
2526 /// only extern inline functions can be redefined, and even then only in
2527 /// GNU89 mode.
2528 static bool canRedefineFunction(const FunctionDecl *FD,
2529                                 const LangOptions& LangOpts) {
2530   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2531           !LangOpts.CPlusPlus &&
2532           FD->isInlineSpecified() &&
2533           FD->getStorageClass() == SC_Extern);
2534 }
2535 
2536 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2537   const AttributedType *AT = T->getAs<AttributedType>();
2538   while (AT && !AT->isCallingConv())
2539     AT = AT->getModifiedType()->getAs<AttributedType>();
2540   return AT;
2541 }
2542 
2543 template <typename T>
2544 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2545   const DeclContext *DC = Old->getDeclContext();
2546   if (DC->isRecord())
2547     return false;
2548 
2549   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2550   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2551     return true;
2552   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2553     return true;
2554   return false;
2555 }
2556 
2557 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2558 static bool isExternC(VarTemplateDecl *) { return false; }
2559 
2560 /// \brief Check whether a redeclaration of an entity introduced by a
2561 /// using-declaration is valid, given that we know it's not an overload
2562 /// (nor a hidden tag declaration).
2563 template<typename ExpectedDecl>
2564 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2565                                    ExpectedDecl *New) {
2566   // C++11 [basic.scope.declarative]p4:
2567   //   Given a set of declarations in a single declarative region, each of
2568   //   which specifies the same unqualified name,
2569   //   -- they shall all refer to the same entity, or all refer to functions
2570   //      and function templates; or
2571   //   -- exactly one declaration shall declare a class name or enumeration
2572   //      name that is not a typedef name and the other declarations shall all
2573   //      refer to the same variable or enumerator, or all refer to functions
2574   //      and function templates; in this case the class name or enumeration
2575   //      name is hidden (3.3.10).
2576 
2577   // C++11 [namespace.udecl]p14:
2578   //   If a function declaration in namespace scope or block scope has the
2579   //   same name and the same parameter-type-list as a function introduced
2580   //   by a using-declaration, and the declarations do not declare the same
2581   //   function, the program is ill-formed.
2582 
2583   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2584   if (Old &&
2585       !Old->getDeclContext()->getRedeclContext()->Equals(
2586           New->getDeclContext()->getRedeclContext()) &&
2587       !(isExternC(Old) && isExternC(New)))
2588     Old = nullptr;
2589 
2590   if (!Old) {
2591     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2592     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2593     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2594     return true;
2595   }
2596   return false;
2597 }
2598 
2599 /// MergeFunctionDecl - We just parsed a function 'New' from
2600 /// declarator D which has the same name and scope as a previous
2601 /// declaration 'Old'.  Figure out how to resolve this situation,
2602 /// merging decls or emitting diagnostics as appropriate.
2603 ///
2604 /// In C++, New and Old must be declarations that are not
2605 /// overloaded. Use IsOverload to determine whether New and Old are
2606 /// overloaded, and to select the Old declaration that New should be
2607 /// merged with.
2608 ///
2609 /// Returns true if there was an error, false otherwise.
2610 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2611                              Scope *S, bool MergeTypeWithOld) {
2612   // Verify the old decl was also a function.
2613   FunctionDecl *Old = OldD->getAsFunction();
2614   if (!Old) {
2615     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2616       if (New->getFriendObjectKind()) {
2617         Diag(New->getLocation(), diag::err_using_decl_friend);
2618         Diag(Shadow->getTargetDecl()->getLocation(),
2619              diag::note_using_decl_target);
2620         Diag(Shadow->getUsingDecl()->getLocation(),
2621              diag::note_using_decl) << 0;
2622         return true;
2623       }
2624 
2625       // Check whether the two declarations might declare the same function.
2626       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2627         return true;
2628       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2629     } else {
2630       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2631         << New->getDeclName();
2632       Diag(OldD->getLocation(), diag::note_previous_definition);
2633       return true;
2634     }
2635   }
2636 
2637   // If the old declaration is invalid, just give up here.
2638   if (Old->isInvalidDecl())
2639     return true;
2640 
2641   diag::kind PrevDiag;
2642   SourceLocation OldLocation;
2643   std::tie(PrevDiag, OldLocation) =
2644       getNoteDiagForInvalidRedeclaration(Old, New);
2645 
2646   // Don't complain about this if we're in GNU89 mode and the old function
2647   // is an extern inline function.
2648   // Don't complain about specializations. They are not supposed to have
2649   // storage classes.
2650   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2651       New->getStorageClass() == SC_Static &&
2652       Old->hasExternalFormalLinkage() &&
2653       !New->getTemplateSpecializationInfo() &&
2654       !canRedefineFunction(Old, getLangOpts())) {
2655     if (getLangOpts().MicrosoftExt) {
2656       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2657       Diag(OldLocation, PrevDiag);
2658     } else {
2659       Diag(New->getLocation(), diag::err_static_non_static) << New;
2660       Diag(OldLocation, PrevDiag);
2661       return true;
2662     }
2663   }
2664 
2665 
2666   // If a function is first declared with a calling convention, but is later
2667   // declared or defined without one, all following decls assume the calling
2668   // convention of the first.
2669   //
2670   // It's OK if a function is first declared without a calling convention,
2671   // but is later declared or defined with the default calling convention.
2672   //
2673   // To test if either decl has an explicit calling convention, we look for
2674   // AttributedType sugar nodes on the type as written.  If they are missing or
2675   // were canonicalized away, we assume the calling convention was implicit.
2676   //
2677   // Note also that we DO NOT return at this point, because we still have
2678   // other tests to run.
2679   QualType OldQType = Context.getCanonicalType(Old->getType());
2680   QualType NewQType = Context.getCanonicalType(New->getType());
2681   const FunctionType *OldType = cast<FunctionType>(OldQType);
2682   const FunctionType *NewType = cast<FunctionType>(NewQType);
2683   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2684   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2685   bool RequiresAdjustment = false;
2686 
2687   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2688     FunctionDecl *First = Old->getFirstDecl();
2689     const FunctionType *FT =
2690         First->getType().getCanonicalType()->castAs<FunctionType>();
2691     FunctionType::ExtInfo FI = FT->getExtInfo();
2692     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2693     if (!NewCCExplicit) {
2694       // Inherit the CC from the previous declaration if it was specified
2695       // there but not here.
2696       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2697       RequiresAdjustment = true;
2698     } else {
2699       // Calling conventions aren't compatible, so complain.
2700       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2701       Diag(New->getLocation(), diag::err_cconv_change)
2702         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2703         << !FirstCCExplicit
2704         << (!FirstCCExplicit ? "" :
2705             FunctionType::getNameForCallConv(FI.getCC()));
2706 
2707       // Put the note on the first decl, since it is the one that matters.
2708       Diag(First->getLocation(), diag::note_previous_declaration);
2709       return true;
2710     }
2711   }
2712 
2713   // FIXME: diagnose the other way around?
2714   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2715     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2716     RequiresAdjustment = true;
2717   }
2718 
2719   // Merge regparm attribute.
2720   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2721       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2722     if (NewTypeInfo.getHasRegParm()) {
2723       Diag(New->getLocation(), diag::err_regparm_mismatch)
2724         << NewType->getRegParmType()
2725         << OldType->getRegParmType();
2726       Diag(OldLocation, diag::note_previous_declaration);
2727       return true;
2728     }
2729 
2730     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2731     RequiresAdjustment = true;
2732   }
2733 
2734   // Merge ns_returns_retained attribute.
2735   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2736     if (NewTypeInfo.getProducesResult()) {
2737       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2738       Diag(OldLocation, diag::note_previous_declaration);
2739       return true;
2740     }
2741 
2742     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2743     RequiresAdjustment = true;
2744   }
2745 
2746   if (RequiresAdjustment) {
2747     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2748     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2749     New->setType(QualType(AdjustedType, 0));
2750     NewQType = Context.getCanonicalType(New->getType());
2751     NewType = cast<FunctionType>(NewQType);
2752   }
2753 
2754   // If this redeclaration makes the function inline, we may need to add it to
2755   // UndefinedButUsed.
2756   if (!Old->isInlined() && New->isInlined() &&
2757       !New->hasAttr<GNUInlineAttr>() &&
2758       !getLangOpts().GNUInline &&
2759       Old->isUsed(false) &&
2760       !Old->isDefined() && !New->isThisDeclarationADefinition())
2761     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2762                                            SourceLocation()));
2763 
2764   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2765   // about it.
2766   if (New->hasAttr<GNUInlineAttr>() &&
2767       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2768     UndefinedButUsed.erase(Old->getCanonicalDecl());
2769   }
2770 
2771   if (getLangOpts().CPlusPlus) {
2772     // (C++98 13.1p2):
2773     //   Certain function declarations cannot be overloaded:
2774     //     -- Function declarations that differ only in the return type
2775     //        cannot be overloaded.
2776 
2777     // Go back to the type source info to compare the declared return types,
2778     // per C++1y [dcl.type.auto]p13:
2779     //   Redeclarations or specializations of a function or function template
2780     //   with a declared return type that uses a placeholder type shall also
2781     //   use that placeholder, not a deduced type.
2782     QualType OldDeclaredReturnType =
2783         (Old->getTypeSourceInfo()
2784              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2785              : OldType)->getReturnType();
2786     QualType NewDeclaredReturnType =
2787         (New->getTypeSourceInfo()
2788              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2789              : NewType)->getReturnType();
2790     QualType ResQT;
2791     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2792         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2793           New->isLocalExternDecl())) {
2794       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2795           OldDeclaredReturnType->isObjCObjectPointerType())
2796         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2797       if (ResQT.isNull()) {
2798         if (New->isCXXClassMember() && New->isOutOfLine())
2799           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2800               << New << New->getReturnTypeSourceRange();
2801         else
2802           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2803               << New->getReturnTypeSourceRange();
2804         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2805                                     << Old->getReturnTypeSourceRange();
2806         return true;
2807       }
2808       else
2809         NewQType = ResQT;
2810     }
2811 
2812     QualType OldReturnType = OldType->getReturnType();
2813     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2814     if (OldReturnType != NewReturnType) {
2815       // If this function has a deduced return type and has already been
2816       // defined, copy the deduced value from the old declaration.
2817       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2818       if (OldAT && OldAT->isDeduced()) {
2819         New->setType(
2820             SubstAutoType(New->getType(),
2821                           OldAT->isDependentType() ? Context.DependentTy
2822                                                    : OldAT->getDeducedType()));
2823         NewQType = Context.getCanonicalType(
2824             SubstAutoType(NewQType,
2825                           OldAT->isDependentType() ? Context.DependentTy
2826                                                    : OldAT->getDeducedType()));
2827       }
2828     }
2829 
2830     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2831     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2832     if (OldMethod && NewMethod) {
2833       // Preserve triviality.
2834       NewMethod->setTrivial(OldMethod->isTrivial());
2835 
2836       // MSVC allows explicit template specialization at class scope:
2837       // 2 CXXMethodDecls referring to the same function will be injected.
2838       // We don't want a redeclaration error.
2839       bool IsClassScopeExplicitSpecialization =
2840                               OldMethod->isFunctionTemplateSpecialization() &&
2841                               NewMethod->isFunctionTemplateSpecialization();
2842       bool isFriend = NewMethod->getFriendObjectKind();
2843 
2844       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2845           !IsClassScopeExplicitSpecialization) {
2846         //    -- Member function declarations with the same name and the
2847         //       same parameter types cannot be overloaded if any of them
2848         //       is a static member function declaration.
2849         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2850           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2851           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2852           return true;
2853         }
2854 
2855         // C++ [class.mem]p1:
2856         //   [...] A member shall not be declared twice in the
2857         //   member-specification, except that a nested class or member
2858         //   class template can be declared and then later defined.
2859         if (ActiveTemplateInstantiations.empty()) {
2860           unsigned NewDiag;
2861           if (isa<CXXConstructorDecl>(OldMethod))
2862             NewDiag = diag::err_constructor_redeclared;
2863           else if (isa<CXXDestructorDecl>(NewMethod))
2864             NewDiag = diag::err_destructor_redeclared;
2865           else if (isa<CXXConversionDecl>(NewMethod))
2866             NewDiag = diag::err_conv_function_redeclared;
2867           else
2868             NewDiag = diag::err_member_redeclared;
2869 
2870           Diag(New->getLocation(), NewDiag);
2871         } else {
2872           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2873             << New << New->getType();
2874         }
2875         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2876         return true;
2877 
2878       // Complain if this is an explicit declaration of a special
2879       // member that was initially declared implicitly.
2880       //
2881       // As an exception, it's okay to befriend such methods in order
2882       // to permit the implicit constructor/destructor/operator calls.
2883       } else if (OldMethod->isImplicit()) {
2884         if (isFriend) {
2885           NewMethod->setImplicit();
2886         } else {
2887           Diag(NewMethod->getLocation(),
2888                diag::err_definition_of_implicitly_declared_member)
2889             << New << getSpecialMember(OldMethod);
2890           return true;
2891         }
2892       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2893         Diag(NewMethod->getLocation(),
2894              diag::err_definition_of_explicitly_defaulted_member)
2895           << getSpecialMember(OldMethod);
2896         return true;
2897       }
2898     }
2899 
2900     // C++11 [dcl.attr.noreturn]p1:
2901     //   The first declaration of a function shall specify the noreturn
2902     //   attribute if any declaration of that function specifies the noreturn
2903     //   attribute.
2904     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2905     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2906       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2907       Diag(Old->getFirstDecl()->getLocation(),
2908            diag::note_noreturn_missing_first_decl);
2909     }
2910 
2911     // C++11 [dcl.attr.depend]p2:
2912     //   The first declaration of a function shall specify the
2913     //   carries_dependency attribute for its declarator-id if any declaration
2914     //   of the function specifies the carries_dependency attribute.
2915     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2916     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2917       Diag(CDA->getLocation(),
2918            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2919       Diag(Old->getFirstDecl()->getLocation(),
2920            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2921     }
2922 
2923     // (C++98 8.3.5p3):
2924     //   All declarations for a function shall agree exactly in both the
2925     //   return type and the parameter-type-list.
2926     // We also want to respect all the extended bits except noreturn.
2927 
2928     // noreturn should now match unless the old type info didn't have it.
2929     QualType OldQTypeForComparison = OldQType;
2930     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2931       assert(OldQType == QualType(OldType, 0));
2932       const FunctionType *OldTypeForComparison
2933         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2934       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2935       assert(OldQTypeForComparison.isCanonical());
2936     }
2937 
2938     if (haveIncompatibleLanguageLinkages(Old, New)) {
2939       // As a special case, retain the language linkage from previous
2940       // declarations of a friend function as an extension.
2941       //
2942       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2943       // and is useful because there's otherwise no way to specify language
2944       // linkage within class scope.
2945       //
2946       // Check cautiously as the friend object kind isn't yet complete.
2947       if (New->getFriendObjectKind() != Decl::FOK_None) {
2948         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2949         Diag(OldLocation, PrevDiag);
2950       } else {
2951         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2952         Diag(OldLocation, PrevDiag);
2953         return true;
2954       }
2955     }
2956 
2957     if (OldQTypeForComparison == NewQType)
2958       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2959 
2960     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2961         New->isLocalExternDecl()) {
2962       // It's OK if we couldn't merge types for a local function declaraton
2963       // if either the old or new type is dependent. We'll merge the types
2964       // when we instantiate the function.
2965       return false;
2966     }
2967 
2968     // Fall through for conflicting redeclarations and redefinitions.
2969   }
2970 
2971   // C: Function types need to be compatible, not identical. This handles
2972   // duplicate function decls like "void f(int); void f(enum X);" properly.
2973   if (!getLangOpts().CPlusPlus &&
2974       Context.typesAreCompatible(OldQType, NewQType)) {
2975     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2976     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2977     const FunctionProtoType *OldProto = nullptr;
2978     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
2979         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2980       // The old declaration provided a function prototype, but the
2981       // new declaration does not. Merge in the prototype.
2982       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2983       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
2984       NewQType =
2985           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2986                                   OldProto->getExtProtoInfo());
2987       New->setType(NewQType);
2988       New->setHasInheritedPrototype();
2989 
2990       // Synthesize parameters with the same types.
2991       SmallVector<ParmVarDecl*, 16> Params;
2992       for (const auto &ParamType : OldProto->param_types()) {
2993         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
2994                                                  SourceLocation(), nullptr,
2995                                                  ParamType, /*TInfo=*/nullptr,
2996                                                  SC_None, nullptr);
2997         Param->setScopeInfo(0, Params.size());
2998         Param->setImplicit();
2999         Params.push_back(Param);
3000       }
3001 
3002       New->setParams(Params);
3003     }
3004 
3005     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3006   }
3007 
3008   // GNU C permits a K&R definition to follow a prototype declaration
3009   // if the declared types of the parameters in the K&R definition
3010   // match the types in the prototype declaration, even when the
3011   // promoted types of the parameters from the K&R definition differ
3012   // from the types in the prototype. GCC then keeps the types from
3013   // the prototype.
3014   //
3015   // If a variadic prototype is followed by a non-variadic K&R definition,
3016   // the K&R definition becomes variadic.  This is sort of an edge case, but
3017   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3018   // C99 6.9.1p8.
3019   if (!getLangOpts().CPlusPlus &&
3020       Old->hasPrototype() && !New->hasPrototype() &&
3021       New->getType()->getAs<FunctionProtoType>() &&
3022       Old->getNumParams() == New->getNumParams()) {
3023     SmallVector<QualType, 16> ArgTypes;
3024     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3025     const FunctionProtoType *OldProto
3026       = Old->getType()->getAs<FunctionProtoType>();
3027     const FunctionProtoType *NewProto
3028       = New->getType()->getAs<FunctionProtoType>();
3029 
3030     // Determine whether this is the GNU C extension.
3031     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3032                                                NewProto->getReturnType());
3033     bool LooseCompatible = !MergedReturn.isNull();
3034     for (unsigned Idx = 0, End = Old->getNumParams();
3035          LooseCompatible && Idx != End; ++Idx) {
3036       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3037       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3038       if (Context.typesAreCompatible(OldParm->getType(),
3039                                      NewProto->getParamType(Idx))) {
3040         ArgTypes.push_back(NewParm->getType());
3041       } else if (Context.typesAreCompatible(OldParm->getType(),
3042                                             NewParm->getType(),
3043                                             /*CompareUnqualified=*/true)) {
3044         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3045                                            NewProto->getParamType(Idx) };
3046         Warnings.push_back(Warn);
3047         ArgTypes.push_back(NewParm->getType());
3048       } else
3049         LooseCompatible = false;
3050     }
3051 
3052     if (LooseCompatible) {
3053       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3054         Diag(Warnings[Warn].NewParm->getLocation(),
3055              diag::ext_param_promoted_not_compatible_with_prototype)
3056           << Warnings[Warn].PromotedType
3057           << Warnings[Warn].OldParm->getType();
3058         if (Warnings[Warn].OldParm->getLocation().isValid())
3059           Diag(Warnings[Warn].OldParm->getLocation(),
3060                diag::note_previous_declaration);
3061       }
3062 
3063       if (MergeTypeWithOld)
3064         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3065                                              OldProto->getExtProtoInfo()));
3066       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3067     }
3068 
3069     // Fall through to diagnose conflicting types.
3070   }
3071 
3072   // A function that has already been declared has been redeclared or
3073   // defined with a different type; show an appropriate diagnostic.
3074 
3075   // If the previous declaration was an implicitly-generated builtin
3076   // declaration, then at the very least we should use a specialized note.
3077   unsigned BuiltinID;
3078   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3079     // If it's actually a library-defined builtin function like 'malloc'
3080     // or 'printf', just warn about the incompatible redeclaration.
3081     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3082       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3083       Diag(OldLocation, diag::note_previous_builtin_declaration)
3084         << Old << Old->getType();
3085 
3086       // If this is a global redeclaration, just forget hereafter
3087       // about the "builtin-ness" of the function.
3088       //
3089       // Doing this for local extern declarations is problematic.  If
3090       // the builtin declaration remains visible, a second invalid
3091       // local declaration will produce a hard error; if it doesn't
3092       // remain visible, a single bogus local redeclaration (which is
3093       // actually only a warning) could break all the downstream code.
3094       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3095         New->getIdentifier()->revertBuiltin();
3096 
3097       return false;
3098     }
3099 
3100     PrevDiag = diag::note_previous_builtin_declaration;
3101   }
3102 
3103   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3104   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3105   return true;
3106 }
3107 
3108 /// \brief Completes the merge of two function declarations that are
3109 /// known to be compatible.
3110 ///
3111 /// This routine handles the merging of attributes and other
3112 /// properties of function declarations from the old declaration to
3113 /// the new declaration, once we know that New is in fact a
3114 /// redeclaration of Old.
3115 ///
3116 /// \returns false
3117 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3118                                         Scope *S, bool MergeTypeWithOld) {
3119   // Merge the attributes
3120   mergeDeclAttributes(New, Old);
3121 
3122   // Merge "pure" flag.
3123   if (Old->isPure())
3124     New->setPure();
3125 
3126   // Merge "used" flag.
3127   if (Old->getMostRecentDecl()->isUsed(false))
3128     New->setIsUsed();
3129 
3130   // Merge attributes from the parameters.  These can mismatch with K&R
3131   // declarations.
3132   if (New->getNumParams() == Old->getNumParams())
3133       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3134         ParmVarDecl *NewParam = New->getParamDecl(i);
3135         ParmVarDecl *OldParam = Old->getParamDecl(i);
3136         mergeParamDeclAttributes(NewParam, OldParam, *this);
3137         mergeParamDeclTypes(NewParam, OldParam, *this);
3138       }
3139 
3140   if (getLangOpts().CPlusPlus)
3141     return MergeCXXFunctionDecl(New, Old, S);
3142 
3143   // Merge the function types so the we get the composite types for the return
3144   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3145   // was visible.
3146   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3147   if (!Merged.isNull() && MergeTypeWithOld)
3148     New->setType(Merged);
3149 
3150   return false;
3151 }
3152 
3153 
3154 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3155                                 ObjCMethodDecl *oldMethod) {
3156 
3157   // Merge the attributes, including deprecated/unavailable
3158   AvailabilityMergeKind MergeKind =
3159     isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3160                                                    : AMK_Override;
3161   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3162 
3163   // Merge attributes from the parameters.
3164   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3165                                        oe = oldMethod->param_end();
3166   for (ObjCMethodDecl::param_iterator
3167          ni = newMethod->param_begin(), ne = newMethod->param_end();
3168        ni != ne && oi != oe; ++ni, ++oi)
3169     mergeParamDeclAttributes(*ni, *oi, *this);
3170 
3171   CheckObjCMethodOverride(newMethod, oldMethod);
3172 }
3173 
3174 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3175 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3176 /// emitting diagnostics as appropriate.
3177 ///
3178 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3179 /// to here in AddInitializerToDecl. We can't check them before the initializer
3180 /// is attached.
3181 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3182                              bool MergeTypeWithOld) {
3183   if (New->isInvalidDecl() || Old->isInvalidDecl())
3184     return;
3185 
3186   QualType MergedT;
3187   if (getLangOpts().CPlusPlus) {
3188     if (New->getType()->isUndeducedType()) {
3189       // We don't know what the new type is until the initializer is attached.
3190       return;
3191     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3192       // These could still be something that needs exception specs checked.
3193       return MergeVarDeclExceptionSpecs(New, Old);
3194     }
3195     // C++ [basic.link]p10:
3196     //   [...] the types specified by all declarations referring to a given
3197     //   object or function shall be identical, except that declarations for an
3198     //   array object can specify array types that differ by the presence or
3199     //   absence of a major array bound (8.3.4).
3200     else if (Old->getType()->isIncompleteArrayType() &&
3201              New->getType()->isArrayType()) {
3202       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3203       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3204       if (Context.hasSameType(OldArray->getElementType(),
3205                               NewArray->getElementType()))
3206         MergedT = New->getType();
3207     } else if (Old->getType()->isArrayType() &&
3208                New->getType()->isIncompleteArrayType()) {
3209       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3210       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3211       if (Context.hasSameType(OldArray->getElementType(),
3212                               NewArray->getElementType()))
3213         MergedT = Old->getType();
3214     } else if (New->getType()->isObjCObjectPointerType() &&
3215                Old->getType()->isObjCObjectPointerType()) {
3216       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3217                                               Old->getType());
3218     }
3219   } else {
3220     // C 6.2.7p2:
3221     //   All declarations that refer to the same object or function shall have
3222     //   compatible type.
3223     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3224   }
3225   if (MergedT.isNull()) {
3226     // It's OK if we couldn't merge types if either type is dependent, for a
3227     // block-scope variable. In other cases (static data members of class
3228     // templates, variable templates, ...), we require the types to be
3229     // equivalent.
3230     // FIXME: The C++ standard doesn't say anything about this.
3231     if ((New->getType()->isDependentType() ||
3232          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3233       // If the old type was dependent, we can't merge with it, so the new type
3234       // becomes dependent for now. We'll reproduce the original type when we
3235       // instantiate the TypeSourceInfo for the variable.
3236       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3237         New->setType(Context.DependentTy);
3238       return;
3239     }
3240 
3241     // FIXME: Even if this merging succeeds, some other non-visible declaration
3242     // of this variable might have an incompatible type. For instance:
3243     //
3244     //   extern int arr[];
3245     //   void f() { extern int arr[2]; }
3246     //   void g() { extern int arr[3]; }
3247     //
3248     // Neither C nor C++ requires a diagnostic for this, but we should still try
3249     // to diagnose it.
3250     Diag(New->getLocation(), New->isThisDeclarationADefinition()
3251                                  ? diag::err_redefinition_different_type
3252                                  : diag::err_redeclaration_different_type)
3253         << New->getDeclName() << New->getType() << Old->getType();
3254 
3255     diag::kind PrevDiag;
3256     SourceLocation OldLocation;
3257     std::tie(PrevDiag, OldLocation) =
3258         getNoteDiagForInvalidRedeclaration(Old, New);
3259     Diag(OldLocation, PrevDiag);
3260     return New->setInvalidDecl();
3261   }
3262 
3263   // Don't actually update the type on the new declaration if the old
3264   // declaration was an extern declaration in a different scope.
3265   if (MergeTypeWithOld)
3266     New->setType(MergedT);
3267 }
3268 
3269 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3270                                   LookupResult &Previous) {
3271   // C11 6.2.7p4:
3272   //   For an identifier with internal or external linkage declared
3273   //   in a scope in which a prior declaration of that identifier is
3274   //   visible, if the prior declaration specifies internal or
3275   //   external linkage, the type of the identifier at the later
3276   //   declaration becomes the composite type.
3277   //
3278   // If the variable isn't visible, we do not merge with its type.
3279   if (Previous.isShadowed())
3280     return false;
3281 
3282   if (S.getLangOpts().CPlusPlus) {
3283     // C++11 [dcl.array]p3:
3284     //   If there is a preceding declaration of the entity in the same
3285     //   scope in which the bound was specified, an omitted array bound
3286     //   is taken to be the same as in that earlier declaration.
3287     return NewVD->isPreviousDeclInSameBlockScope() ||
3288            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3289             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3290   } else {
3291     // If the old declaration was function-local, don't merge with its
3292     // type unless we're in the same function.
3293     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3294            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3295   }
3296 }
3297 
3298 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3299 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3300 /// situation, merging decls or emitting diagnostics as appropriate.
3301 ///
3302 /// Tentative definition rules (C99 6.9.2p2) are checked by
3303 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3304 /// definitions here, since the initializer hasn't been attached.
3305 ///
3306 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3307   // If the new decl is already invalid, don't do any other checking.
3308   if (New->isInvalidDecl())
3309     return;
3310 
3311   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3312 
3313   // Verify the old decl was also a variable or variable template.
3314   VarDecl *Old = nullptr;
3315   VarTemplateDecl *OldTemplate = nullptr;
3316   if (Previous.isSingleResult()) {
3317     if (NewTemplate) {
3318       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3319       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3320 
3321       if (auto *Shadow =
3322               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3323         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3324           return New->setInvalidDecl();
3325     } else {
3326       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3327 
3328       if (auto *Shadow =
3329               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3330         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3331           return New->setInvalidDecl();
3332     }
3333   }
3334   if (!Old) {
3335     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3336       << New->getDeclName();
3337     Diag(Previous.getRepresentativeDecl()->getLocation(),
3338          diag::note_previous_definition);
3339     return New->setInvalidDecl();
3340   }
3341 
3342   if (!shouldLinkPossiblyHiddenDecl(Old, New))
3343     return;
3344 
3345   // Ensure the template parameters are compatible.
3346   if (NewTemplate &&
3347       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3348                                       OldTemplate->getTemplateParameters(),
3349                                       /*Complain=*/true, TPL_TemplateMatch))
3350     return;
3351 
3352   // C++ [class.mem]p1:
3353   //   A member shall not be declared twice in the member-specification [...]
3354   //
3355   // Here, we need only consider static data members.
3356   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3357     Diag(New->getLocation(), diag::err_duplicate_member)
3358       << New->getIdentifier();
3359     Diag(Old->getLocation(), diag::note_previous_declaration);
3360     New->setInvalidDecl();
3361   }
3362 
3363   mergeDeclAttributes(New, Old);
3364   // Warn if an already-declared variable is made a weak_import in a subsequent
3365   // declaration
3366   if (New->hasAttr<WeakImportAttr>() &&
3367       Old->getStorageClass() == SC_None &&
3368       !Old->hasAttr<WeakImportAttr>()) {
3369     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3370     Diag(Old->getLocation(), diag::note_previous_definition);
3371     // Remove weak_import attribute on new declaration.
3372     New->dropAttr<WeakImportAttr>();
3373   }
3374 
3375   // Merge the types.
3376   VarDecl *MostRecent = Old->getMostRecentDecl();
3377   if (MostRecent != Old) {
3378     MergeVarDeclTypes(New, MostRecent,
3379                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3380     if (New->isInvalidDecl())
3381       return;
3382   }
3383 
3384   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3385   if (New->isInvalidDecl())
3386     return;
3387 
3388   diag::kind PrevDiag;
3389   SourceLocation OldLocation;
3390   std::tie(PrevDiag, OldLocation) =
3391       getNoteDiagForInvalidRedeclaration(Old, New);
3392 
3393   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3394   if (New->getStorageClass() == SC_Static &&
3395       !New->isStaticDataMember() &&
3396       Old->hasExternalFormalLinkage()) {
3397     if (getLangOpts().MicrosoftExt) {
3398       Diag(New->getLocation(), diag::ext_static_non_static)
3399           << New->getDeclName();
3400       Diag(OldLocation, PrevDiag);
3401     } else {
3402       Diag(New->getLocation(), diag::err_static_non_static)
3403           << New->getDeclName();
3404       Diag(OldLocation, PrevDiag);
3405       return New->setInvalidDecl();
3406     }
3407   }
3408   // C99 6.2.2p4:
3409   //   For an identifier declared with the storage-class specifier
3410   //   extern in a scope in which a prior declaration of that
3411   //   identifier is visible,23) if the prior declaration specifies
3412   //   internal or external linkage, the linkage of the identifier at
3413   //   the later declaration is the same as the linkage specified at
3414   //   the prior declaration. If no prior declaration is visible, or
3415   //   if the prior declaration specifies no linkage, then the
3416   //   identifier has external linkage.
3417   if (New->hasExternalStorage() && Old->hasLinkage())
3418     /* Okay */;
3419   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3420            !New->isStaticDataMember() &&
3421            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3422     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3423     Diag(OldLocation, PrevDiag);
3424     return New->setInvalidDecl();
3425   }
3426 
3427   // Check if extern is followed by non-extern and vice-versa.
3428   if (New->hasExternalStorage() &&
3429       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3430     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3431     Diag(OldLocation, PrevDiag);
3432     return New->setInvalidDecl();
3433   }
3434   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3435       !New->hasExternalStorage()) {
3436     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3437     Diag(OldLocation, PrevDiag);
3438     return New->setInvalidDecl();
3439   }
3440 
3441   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3442 
3443   // FIXME: The test for external storage here seems wrong? We still
3444   // need to check for mismatches.
3445   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3446       // Don't complain about out-of-line definitions of static members.
3447       !(Old->getLexicalDeclContext()->isRecord() &&
3448         !New->getLexicalDeclContext()->isRecord())) {
3449     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3450     Diag(OldLocation, PrevDiag);
3451     return New->setInvalidDecl();
3452   }
3453 
3454   if (New->getTLSKind() != Old->getTLSKind()) {
3455     if (!Old->getTLSKind()) {
3456       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3457       Diag(OldLocation, PrevDiag);
3458     } else if (!New->getTLSKind()) {
3459       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3460       Diag(OldLocation, PrevDiag);
3461     } else {
3462       // Do not allow redeclaration to change the variable between requiring
3463       // static and dynamic initialization.
3464       // FIXME: GCC allows this, but uses the TLS keyword on the first
3465       // declaration to determine the kind. Do we need to be compatible here?
3466       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3467         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3468       Diag(OldLocation, PrevDiag);
3469     }
3470   }
3471 
3472   // C++ doesn't have tentative definitions, so go right ahead and check here.
3473   VarDecl *Def;
3474   if (getLangOpts().CPlusPlus &&
3475       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3476       (Def = Old->getDefinition())) {
3477     NamedDecl *Hidden = nullptr;
3478     if (!hasVisibleDefinition(Def, &Hidden) &&
3479         (New->getFormalLinkage() == InternalLinkage ||
3480          New->getDescribedVarTemplate() ||
3481          New->getNumTemplateParameterLists() ||
3482          New->getDeclContext()->isDependentContext())) {
3483       // The previous definition is hidden, and multiple definitions are
3484       // permitted (in separate TUs). Form another definition of it.
3485     } else {
3486       Diag(New->getLocation(), diag::err_redefinition) << New;
3487       Diag(Def->getLocation(), diag::note_previous_definition);
3488       New->setInvalidDecl();
3489       return;
3490     }
3491   }
3492 
3493   if (haveIncompatibleLanguageLinkages(Old, New)) {
3494     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3495     Diag(OldLocation, PrevDiag);
3496     New->setInvalidDecl();
3497     return;
3498   }
3499 
3500   // Merge "used" flag.
3501   if (Old->getMostRecentDecl()->isUsed(false))
3502     New->setIsUsed();
3503 
3504   // Keep a chain of previous declarations.
3505   New->setPreviousDecl(Old);
3506   if (NewTemplate)
3507     NewTemplate->setPreviousDecl(OldTemplate);
3508 
3509   // Inherit access appropriately.
3510   New->setAccess(Old->getAccess());
3511   if (NewTemplate)
3512     NewTemplate->setAccess(New->getAccess());
3513 }
3514 
3515 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3516 /// no declarator (e.g. "struct foo;") is parsed.
3517 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3518                                        DeclSpec &DS) {
3519   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3520 }
3521 
3522 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3523 // disambiguate entities defined in different scopes.
3524 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3525 // compatibility.
3526 // We will pick our mangling number depending on which version of MSVC is being
3527 // targeted.
3528 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3529   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3530              ? S->getMSCurManglingNumber()
3531              : S->getMSLastManglingNumber();
3532 }
3533 
3534 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3535   if (!Context.getLangOpts().CPlusPlus)
3536     return;
3537 
3538   if (isa<CXXRecordDecl>(Tag->getParent())) {
3539     // If this tag is the direct child of a class, number it if
3540     // it is anonymous.
3541     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3542       return;
3543     MangleNumberingContext &MCtx =
3544         Context.getManglingNumberContext(Tag->getParent());
3545     Context.setManglingNumber(
3546         Tag, MCtx.getManglingNumber(
3547                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3548     return;
3549   }
3550 
3551   // If this tag isn't a direct child of a class, number it if it is local.
3552   Decl *ManglingContextDecl;
3553   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3554           Tag->getDeclContext(), ManglingContextDecl)) {
3555     Context.setManglingNumber(
3556         Tag, MCtx->getManglingNumber(
3557                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3558   }
3559 }
3560 
3561 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3562                                         TypedefNameDecl *NewTD) {
3563   // Do nothing if the tag is not anonymous or already has an
3564   // associated typedef (from an earlier typedef in this decl group).
3565   if (TagFromDeclSpec->getIdentifier())
3566     return;
3567   if (TagFromDeclSpec->getTypedefNameForAnonDecl())
3568     return;
3569 
3570   // A well-formed anonymous tag must always be a TUK_Definition.
3571   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3572 
3573   // The type must match the tag exactly;  no qualifiers allowed.
3574   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3575                            Context.getTagDeclType(TagFromDeclSpec)))
3576     return;
3577 
3578   // If we've already computed linkage for the anonymous tag, then
3579   // adding a typedef name for the anonymous decl can change that
3580   // linkage, which might be a serious problem.  Diagnose this as
3581   // unsupported and ignore the typedef name.  TODO: we should
3582   // pursue this as a language defect and establish a formal rule
3583   // for how to handle it.
3584   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3585     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3586 
3587     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3588     tagLoc = getLocForEndOfToken(tagLoc);
3589 
3590     llvm::SmallString<40> textToInsert;
3591     textToInsert += ' ';
3592     textToInsert += NewTD->getIdentifier()->getName();
3593     Diag(tagLoc, diag::note_typedef_changes_linkage)
3594         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3595     return;
3596   }
3597 
3598   // Otherwise, set this is the anon-decl typedef for the tag.
3599   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3600 }
3601 
3602 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3603   switch (T) {
3604   case DeclSpec::TST_class:
3605     return 0;
3606   case DeclSpec::TST_struct:
3607     return 1;
3608   case DeclSpec::TST_interface:
3609     return 2;
3610   case DeclSpec::TST_union:
3611     return 3;
3612   case DeclSpec::TST_enum:
3613     return 4;
3614   default:
3615     llvm_unreachable("unexpected type specifier");
3616   }
3617 }
3618 
3619 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3620 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3621 /// parameters to cope with template friend declarations.
3622 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3623                                        DeclSpec &DS,
3624                                        MultiTemplateParamsArg TemplateParams,
3625                                        bool IsExplicitInstantiation) {
3626   Decl *TagD = nullptr;
3627   TagDecl *Tag = nullptr;
3628   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3629       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3630       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3631       DS.getTypeSpecType() == DeclSpec::TST_union ||
3632       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3633     TagD = DS.getRepAsDecl();
3634 
3635     if (!TagD) // We probably had an error
3636       return nullptr;
3637 
3638     // Note that the above type specs guarantee that the
3639     // type rep is a Decl, whereas in many of the others
3640     // it's a Type.
3641     if (isa<TagDecl>(TagD))
3642       Tag = cast<TagDecl>(TagD);
3643     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3644       Tag = CTD->getTemplatedDecl();
3645   }
3646 
3647   if (Tag) {
3648     handleTagNumbering(Tag, S);
3649     Tag->setFreeStanding();
3650     if (Tag->isInvalidDecl())
3651       return Tag;
3652   }
3653 
3654   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3655     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3656     // or incomplete types shall not be restrict-qualified."
3657     if (TypeQuals & DeclSpec::TQ_restrict)
3658       Diag(DS.getRestrictSpecLoc(),
3659            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3660            << DS.getSourceRange();
3661   }
3662 
3663   if (DS.isConstexprSpecified()) {
3664     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3665     // and definitions of functions and variables.
3666     if (Tag)
3667       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3668           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3669     else
3670       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3671     // Don't emit warnings after this error.
3672     return TagD;
3673   }
3674 
3675   if (DS.isConceptSpecified()) {
3676     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3677     // either a function concept and its definition or a variable concept and
3678     // its initializer.
3679     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3680     return TagD;
3681   }
3682 
3683   DiagnoseFunctionSpecifiers(DS);
3684 
3685   if (DS.isFriendSpecified()) {
3686     // If we're dealing with a decl but not a TagDecl, assume that
3687     // whatever routines created it handled the friendship aspect.
3688     if (TagD && !Tag)
3689       return nullptr;
3690     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3691   }
3692 
3693   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3694   bool IsExplicitSpecialization =
3695     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3696   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3697       !IsExplicitInstantiation && !IsExplicitSpecialization) {
3698     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3699     // nested-name-specifier unless it is an explicit instantiation
3700     // or an explicit specialization.
3701     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3702     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3703         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3704     return nullptr;
3705   }
3706 
3707   // Track whether this decl-specifier declares anything.
3708   bool DeclaresAnything = true;
3709 
3710   // Handle anonymous struct definitions.
3711   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3712     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3713         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3714       if (getLangOpts().CPlusPlus ||
3715           Record->getDeclContext()->isRecord())
3716         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3717                                            Context.getPrintingPolicy());
3718 
3719       DeclaresAnything = false;
3720     }
3721   }
3722 
3723   // C11 6.7.2.1p2:
3724   //   A struct-declaration that does not declare an anonymous structure or
3725   //   anonymous union shall contain a struct-declarator-list.
3726   //
3727   // This rule also existed in C89 and C99; the grammar for struct-declaration
3728   // did not permit a struct-declaration without a struct-declarator-list.
3729   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3730       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3731     // Check for Microsoft C extension: anonymous struct/union member.
3732     // Handle 2 kinds of anonymous struct/union:
3733     //   struct STRUCT;
3734     //   union UNION;
3735     // and
3736     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3737     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3738     if ((Tag && Tag->getDeclName()) ||
3739         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3740       RecordDecl *Record = nullptr;
3741       if (Tag)
3742         Record = dyn_cast<RecordDecl>(Tag);
3743       else if (const RecordType *RT =
3744                    DS.getRepAsType().get()->getAsStructureType())
3745         Record = RT->getDecl();
3746       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3747         Record = UT->getDecl();
3748 
3749       if (Record && getLangOpts().MicrosoftExt) {
3750         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3751           << Record->isUnion() << DS.getSourceRange();
3752         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3753       }
3754 
3755       DeclaresAnything = false;
3756     }
3757   }
3758 
3759   // Skip all the checks below if we have a type error.
3760   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3761       (TagD && TagD->isInvalidDecl()))
3762     return TagD;
3763 
3764   if (getLangOpts().CPlusPlus &&
3765       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3766     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3767       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3768           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3769         DeclaresAnything = false;
3770 
3771   if (!DS.isMissingDeclaratorOk()) {
3772     // Customize diagnostic for a typedef missing a name.
3773     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3774       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3775         << DS.getSourceRange();
3776     else
3777       DeclaresAnything = false;
3778   }
3779 
3780   if (DS.isModulePrivateSpecified() &&
3781       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3782     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3783       << Tag->getTagKind()
3784       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3785 
3786   ActOnDocumentableDecl(TagD);
3787 
3788   // C 6.7/2:
3789   //   A declaration [...] shall declare at least a declarator [...], a tag,
3790   //   or the members of an enumeration.
3791   // C++ [dcl.dcl]p3:
3792   //   [If there are no declarators], and except for the declaration of an
3793   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3794   //   names into the program, or shall redeclare a name introduced by a
3795   //   previous declaration.
3796   if (!DeclaresAnything) {
3797     // In C, we allow this as a (popular) extension / bug. Don't bother
3798     // producing further diagnostics for redundant qualifiers after this.
3799     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3800     return TagD;
3801   }
3802 
3803   // C++ [dcl.stc]p1:
3804   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3805   //   init-declarator-list of the declaration shall not be empty.
3806   // C++ [dcl.fct.spec]p1:
3807   //   If a cv-qualifier appears in a decl-specifier-seq, the
3808   //   init-declarator-list of the declaration shall not be empty.
3809   //
3810   // Spurious qualifiers here appear to be valid in C.
3811   unsigned DiagID = diag::warn_standalone_specifier;
3812   if (getLangOpts().CPlusPlus)
3813     DiagID = diag::ext_standalone_specifier;
3814 
3815   // Note that a linkage-specification sets a storage class, but
3816   // 'extern "C" struct foo;' is actually valid and not theoretically
3817   // useless.
3818   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3819     if (SCS == DeclSpec::SCS_mutable)
3820       // Since mutable is not a viable storage class specifier in C, there is
3821       // no reason to treat it as an extension. Instead, diagnose as an error.
3822       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3823     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3824       Diag(DS.getStorageClassSpecLoc(), DiagID)
3825         << DeclSpec::getSpecifierName(SCS);
3826   }
3827 
3828   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3829     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3830       << DeclSpec::getSpecifierName(TSCS);
3831   if (DS.getTypeQualifiers()) {
3832     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3833       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3834     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3835       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3836     // Restrict is covered above.
3837     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3838       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3839   }
3840 
3841   // Warn about ignored type attributes, for example:
3842   // __attribute__((aligned)) struct A;
3843   // Attributes should be placed after tag to apply to type declaration.
3844   if (!DS.getAttributes().empty()) {
3845     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3846     if (TypeSpecType == DeclSpec::TST_class ||
3847         TypeSpecType == DeclSpec::TST_struct ||
3848         TypeSpecType == DeclSpec::TST_interface ||
3849         TypeSpecType == DeclSpec::TST_union ||
3850         TypeSpecType == DeclSpec::TST_enum) {
3851       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
3852            attrs = attrs->getNext())
3853         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3854             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
3855     }
3856   }
3857 
3858   return TagD;
3859 }
3860 
3861 /// We are trying to inject an anonymous member into the given scope;
3862 /// check if there's an existing declaration that can't be overloaded.
3863 ///
3864 /// \return true if this is a forbidden redeclaration
3865 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3866                                          Scope *S,
3867                                          DeclContext *Owner,
3868                                          DeclarationName Name,
3869                                          SourceLocation NameLoc,
3870                                          unsigned diagnostic) {
3871   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3872                  Sema::ForRedeclaration);
3873   if (!SemaRef.LookupName(R, S)) return false;
3874 
3875   if (R.getAsSingle<TagDecl>())
3876     return false;
3877 
3878   // Pick a representative declaration.
3879   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3880   assert(PrevDecl && "Expected a non-null Decl");
3881 
3882   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3883     return false;
3884 
3885   SemaRef.Diag(NameLoc, diagnostic) << Name;
3886   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3887 
3888   return true;
3889 }
3890 
3891 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3892 /// anonymous struct or union AnonRecord into the owning context Owner
3893 /// and scope S. This routine will be invoked just after we realize
3894 /// that an unnamed union or struct is actually an anonymous union or
3895 /// struct, e.g.,
3896 ///
3897 /// @code
3898 /// union {
3899 ///   int i;
3900 ///   float f;
3901 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3902 ///    // f into the surrounding scope.x
3903 /// @endcode
3904 ///
3905 /// This routine is recursive, injecting the names of nested anonymous
3906 /// structs/unions into the owning context and scope as well.
3907 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3908                                          DeclContext *Owner,
3909                                          RecordDecl *AnonRecord,
3910                                          AccessSpecifier AS,
3911                                          SmallVectorImpl<NamedDecl *> &Chaining,
3912                                          bool MSAnonStruct) {
3913   unsigned diagKind
3914     = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3915                             : diag::err_anonymous_struct_member_redecl;
3916 
3917   bool Invalid = false;
3918 
3919   // Look every FieldDecl and IndirectFieldDecl with a name.
3920   for (auto *D : AnonRecord->decls()) {
3921     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3922         cast<NamedDecl>(D)->getDeclName()) {
3923       ValueDecl *VD = cast<ValueDecl>(D);
3924       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3925                                        VD->getLocation(), diagKind)) {
3926         // C++ [class.union]p2:
3927         //   The names of the members of an anonymous union shall be
3928         //   distinct from the names of any other entity in the
3929         //   scope in which the anonymous union is declared.
3930         Invalid = true;
3931       } else {
3932         // C++ [class.union]p2:
3933         //   For the purpose of name lookup, after the anonymous union
3934         //   definition, the members of the anonymous union are
3935         //   considered to have been defined in the scope in which the
3936         //   anonymous union is declared.
3937         unsigned OldChainingSize = Chaining.size();
3938         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3939           Chaining.append(IF->chain_begin(), IF->chain_end());
3940         else
3941           Chaining.push_back(VD);
3942 
3943         assert(Chaining.size() >= 2);
3944         NamedDecl **NamedChain =
3945           new (SemaRef.Context)NamedDecl*[Chaining.size()];
3946         for (unsigned i = 0; i < Chaining.size(); i++)
3947           NamedChain[i] = Chaining[i];
3948 
3949         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
3950             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
3951             VD->getType(), NamedChain, Chaining.size());
3952 
3953         for (const auto *Attr : VD->attrs())
3954           IndirectField->addAttr(Attr->clone(SemaRef.Context));
3955 
3956         IndirectField->setAccess(AS);
3957         IndirectField->setImplicit();
3958         SemaRef.PushOnScopeChains(IndirectField, S);
3959 
3960         // That includes picking up the appropriate access specifier.
3961         if (AS != AS_none) IndirectField->setAccess(AS);
3962 
3963         Chaining.resize(OldChainingSize);
3964       }
3965     }
3966   }
3967 
3968   return Invalid;
3969 }
3970 
3971 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3972 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
3973 /// illegal input values are mapped to SC_None.
3974 static StorageClass
3975 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3976   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3977   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3978          "Parser allowed 'typedef' as storage class VarDecl.");
3979   switch (StorageClassSpec) {
3980   case DeclSpec::SCS_unspecified:    return SC_None;
3981   case DeclSpec::SCS_extern:
3982     if (DS.isExternInLinkageSpec())
3983       return SC_None;
3984     return SC_Extern;
3985   case DeclSpec::SCS_static:         return SC_Static;
3986   case DeclSpec::SCS_auto:           return SC_Auto;
3987   case DeclSpec::SCS_register:       return SC_Register;
3988   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3989     // Illegal SCSs map to None: error reporting is up to the caller.
3990   case DeclSpec::SCS_mutable:        // Fall through.
3991   case DeclSpec::SCS_typedef:        return SC_None;
3992   }
3993   llvm_unreachable("unknown storage class specifier");
3994 }
3995 
3996 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3997   assert(Record->hasInClassInitializer());
3998 
3999   for (const auto *I : Record->decls()) {
4000     const auto *FD = dyn_cast<FieldDecl>(I);
4001     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4002       FD = IFD->getAnonField();
4003     if (FD && FD->hasInClassInitializer())
4004       return FD->getLocation();
4005   }
4006 
4007   llvm_unreachable("couldn't find in-class initializer");
4008 }
4009 
4010 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4011                                       SourceLocation DefaultInitLoc) {
4012   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4013     return;
4014 
4015   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4016   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4017 }
4018 
4019 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4020                                       CXXRecordDecl *AnonUnion) {
4021   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4022     return;
4023 
4024   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4025 }
4026 
4027 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4028 /// anonymous structure or union. Anonymous unions are a C++ feature
4029 /// (C++ [class.union]) and a C11 feature; anonymous structures
4030 /// are a C11 feature and GNU C++ extension.
4031 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4032                                         AccessSpecifier AS,
4033                                         RecordDecl *Record,
4034                                         const PrintingPolicy &Policy) {
4035   DeclContext *Owner = Record->getDeclContext();
4036 
4037   // Diagnose whether this anonymous struct/union is an extension.
4038   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4039     Diag(Record->getLocation(), diag::ext_anonymous_union);
4040   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4041     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4042   else if (!Record->isUnion() && !getLangOpts().C11)
4043     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4044 
4045   // C and C++ require different kinds of checks for anonymous
4046   // structs/unions.
4047   bool Invalid = false;
4048   if (getLangOpts().CPlusPlus) {
4049     const char *PrevSpec = nullptr;
4050     unsigned DiagID;
4051     if (Record->isUnion()) {
4052       // C++ [class.union]p6:
4053       //   Anonymous unions declared in a named namespace or in the
4054       //   global namespace shall be declared static.
4055       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4056           (isa<TranslationUnitDecl>(Owner) ||
4057            (isa<NamespaceDecl>(Owner) &&
4058             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4059         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4060           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4061 
4062         // Recover by adding 'static'.
4063         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4064                                PrevSpec, DiagID, Policy);
4065       }
4066       // C++ [class.union]p6:
4067       //   A storage class is not allowed in a declaration of an
4068       //   anonymous union in a class scope.
4069       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4070                isa<RecordDecl>(Owner)) {
4071         Diag(DS.getStorageClassSpecLoc(),
4072              diag::err_anonymous_union_with_storage_spec)
4073           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4074 
4075         // Recover by removing the storage specifier.
4076         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4077                                SourceLocation(),
4078                                PrevSpec, DiagID, Context.getPrintingPolicy());
4079       }
4080     }
4081 
4082     // Ignore const/volatile/restrict qualifiers.
4083     if (DS.getTypeQualifiers()) {
4084       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4085         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4086           << Record->isUnion() << "const"
4087           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4088       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4089         Diag(DS.getVolatileSpecLoc(),
4090              diag::ext_anonymous_struct_union_qualified)
4091           << Record->isUnion() << "volatile"
4092           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4093       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4094         Diag(DS.getRestrictSpecLoc(),
4095              diag::ext_anonymous_struct_union_qualified)
4096           << Record->isUnion() << "restrict"
4097           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4098       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4099         Diag(DS.getAtomicSpecLoc(),
4100              diag::ext_anonymous_struct_union_qualified)
4101           << Record->isUnion() << "_Atomic"
4102           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4103 
4104       DS.ClearTypeQualifiers();
4105     }
4106 
4107     // C++ [class.union]p2:
4108     //   The member-specification of an anonymous union shall only
4109     //   define non-static data members. [Note: nested types and
4110     //   functions cannot be declared within an anonymous union. ]
4111     for (auto *Mem : Record->decls()) {
4112       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4113         // C++ [class.union]p3:
4114         //   An anonymous union shall not have private or protected
4115         //   members (clause 11).
4116         assert(FD->getAccess() != AS_none);
4117         if (FD->getAccess() != AS_public) {
4118           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4119             << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
4120           Invalid = true;
4121         }
4122 
4123         // C++ [class.union]p1
4124         //   An object of a class with a non-trivial constructor, a non-trivial
4125         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4126         //   assignment operator cannot be a member of a union, nor can an
4127         //   array of such objects.
4128         if (CheckNontrivialField(FD))
4129           Invalid = true;
4130       } else if (Mem->isImplicit()) {
4131         // Any implicit members are fine.
4132       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4133         // This is a type that showed up in an
4134         // elaborated-type-specifier inside the anonymous struct or
4135         // union, but which actually declares a type outside of the
4136         // anonymous struct or union. It's okay.
4137       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4138         if (!MemRecord->isAnonymousStructOrUnion() &&
4139             MemRecord->getDeclName()) {
4140           // Visual C++ allows type definition in anonymous struct or union.
4141           if (getLangOpts().MicrosoftExt)
4142             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4143               << (int)Record->isUnion();
4144           else {
4145             // This is a nested type declaration.
4146             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4147               << (int)Record->isUnion();
4148             Invalid = true;
4149           }
4150         } else {
4151           // This is an anonymous type definition within another anonymous type.
4152           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4153           // not part of standard C++.
4154           Diag(MemRecord->getLocation(),
4155                diag::ext_anonymous_record_with_anonymous_type)
4156             << (int)Record->isUnion();
4157         }
4158       } else if (isa<AccessSpecDecl>(Mem)) {
4159         // Any access specifier is fine.
4160       } else if (isa<StaticAssertDecl>(Mem)) {
4161         // In C++1z, static_assert declarations are also fine.
4162       } else {
4163         // We have something that isn't a non-static data
4164         // member. Complain about it.
4165         unsigned DK = diag::err_anonymous_record_bad_member;
4166         if (isa<TypeDecl>(Mem))
4167           DK = diag::err_anonymous_record_with_type;
4168         else if (isa<FunctionDecl>(Mem))
4169           DK = diag::err_anonymous_record_with_function;
4170         else if (isa<VarDecl>(Mem))
4171           DK = diag::err_anonymous_record_with_static;
4172 
4173         // Visual C++ allows type definition in anonymous struct or union.
4174         if (getLangOpts().MicrosoftExt &&
4175             DK == diag::err_anonymous_record_with_type)
4176           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4177             << (int)Record->isUnion();
4178         else {
4179           Diag(Mem->getLocation(), DK)
4180               << (int)Record->isUnion();
4181           Invalid = true;
4182         }
4183       }
4184     }
4185 
4186     // C++11 [class.union]p8 (DR1460):
4187     //   At most one variant member of a union may have a
4188     //   brace-or-equal-initializer.
4189     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4190         Owner->isRecord())
4191       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4192                                 cast<CXXRecordDecl>(Record));
4193   }
4194 
4195   if (!Record->isUnion() && !Owner->isRecord()) {
4196     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4197       << (int)getLangOpts().CPlusPlus;
4198     Invalid = true;
4199   }
4200 
4201   // Mock up a declarator.
4202   Declarator Dc(DS, Declarator::MemberContext);
4203   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4204   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4205 
4206   // Create a declaration for this anonymous struct/union.
4207   NamedDecl *Anon = nullptr;
4208   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4209     Anon = FieldDecl::Create(Context, OwningClass,
4210                              DS.getLocStart(),
4211                              Record->getLocation(),
4212                              /*IdentifierInfo=*/nullptr,
4213                              Context.getTypeDeclType(Record),
4214                              TInfo,
4215                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4216                              /*InitStyle=*/ICIS_NoInit);
4217     Anon->setAccess(AS);
4218     if (getLangOpts().CPlusPlus)
4219       FieldCollector->Add(cast<FieldDecl>(Anon));
4220   } else {
4221     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4222     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4223     if (SCSpec == DeclSpec::SCS_mutable) {
4224       // mutable can only appear on non-static class members, so it's always
4225       // an error here
4226       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4227       Invalid = true;
4228       SC = SC_None;
4229     }
4230 
4231     Anon = VarDecl::Create(Context, Owner,
4232                            DS.getLocStart(),
4233                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4234                            Context.getTypeDeclType(Record),
4235                            TInfo, SC);
4236 
4237     // Default-initialize the implicit variable. This initialization will be
4238     // trivial in almost all cases, except if a union member has an in-class
4239     // initializer:
4240     //   union { int n = 0; };
4241     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4242   }
4243   Anon->setImplicit();
4244 
4245   // Mark this as an anonymous struct/union type.
4246   Record->setAnonymousStructOrUnion(true);
4247 
4248   // Add the anonymous struct/union object to the current
4249   // context. We'll be referencing this object when we refer to one of
4250   // its members.
4251   Owner->addDecl(Anon);
4252 
4253   // Inject the members of the anonymous struct/union into the owning
4254   // context and into the identifier resolver chain for name lookup
4255   // purposes.
4256   SmallVector<NamedDecl*, 2> Chain;
4257   Chain.push_back(Anon);
4258 
4259   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
4260                                           Chain, false))
4261     Invalid = true;
4262 
4263   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4264     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4265       Decl *ManglingContextDecl;
4266       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4267               NewVD->getDeclContext(), ManglingContextDecl)) {
4268         Context.setManglingNumber(
4269             NewVD, MCtx->getManglingNumber(
4270                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4271         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4272       }
4273     }
4274   }
4275 
4276   if (Invalid)
4277     Anon->setInvalidDecl();
4278 
4279   return Anon;
4280 }
4281 
4282 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4283 /// Microsoft C anonymous structure.
4284 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4285 /// Example:
4286 ///
4287 /// struct A { int a; };
4288 /// struct B { struct A; int b; };
4289 ///
4290 /// void foo() {
4291 ///   B var;
4292 ///   var.a = 3;
4293 /// }
4294 ///
4295 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4296                                            RecordDecl *Record) {
4297   assert(Record && "expected a record!");
4298 
4299   // Mock up a declarator.
4300   Declarator Dc(DS, Declarator::TypeNameContext);
4301   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4302   assert(TInfo && "couldn't build declarator info for anonymous struct");
4303 
4304   auto *ParentDecl = cast<RecordDecl>(CurContext);
4305   QualType RecTy = Context.getTypeDeclType(Record);
4306 
4307   // Create a declaration for this anonymous struct.
4308   NamedDecl *Anon = FieldDecl::Create(Context,
4309                              ParentDecl,
4310                              DS.getLocStart(),
4311                              DS.getLocStart(),
4312                              /*IdentifierInfo=*/nullptr,
4313                              RecTy,
4314                              TInfo,
4315                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4316                              /*InitStyle=*/ICIS_NoInit);
4317   Anon->setImplicit();
4318 
4319   // Add the anonymous struct object to the current context.
4320   CurContext->addDecl(Anon);
4321 
4322   // Inject the members of the anonymous struct into the current
4323   // context and into the identifier resolver chain for name lookup
4324   // purposes.
4325   SmallVector<NamedDecl*, 2> Chain;
4326   Chain.push_back(Anon);
4327 
4328   RecordDecl *RecordDef = Record->getDefinition();
4329   if (RequireCompleteType(Anon->getLocation(), RecTy,
4330                           diag::err_field_incomplete) ||
4331       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4332                                           AS_none, Chain, true)) {
4333     Anon->setInvalidDecl();
4334     ParentDecl->setInvalidDecl();
4335   }
4336 
4337   return Anon;
4338 }
4339 
4340 /// GetNameForDeclarator - Determine the full declaration name for the
4341 /// given Declarator.
4342 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4343   return GetNameFromUnqualifiedId(D.getName());
4344 }
4345 
4346 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4347 DeclarationNameInfo
4348 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4349   DeclarationNameInfo NameInfo;
4350   NameInfo.setLoc(Name.StartLocation);
4351 
4352   switch (Name.getKind()) {
4353 
4354   case UnqualifiedId::IK_ImplicitSelfParam:
4355   case UnqualifiedId::IK_Identifier:
4356     NameInfo.setName(Name.Identifier);
4357     NameInfo.setLoc(Name.StartLocation);
4358     return NameInfo;
4359 
4360   case UnqualifiedId::IK_OperatorFunctionId:
4361     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4362                                            Name.OperatorFunctionId.Operator));
4363     NameInfo.setLoc(Name.StartLocation);
4364     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4365       = Name.OperatorFunctionId.SymbolLocations[0];
4366     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4367       = Name.EndLocation.getRawEncoding();
4368     return NameInfo;
4369 
4370   case UnqualifiedId::IK_LiteralOperatorId:
4371     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4372                                                            Name.Identifier));
4373     NameInfo.setLoc(Name.StartLocation);
4374     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4375     return NameInfo;
4376 
4377   case UnqualifiedId::IK_ConversionFunctionId: {
4378     TypeSourceInfo *TInfo;
4379     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4380     if (Ty.isNull())
4381       return DeclarationNameInfo();
4382     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4383                                                Context.getCanonicalType(Ty)));
4384     NameInfo.setLoc(Name.StartLocation);
4385     NameInfo.setNamedTypeInfo(TInfo);
4386     return NameInfo;
4387   }
4388 
4389   case UnqualifiedId::IK_ConstructorName: {
4390     TypeSourceInfo *TInfo;
4391     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4392     if (Ty.isNull())
4393       return DeclarationNameInfo();
4394     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4395                                               Context.getCanonicalType(Ty)));
4396     NameInfo.setLoc(Name.StartLocation);
4397     NameInfo.setNamedTypeInfo(TInfo);
4398     return NameInfo;
4399   }
4400 
4401   case UnqualifiedId::IK_ConstructorTemplateId: {
4402     // In well-formed code, we can only have a constructor
4403     // template-id that refers to the current context, so go there
4404     // to find the actual type being constructed.
4405     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4406     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4407       return DeclarationNameInfo();
4408 
4409     // Determine the type of the class being constructed.
4410     QualType CurClassType = Context.getTypeDeclType(CurClass);
4411 
4412     // FIXME: Check two things: that the template-id names the same type as
4413     // CurClassType, and that the template-id does not occur when the name
4414     // was qualified.
4415 
4416     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4417                                     Context.getCanonicalType(CurClassType)));
4418     NameInfo.setLoc(Name.StartLocation);
4419     // FIXME: should we retrieve TypeSourceInfo?
4420     NameInfo.setNamedTypeInfo(nullptr);
4421     return NameInfo;
4422   }
4423 
4424   case UnqualifiedId::IK_DestructorName: {
4425     TypeSourceInfo *TInfo;
4426     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4427     if (Ty.isNull())
4428       return DeclarationNameInfo();
4429     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4430                                               Context.getCanonicalType(Ty)));
4431     NameInfo.setLoc(Name.StartLocation);
4432     NameInfo.setNamedTypeInfo(TInfo);
4433     return NameInfo;
4434   }
4435 
4436   case UnqualifiedId::IK_TemplateId: {
4437     TemplateName TName = Name.TemplateId->Template.get();
4438     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4439     return Context.getNameForTemplate(TName, TNameLoc);
4440   }
4441 
4442   } // switch (Name.getKind())
4443 
4444   llvm_unreachable("Unknown name kind");
4445 }
4446 
4447 static QualType getCoreType(QualType Ty) {
4448   do {
4449     if (Ty->isPointerType() || Ty->isReferenceType())
4450       Ty = Ty->getPointeeType();
4451     else if (Ty->isArrayType())
4452       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4453     else
4454       return Ty.withoutLocalFastQualifiers();
4455   } while (true);
4456 }
4457 
4458 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4459 /// and Definition have "nearly" matching parameters. This heuristic is
4460 /// used to improve diagnostics in the case where an out-of-line function
4461 /// definition doesn't match any declaration within the class or namespace.
4462 /// Also sets Params to the list of indices to the parameters that differ
4463 /// between the declaration and the definition. If hasSimilarParameters
4464 /// returns true and Params is empty, then all of the parameters match.
4465 static bool hasSimilarParameters(ASTContext &Context,
4466                                      FunctionDecl *Declaration,
4467                                      FunctionDecl *Definition,
4468                                      SmallVectorImpl<unsigned> &Params) {
4469   Params.clear();
4470   if (Declaration->param_size() != Definition->param_size())
4471     return false;
4472   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4473     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4474     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4475 
4476     // The parameter types are identical
4477     if (Context.hasSameType(DefParamTy, DeclParamTy))
4478       continue;
4479 
4480     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4481     QualType DefParamBaseTy = getCoreType(DefParamTy);
4482     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4483     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4484 
4485     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4486         (DeclTyName && DeclTyName == DefTyName))
4487       Params.push_back(Idx);
4488     else  // The two parameters aren't even close
4489       return false;
4490   }
4491 
4492   return true;
4493 }
4494 
4495 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4496 /// declarator needs to be rebuilt in the current instantiation.
4497 /// Any bits of declarator which appear before the name are valid for
4498 /// consideration here.  That's specifically the type in the decl spec
4499 /// and the base type in any member-pointer chunks.
4500 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4501                                                     DeclarationName Name) {
4502   // The types we specifically need to rebuild are:
4503   //   - typenames, typeofs, and decltypes
4504   //   - types which will become injected class names
4505   // Of course, we also need to rebuild any type referencing such a
4506   // type.  It's safest to just say "dependent", but we call out a
4507   // few cases here.
4508 
4509   DeclSpec &DS = D.getMutableDeclSpec();
4510   switch (DS.getTypeSpecType()) {
4511   case DeclSpec::TST_typename:
4512   case DeclSpec::TST_typeofType:
4513   case DeclSpec::TST_underlyingType:
4514   case DeclSpec::TST_atomic: {
4515     // Grab the type from the parser.
4516     TypeSourceInfo *TSI = nullptr;
4517     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4518     if (T.isNull() || !T->isDependentType()) break;
4519 
4520     // Make sure there's a type source info.  This isn't really much
4521     // of a waste; most dependent types should have type source info
4522     // attached already.
4523     if (!TSI)
4524       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4525 
4526     // Rebuild the type in the current instantiation.
4527     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4528     if (!TSI) return true;
4529 
4530     // Store the new type back in the decl spec.
4531     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4532     DS.UpdateTypeRep(LocType);
4533     break;
4534   }
4535 
4536   case DeclSpec::TST_decltype:
4537   case DeclSpec::TST_typeofExpr: {
4538     Expr *E = DS.getRepAsExpr();
4539     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4540     if (Result.isInvalid()) return true;
4541     DS.UpdateExprRep(Result.get());
4542     break;
4543   }
4544 
4545   default:
4546     // Nothing to do for these decl specs.
4547     break;
4548   }
4549 
4550   // It doesn't matter what order we do this in.
4551   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4552     DeclaratorChunk &Chunk = D.getTypeObject(I);
4553 
4554     // The only type information in the declarator which can come
4555     // before the declaration name is the base type of a member
4556     // pointer.
4557     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4558       continue;
4559 
4560     // Rebuild the scope specifier in-place.
4561     CXXScopeSpec &SS = Chunk.Mem.Scope();
4562     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4563       return true;
4564   }
4565 
4566   return false;
4567 }
4568 
4569 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4570   D.setFunctionDefinitionKind(FDK_Declaration);
4571   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4572 
4573   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4574       Dcl && Dcl->getDeclContext()->isFileContext())
4575     Dcl->setTopLevelDeclInObjCContainer();
4576 
4577   return Dcl;
4578 }
4579 
4580 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4581 ///   If T is the name of a class, then each of the following shall have a
4582 ///   name different from T:
4583 ///     - every static data member of class T;
4584 ///     - every member function of class T
4585 ///     - every member of class T that is itself a type;
4586 /// \returns true if the declaration name violates these rules.
4587 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4588                                    DeclarationNameInfo NameInfo) {
4589   DeclarationName Name = NameInfo.getName();
4590 
4591   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4592     if (Record->getIdentifier() && Record->getDeclName() == Name) {
4593       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4594       return true;
4595     }
4596 
4597   return false;
4598 }
4599 
4600 /// \brief Diagnose a declaration whose declarator-id has the given
4601 /// nested-name-specifier.
4602 ///
4603 /// \param SS The nested-name-specifier of the declarator-id.
4604 ///
4605 /// \param DC The declaration context to which the nested-name-specifier
4606 /// resolves.
4607 ///
4608 /// \param Name The name of the entity being declared.
4609 ///
4610 /// \param Loc The location of the name of the entity being declared.
4611 ///
4612 /// \returns true if we cannot safely recover from this error, false otherwise.
4613 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4614                                         DeclarationName Name,
4615                                         SourceLocation Loc) {
4616   DeclContext *Cur = CurContext;
4617   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4618     Cur = Cur->getParent();
4619 
4620   // If the user provided a superfluous scope specifier that refers back to the
4621   // class in which the entity is already declared, diagnose and ignore it.
4622   //
4623   // class X {
4624   //   void X::f();
4625   // };
4626   //
4627   // Note, it was once ill-formed to give redundant qualification in all
4628   // contexts, but that rule was removed by DR482.
4629   if (Cur->Equals(DC)) {
4630     if (Cur->isRecord()) {
4631       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4632                                       : diag::err_member_extra_qualification)
4633         << Name << FixItHint::CreateRemoval(SS.getRange());
4634       SS.clear();
4635     } else {
4636       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4637     }
4638     return false;
4639   }
4640 
4641   // Check whether the qualifying scope encloses the scope of the original
4642   // declaration.
4643   if (!Cur->Encloses(DC)) {
4644     if (Cur->isRecord())
4645       Diag(Loc, diag::err_member_qualification)
4646         << Name << SS.getRange();
4647     else if (isa<TranslationUnitDecl>(DC))
4648       Diag(Loc, diag::err_invalid_declarator_global_scope)
4649         << Name << SS.getRange();
4650     else if (isa<FunctionDecl>(Cur))
4651       Diag(Loc, diag::err_invalid_declarator_in_function)
4652         << Name << SS.getRange();
4653     else if (isa<BlockDecl>(Cur))
4654       Diag(Loc, diag::err_invalid_declarator_in_block)
4655         << Name << SS.getRange();
4656     else
4657       Diag(Loc, diag::err_invalid_declarator_scope)
4658       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4659 
4660     return true;
4661   }
4662 
4663   if (Cur->isRecord()) {
4664     // Cannot qualify members within a class.
4665     Diag(Loc, diag::err_member_qualification)
4666       << Name << SS.getRange();
4667     SS.clear();
4668 
4669     // C++ constructors and destructors with incorrect scopes can break
4670     // our AST invariants by having the wrong underlying types. If
4671     // that's the case, then drop this declaration entirely.
4672     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4673          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4674         !Context.hasSameType(Name.getCXXNameType(),
4675                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4676       return true;
4677 
4678     return false;
4679   }
4680 
4681   // C++11 [dcl.meaning]p1:
4682   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4683   //   not begin with a decltype-specifer"
4684   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4685   while (SpecLoc.getPrefix())
4686     SpecLoc = SpecLoc.getPrefix();
4687   if (dyn_cast_or_null<DecltypeType>(
4688         SpecLoc.getNestedNameSpecifier()->getAsType()))
4689     Diag(Loc, diag::err_decltype_in_declarator)
4690       << SpecLoc.getTypeLoc().getSourceRange();
4691 
4692   return false;
4693 }
4694 
4695 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4696                                   MultiTemplateParamsArg TemplateParamLists) {
4697   // TODO: consider using NameInfo for diagnostic.
4698   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4699   DeclarationName Name = NameInfo.getName();
4700 
4701   // All of these full declarators require an identifier.  If it doesn't have
4702   // one, the ParsedFreeStandingDeclSpec action should be used.
4703   if (!Name) {
4704     if (!D.isInvalidType())  // Reject this if we think it is valid.
4705       Diag(D.getDeclSpec().getLocStart(),
4706            diag::err_declarator_need_ident)
4707         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4708     return nullptr;
4709   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4710     return nullptr;
4711 
4712   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4713   // we find one that is.
4714   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4715          (S->getFlags() & Scope::TemplateParamScope) != 0)
4716     S = S->getParent();
4717 
4718   DeclContext *DC = CurContext;
4719   if (D.getCXXScopeSpec().isInvalid())
4720     D.setInvalidType();
4721   else if (D.getCXXScopeSpec().isSet()) {
4722     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4723                                         UPPC_DeclarationQualifier))
4724       return nullptr;
4725 
4726     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4727     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4728     if (!DC || isa<EnumDecl>(DC)) {
4729       // If we could not compute the declaration context, it's because the
4730       // declaration context is dependent but does not refer to a class,
4731       // class template, or class template partial specialization. Complain
4732       // and return early, to avoid the coming semantic disaster.
4733       Diag(D.getIdentifierLoc(),
4734            diag::err_template_qualified_declarator_no_match)
4735         << D.getCXXScopeSpec().getScopeRep()
4736         << D.getCXXScopeSpec().getRange();
4737       return nullptr;
4738     }
4739     bool IsDependentContext = DC->isDependentContext();
4740 
4741     if (!IsDependentContext &&
4742         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4743       return nullptr;
4744 
4745     // If a class is incomplete, do not parse entities inside it.
4746     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4747       Diag(D.getIdentifierLoc(),
4748            diag::err_member_def_undefined_record)
4749         << Name << DC << D.getCXXScopeSpec().getRange();
4750       return nullptr;
4751     }
4752     if (!D.getDeclSpec().isFriendSpecified()) {
4753       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4754                                       Name, D.getIdentifierLoc())) {
4755         if (DC->isRecord())
4756           return nullptr;
4757 
4758         D.setInvalidType();
4759       }
4760     }
4761 
4762     // Check whether we need to rebuild the type of the given
4763     // declaration in the current instantiation.
4764     if (EnteringContext && IsDependentContext &&
4765         TemplateParamLists.size() != 0) {
4766       ContextRAII SavedContext(*this, DC);
4767       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4768         D.setInvalidType();
4769     }
4770   }
4771 
4772   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4773   QualType R = TInfo->getType();
4774 
4775   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4776     // If this is a typedef, we'll end up spewing multiple diagnostics.
4777     // Just return early; it's safer. If this is a function, let the
4778     // "constructor cannot have a return type" diagnostic handle it.
4779     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4780       return nullptr;
4781 
4782   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4783                                       UPPC_DeclarationType))
4784     D.setInvalidType();
4785 
4786   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4787                         ForRedeclaration);
4788 
4789   // If we're hiding internal-linkage symbols in modules from redeclaration
4790   // lookup, let name lookup know.
4791   if ((getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) &&
4792       getLangOpts().ModulesHideInternalLinkage &&
4793       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4794     Previous.setAllowHiddenInternal(false);
4795 
4796   // See if this is a redefinition of a variable in the same scope.
4797   if (!D.getCXXScopeSpec().isSet()) {
4798     bool IsLinkageLookup = false;
4799     bool CreateBuiltins = false;
4800 
4801     // If the declaration we're planning to build will be a function
4802     // or object with linkage, then look for another declaration with
4803     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4804     //
4805     // If the declaration we're planning to build will be declared with
4806     // external linkage in the translation unit, create any builtin with
4807     // the same name.
4808     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4809       /* Do nothing*/;
4810     else if (CurContext->isFunctionOrMethod() &&
4811              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4812               R->isFunctionType())) {
4813       IsLinkageLookup = true;
4814       CreateBuiltins =
4815           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4816     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4817                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4818       CreateBuiltins = true;
4819 
4820     if (IsLinkageLookup)
4821       Previous.clear(LookupRedeclarationWithLinkage);
4822 
4823     LookupName(Previous, S, CreateBuiltins);
4824   } else { // Something like "int foo::x;"
4825     LookupQualifiedName(Previous, DC);
4826 
4827     // C++ [dcl.meaning]p1:
4828     //   When the declarator-id is qualified, the declaration shall refer to a
4829     //  previously declared member of the class or namespace to which the
4830     //  qualifier refers (or, in the case of a namespace, of an element of the
4831     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4832     //  thereof; [...]
4833     //
4834     // Note that we already checked the context above, and that we do not have
4835     // enough information to make sure that Previous contains the declaration
4836     // we want to match. For example, given:
4837     //
4838     //   class X {
4839     //     void f();
4840     //     void f(float);
4841     //   };
4842     //
4843     //   void X::f(int) { } // ill-formed
4844     //
4845     // In this case, Previous will point to the overload set
4846     // containing the two f's declared in X, but neither of them
4847     // matches.
4848 
4849     // C++ [dcl.meaning]p1:
4850     //   [...] the member shall not merely have been introduced by a
4851     //   using-declaration in the scope of the class or namespace nominated by
4852     //   the nested-name-specifier of the declarator-id.
4853     RemoveUsingDecls(Previous);
4854   }
4855 
4856   if (Previous.isSingleResult() &&
4857       Previous.getFoundDecl()->isTemplateParameter()) {
4858     // Maybe we will complain about the shadowed template parameter.
4859     if (!D.isInvalidType())
4860       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4861                                       Previous.getFoundDecl());
4862 
4863     // Just pretend that we didn't see the previous declaration.
4864     Previous.clear();
4865   }
4866 
4867   // In C++, the previous declaration we find might be a tag type
4868   // (class or enum). In this case, the new declaration will hide the
4869   // tag type. Note that this does does not apply if we're declaring a
4870   // typedef (C++ [dcl.typedef]p4).
4871   if (Previous.isSingleTagDecl() &&
4872       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4873     Previous.clear();
4874 
4875   // Check that there are no default arguments other than in the parameters
4876   // of a function declaration (C++ only).
4877   if (getLangOpts().CPlusPlus)
4878     CheckExtraCXXDefaultArguments(D);
4879 
4880   if (D.getDeclSpec().isConceptSpecified()) {
4881     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
4882     // applied only to the definition of a function template or variable
4883     // template, declared in namespace scope
4884     if (!TemplateParamLists.size()) {
4885       Diag(D.getDeclSpec().getConceptSpecLoc(),
4886            diag:: err_concept_wrong_decl_kind);
4887       return nullptr;
4888     }
4889 
4890     if (!DC->getRedeclContext()->isFileContext()) {
4891       Diag(D.getIdentifierLoc(),
4892            diag::err_concept_decls_may_only_appear_in_namespace_scope);
4893       return nullptr;
4894     }
4895   }
4896 
4897   NamedDecl *New;
4898 
4899   bool AddToScope = true;
4900   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4901     if (TemplateParamLists.size()) {
4902       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4903       return nullptr;
4904     }
4905 
4906     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4907   } else if (R->isFunctionType()) {
4908     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4909                                   TemplateParamLists,
4910                                   AddToScope);
4911   } else {
4912     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4913                                   AddToScope);
4914   }
4915 
4916   if (!New)
4917     return nullptr;
4918 
4919   // If this has an identifier and is not an invalid redeclaration or
4920   // function template specialization, add it to the scope stack.
4921   if (New->getDeclName() && AddToScope &&
4922        !(D.isRedeclaration() && New->isInvalidDecl())) {
4923     // Only make a locally-scoped extern declaration visible if it is the first
4924     // declaration of this entity. Qualified lookup for such an entity should
4925     // only find this declaration if there is no visible declaration of it.
4926     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4927     PushOnScopeChains(New, S, AddToContext);
4928     if (!AddToContext)
4929       CurContext->addHiddenDecl(New);
4930   }
4931 
4932   return New;
4933 }
4934 
4935 /// Helper method to turn variable array types into constant array
4936 /// types in certain situations which would otherwise be errors (for
4937 /// GCC compatibility).
4938 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4939                                                     ASTContext &Context,
4940                                                     bool &SizeIsNegative,
4941                                                     llvm::APSInt &Oversized) {
4942   // This method tries to turn a variable array into a constant
4943   // array even when the size isn't an ICE.  This is necessary
4944   // for compatibility with code that depends on gcc's buggy
4945   // constant expression folding, like struct {char x[(int)(char*)2];}
4946   SizeIsNegative = false;
4947   Oversized = 0;
4948 
4949   if (T->isDependentType())
4950     return QualType();
4951 
4952   QualifierCollector Qs;
4953   const Type *Ty = Qs.strip(T);
4954 
4955   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4956     QualType Pointee = PTy->getPointeeType();
4957     QualType FixedType =
4958         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4959                                             Oversized);
4960     if (FixedType.isNull()) return FixedType;
4961     FixedType = Context.getPointerType(FixedType);
4962     return Qs.apply(Context, FixedType);
4963   }
4964   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4965     QualType Inner = PTy->getInnerType();
4966     QualType FixedType =
4967         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4968                                             Oversized);
4969     if (FixedType.isNull()) return FixedType;
4970     FixedType = Context.getParenType(FixedType);
4971     return Qs.apply(Context, FixedType);
4972   }
4973 
4974   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
4975   if (!VLATy)
4976     return QualType();
4977   // FIXME: We should probably handle this case
4978   if (VLATy->getElementType()->isVariablyModifiedType())
4979     return QualType();
4980 
4981   llvm::APSInt Res;
4982   if (!VLATy->getSizeExpr() ||
4983       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
4984     return QualType();
4985 
4986   // Check whether the array size is negative.
4987   if (Res.isSigned() && Res.isNegative()) {
4988     SizeIsNegative = true;
4989     return QualType();
4990   }
4991 
4992   // Check whether the array is too large to be addressed.
4993   unsigned ActiveSizeBits
4994     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4995                                               Res);
4996   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4997     Oversized = Res;
4998     return QualType();
4999   }
5000 
5001   return Context.getConstantArrayType(VLATy->getElementType(),
5002                                       Res, ArrayType::Normal, 0);
5003 }
5004 
5005 static void
5006 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5007   SrcTL = SrcTL.getUnqualifiedLoc();
5008   DstTL = DstTL.getUnqualifiedLoc();
5009   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5010     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5011     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5012                                       DstPTL.getPointeeLoc());
5013     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5014     return;
5015   }
5016   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5017     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5018     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5019                                       DstPTL.getInnerLoc());
5020     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5021     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5022     return;
5023   }
5024   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5025   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5026   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5027   TypeLoc DstElemTL = DstATL.getElementLoc();
5028   DstElemTL.initializeFullCopy(SrcElemTL);
5029   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5030   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5031   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5032 }
5033 
5034 /// Helper method to turn variable array types into constant array
5035 /// types in certain situations which would otherwise be errors (for
5036 /// GCC compatibility).
5037 static TypeSourceInfo*
5038 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5039                                               ASTContext &Context,
5040                                               bool &SizeIsNegative,
5041                                               llvm::APSInt &Oversized) {
5042   QualType FixedTy
5043     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5044                                           SizeIsNegative, Oversized);
5045   if (FixedTy.isNull())
5046     return nullptr;
5047   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5048   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5049                                     FixedTInfo->getTypeLoc());
5050   return FixedTInfo;
5051 }
5052 
5053 /// \brief Register the given locally-scoped extern "C" declaration so
5054 /// that it can be found later for redeclarations. We include any extern "C"
5055 /// declaration that is not visible in the translation unit here, not just
5056 /// function-scope declarations.
5057 void
5058 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5059   if (!getLangOpts().CPlusPlus &&
5060       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5061     // Don't need to track declarations in the TU in C.
5062     return;
5063 
5064   // Note that we have a locally-scoped external with this name.
5065   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5066 }
5067 
5068 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5069   // FIXME: We can have multiple results via __attribute__((overloadable)).
5070   auto Result = Context.getExternCContextDecl()->lookup(Name);
5071   return Result.empty() ? nullptr : *Result.begin();
5072 }
5073 
5074 /// \brief Diagnose function specifiers on a declaration of an identifier that
5075 /// does not identify a function.
5076 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5077   // FIXME: We should probably indicate the identifier in question to avoid
5078   // confusion for constructs like "inline int a(), b;"
5079   if (DS.isInlineSpecified())
5080     Diag(DS.getInlineSpecLoc(),
5081          diag::err_inline_non_function);
5082 
5083   if (DS.isVirtualSpecified())
5084     Diag(DS.getVirtualSpecLoc(),
5085          diag::err_virtual_non_function);
5086 
5087   if (DS.isExplicitSpecified())
5088     Diag(DS.getExplicitSpecLoc(),
5089          diag::err_explicit_non_function);
5090 
5091   if (DS.isNoreturnSpecified())
5092     Diag(DS.getNoreturnSpecLoc(),
5093          diag::err_noreturn_non_function);
5094 }
5095 
5096 NamedDecl*
5097 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5098                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5099   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5100   if (D.getCXXScopeSpec().isSet()) {
5101     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5102       << D.getCXXScopeSpec().getRange();
5103     D.setInvalidType();
5104     // Pretend we didn't see the scope specifier.
5105     DC = CurContext;
5106     Previous.clear();
5107   }
5108 
5109   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5110 
5111   if (D.getDeclSpec().isConstexprSpecified())
5112     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5113       << 1;
5114 
5115   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5116     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5117       << D.getName().getSourceRange();
5118     return nullptr;
5119   }
5120 
5121   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5122   if (!NewTD) return nullptr;
5123 
5124   // Handle attributes prior to checking for duplicates in MergeVarDecl
5125   ProcessDeclAttributes(S, NewTD, D);
5126 
5127   CheckTypedefForVariablyModifiedType(S, NewTD);
5128 
5129   bool Redeclaration = D.isRedeclaration();
5130   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5131   D.setRedeclaration(Redeclaration);
5132   return ND;
5133 }
5134 
5135 void
5136 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5137   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5138   // then it shall have block scope.
5139   // Note that variably modified types must be fixed before merging the decl so
5140   // that redeclarations will match.
5141   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5142   QualType T = TInfo->getType();
5143   if (T->isVariablyModifiedType()) {
5144     getCurFunction()->setHasBranchProtectedScope();
5145 
5146     if (S->getFnParent() == nullptr) {
5147       bool SizeIsNegative;
5148       llvm::APSInt Oversized;
5149       TypeSourceInfo *FixedTInfo =
5150         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5151                                                       SizeIsNegative,
5152                                                       Oversized);
5153       if (FixedTInfo) {
5154         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5155         NewTD->setTypeSourceInfo(FixedTInfo);
5156       } else {
5157         if (SizeIsNegative)
5158           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5159         else if (T->isVariableArrayType())
5160           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5161         else if (Oversized.getBoolValue())
5162           Diag(NewTD->getLocation(), diag::err_array_too_large)
5163             << Oversized.toString(10);
5164         else
5165           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5166         NewTD->setInvalidDecl();
5167       }
5168     }
5169   }
5170 }
5171 
5172 
5173 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5174 /// declares a typedef-name, either using the 'typedef' type specifier or via
5175 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5176 NamedDecl*
5177 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5178                            LookupResult &Previous, bool &Redeclaration) {
5179   // Merge the decl with the existing one if appropriate. If the decl is
5180   // in an outer scope, it isn't the same thing.
5181   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5182                        /*AllowInlineNamespace*/false);
5183   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5184   if (!Previous.empty()) {
5185     Redeclaration = true;
5186     MergeTypedefNameDecl(NewTD, Previous);
5187   }
5188 
5189   // If this is the C FILE type, notify the AST context.
5190   if (IdentifierInfo *II = NewTD->getIdentifier())
5191     if (!NewTD->isInvalidDecl() &&
5192         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5193       if (II->isStr("FILE"))
5194         Context.setFILEDecl(NewTD);
5195       else if (II->isStr("jmp_buf"))
5196         Context.setjmp_bufDecl(NewTD);
5197       else if (II->isStr("sigjmp_buf"))
5198         Context.setsigjmp_bufDecl(NewTD);
5199       else if (II->isStr("ucontext_t"))
5200         Context.setucontext_tDecl(NewTD);
5201     }
5202 
5203   return NewTD;
5204 }
5205 
5206 /// \brief Determines whether the given declaration is an out-of-scope
5207 /// previous declaration.
5208 ///
5209 /// This routine should be invoked when name lookup has found a
5210 /// previous declaration (PrevDecl) that is not in the scope where a
5211 /// new declaration by the same name is being introduced. If the new
5212 /// declaration occurs in a local scope, previous declarations with
5213 /// linkage may still be considered previous declarations (C99
5214 /// 6.2.2p4-5, C++ [basic.link]p6).
5215 ///
5216 /// \param PrevDecl the previous declaration found by name
5217 /// lookup
5218 ///
5219 /// \param DC the context in which the new declaration is being
5220 /// declared.
5221 ///
5222 /// \returns true if PrevDecl is an out-of-scope previous declaration
5223 /// for a new delcaration with the same name.
5224 static bool
5225 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5226                                 ASTContext &Context) {
5227   if (!PrevDecl)
5228     return false;
5229 
5230   if (!PrevDecl->hasLinkage())
5231     return false;
5232 
5233   if (Context.getLangOpts().CPlusPlus) {
5234     // C++ [basic.link]p6:
5235     //   If there is a visible declaration of an entity with linkage
5236     //   having the same name and type, ignoring entities declared
5237     //   outside the innermost enclosing namespace scope, the block
5238     //   scope declaration declares that same entity and receives the
5239     //   linkage of the previous declaration.
5240     DeclContext *OuterContext = DC->getRedeclContext();
5241     if (!OuterContext->isFunctionOrMethod())
5242       // This rule only applies to block-scope declarations.
5243       return false;
5244 
5245     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5246     if (PrevOuterContext->isRecord())
5247       // We found a member function: ignore it.
5248       return false;
5249 
5250     // Find the innermost enclosing namespace for the new and
5251     // previous declarations.
5252     OuterContext = OuterContext->getEnclosingNamespaceContext();
5253     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5254 
5255     // The previous declaration is in a different namespace, so it
5256     // isn't the same function.
5257     if (!OuterContext->Equals(PrevOuterContext))
5258       return false;
5259   }
5260 
5261   return true;
5262 }
5263 
5264 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5265   CXXScopeSpec &SS = D.getCXXScopeSpec();
5266   if (!SS.isSet()) return;
5267   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5268 }
5269 
5270 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5271   QualType type = decl->getType();
5272   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5273   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5274     // Various kinds of declaration aren't allowed to be __autoreleasing.
5275     unsigned kind = -1U;
5276     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5277       if (var->hasAttr<BlocksAttr>())
5278         kind = 0; // __block
5279       else if (!var->hasLocalStorage())
5280         kind = 1; // global
5281     } else if (isa<ObjCIvarDecl>(decl)) {
5282       kind = 3; // ivar
5283     } else if (isa<FieldDecl>(decl)) {
5284       kind = 2; // field
5285     }
5286 
5287     if (kind != -1U) {
5288       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5289         << kind;
5290     }
5291   } else if (lifetime == Qualifiers::OCL_None) {
5292     // Try to infer lifetime.
5293     if (!type->isObjCLifetimeType())
5294       return false;
5295 
5296     lifetime = type->getObjCARCImplicitLifetime();
5297     type = Context.getLifetimeQualifiedType(type, lifetime);
5298     decl->setType(type);
5299   }
5300 
5301   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5302     // Thread-local variables cannot have lifetime.
5303     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5304         var->getTLSKind()) {
5305       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5306         << var->getType();
5307       return true;
5308     }
5309   }
5310 
5311   return false;
5312 }
5313 
5314 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5315   // Ensure that an auto decl is deduced otherwise the checks below might cache
5316   // the wrong linkage.
5317   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5318 
5319   // 'weak' only applies to declarations with external linkage.
5320   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5321     if (!ND.isExternallyVisible()) {
5322       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5323       ND.dropAttr<WeakAttr>();
5324     }
5325   }
5326   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5327     if (ND.isExternallyVisible()) {
5328       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5329       ND.dropAttr<WeakRefAttr>();
5330       ND.dropAttr<AliasAttr>();
5331     }
5332   }
5333 
5334   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5335     if (VD->hasInit()) {
5336       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5337         assert(VD->isThisDeclarationADefinition() &&
5338                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5339         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
5340         VD->dropAttr<AliasAttr>();
5341       }
5342     }
5343   }
5344 
5345   // 'selectany' only applies to externally visible variable declarations.
5346   // It does not apply to functions.
5347   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5348     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5349       S.Diag(Attr->getLocation(),
5350              diag::err_attribute_selectany_non_extern_data);
5351       ND.dropAttr<SelectAnyAttr>();
5352     }
5353   }
5354 
5355   // dll attributes require external linkage.
5356   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5357     if (!ND.isExternallyVisible()) {
5358       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5359         << &ND << Attr;
5360       ND.setInvalidDecl();
5361     }
5362   }
5363 }
5364 
5365 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5366                                            NamedDecl *NewDecl,
5367                                            bool IsSpecialization) {
5368   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5369     OldDecl = OldTD->getTemplatedDecl();
5370   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5371     NewDecl = NewTD->getTemplatedDecl();
5372 
5373   if (!OldDecl || !NewDecl)
5374     return;
5375 
5376   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5377   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5378   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5379   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5380 
5381   // dllimport and dllexport are inheritable attributes so we have to exclude
5382   // inherited attribute instances.
5383   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5384                     (NewExportAttr && !NewExportAttr->isInherited());
5385 
5386   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5387   // the only exception being explicit specializations.
5388   // Implicitly generated declarations are also excluded for now because there
5389   // is no other way to switch these to use dllimport or dllexport.
5390   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5391 
5392   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5393     // Allow with a warning for free functions and global variables.
5394     bool JustWarn = false;
5395     if (!OldDecl->isCXXClassMember()) {
5396       auto *VD = dyn_cast<VarDecl>(OldDecl);
5397       if (VD && !VD->getDescribedVarTemplate())
5398         JustWarn = true;
5399       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5400       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5401         JustWarn = true;
5402     }
5403 
5404     // We cannot change a declaration that's been used because IR has already
5405     // been emitted. Dllimported functions will still work though (modulo
5406     // address equality) as they can use the thunk.
5407     if (OldDecl->isUsed())
5408       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5409         JustWarn = false;
5410 
5411     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5412                                : diag::err_attribute_dll_redeclaration;
5413     S.Diag(NewDecl->getLocation(), DiagID)
5414         << NewDecl
5415         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5416     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5417     if (!JustWarn) {
5418       NewDecl->setInvalidDecl();
5419       return;
5420     }
5421   }
5422 
5423   // A redeclaration is not allowed to drop a dllimport attribute, the only
5424   // exceptions being inline function definitions, local extern declarations,
5425   // and qualified friend declarations.
5426   // NB: MSVC converts such a declaration to dllexport.
5427   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5428   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5429     // Ignore static data because out-of-line definitions are diagnosed
5430     // separately.
5431     IsStaticDataMember = VD->isStaticDataMember();
5432   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5433     IsInline = FD->isInlined();
5434     IsQualifiedFriend = FD->getQualifier() &&
5435                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5436   }
5437 
5438   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5439       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5440     S.Diag(NewDecl->getLocation(),
5441            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5442       << NewDecl << OldImportAttr;
5443     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5444     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5445     OldDecl->dropAttr<DLLImportAttr>();
5446     NewDecl->dropAttr<DLLImportAttr>();
5447   } else if (IsInline && OldImportAttr &&
5448              !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5449     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5450     OldDecl->dropAttr<DLLImportAttr>();
5451     NewDecl->dropAttr<DLLImportAttr>();
5452     S.Diag(NewDecl->getLocation(),
5453            diag::warn_dllimport_dropped_from_inline_function)
5454         << NewDecl << OldImportAttr;
5455   }
5456 }
5457 
5458 /// Given that we are within the definition of the given function,
5459 /// will that definition behave like C99's 'inline', where the
5460 /// definition is discarded except for optimization purposes?
5461 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5462   // Try to avoid calling GetGVALinkageForFunction.
5463 
5464   // All cases of this require the 'inline' keyword.
5465   if (!FD->isInlined()) return false;
5466 
5467   // This is only possible in C++ with the gnu_inline attribute.
5468   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5469     return false;
5470 
5471   // Okay, go ahead and call the relatively-more-expensive function.
5472 
5473 #ifndef NDEBUG
5474   // AST quite reasonably asserts that it's working on a function
5475   // definition.  We don't really have a way to tell it that we're
5476   // currently defining the function, so just lie to it in +Asserts
5477   // builds.  This is an awful hack.
5478   FD->setLazyBody(1);
5479 #endif
5480 
5481   bool isC99Inline =
5482       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5483 
5484 #ifndef NDEBUG
5485   FD->setLazyBody(0);
5486 #endif
5487 
5488   return isC99Inline;
5489 }
5490 
5491 /// Determine whether a variable is extern "C" prior to attaching
5492 /// an initializer. We can't just call isExternC() here, because that
5493 /// will also compute and cache whether the declaration is externally
5494 /// visible, which might change when we attach the initializer.
5495 ///
5496 /// This can only be used if the declaration is known to not be a
5497 /// redeclaration of an internal linkage declaration.
5498 ///
5499 /// For instance:
5500 ///
5501 ///   auto x = []{};
5502 ///
5503 /// Attaching the initializer here makes this declaration not externally
5504 /// visible, because its type has internal linkage.
5505 ///
5506 /// FIXME: This is a hack.
5507 template<typename T>
5508 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5509   if (S.getLangOpts().CPlusPlus) {
5510     // In C++, the overloadable attribute negates the effects of extern "C".
5511     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5512       return false;
5513   }
5514   return D->isExternC();
5515 }
5516 
5517 static bool shouldConsiderLinkage(const VarDecl *VD) {
5518   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5519   if (DC->isFunctionOrMethod())
5520     return VD->hasExternalStorage();
5521   if (DC->isFileContext())
5522     return true;
5523   if (DC->isRecord())
5524     return false;
5525   llvm_unreachable("Unexpected context");
5526 }
5527 
5528 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5529   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5530   if (DC->isFileContext() || DC->isFunctionOrMethod())
5531     return true;
5532   if (DC->isRecord())
5533     return false;
5534   llvm_unreachable("Unexpected context");
5535 }
5536 
5537 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5538                           AttributeList::Kind Kind) {
5539   for (const AttributeList *L = AttrList; L; L = L->getNext())
5540     if (L->getKind() == Kind)
5541       return true;
5542   return false;
5543 }
5544 
5545 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5546                           AttributeList::Kind Kind) {
5547   // Check decl attributes on the DeclSpec.
5548   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5549     return true;
5550 
5551   // Walk the declarator structure, checking decl attributes that were in a type
5552   // position to the decl itself.
5553   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5554     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5555       return true;
5556   }
5557 
5558   // Finally, check attributes on the decl itself.
5559   return hasParsedAttr(S, PD.getAttributes(), Kind);
5560 }
5561 
5562 /// Adjust the \c DeclContext for a function or variable that might be a
5563 /// function-local external declaration.
5564 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5565   if (!DC->isFunctionOrMethod())
5566     return false;
5567 
5568   // If this is a local extern function or variable declared within a function
5569   // template, don't add it into the enclosing namespace scope until it is
5570   // instantiated; it might have a dependent type right now.
5571   if (DC->isDependentContext())
5572     return true;
5573 
5574   // C++11 [basic.link]p7:
5575   //   When a block scope declaration of an entity with linkage is not found to
5576   //   refer to some other declaration, then that entity is a member of the
5577   //   innermost enclosing namespace.
5578   //
5579   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5580   // semantically-enclosing namespace, not a lexically-enclosing one.
5581   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5582     DC = DC->getParent();
5583   return true;
5584 }
5585 
5586 /// \brief Returns true if given declaration has external C language linkage.
5587 static bool isDeclExternC(const Decl *D) {
5588   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5589     return FD->isExternC();
5590   if (const auto *VD = dyn_cast<VarDecl>(D))
5591     return VD->isExternC();
5592 
5593   llvm_unreachable("Unknown type of decl!");
5594 }
5595 
5596 NamedDecl *
5597 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5598                               TypeSourceInfo *TInfo, LookupResult &Previous,
5599                               MultiTemplateParamsArg TemplateParamLists,
5600                               bool &AddToScope) {
5601   QualType R = TInfo->getType();
5602   DeclarationName Name = GetNameForDeclarator(D).getName();
5603 
5604   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5605   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5606 
5607   // dllimport globals without explicit storage class are treated as extern. We
5608   // have to change the storage class this early to get the right DeclContext.
5609   if (SC == SC_None && !DC->isRecord() &&
5610       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5611       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5612     SC = SC_Extern;
5613 
5614   DeclContext *OriginalDC = DC;
5615   bool IsLocalExternDecl = SC == SC_Extern &&
5616                            adjustContextForLocalExternDecl(DC);
5617 
5618   if (getLangOpts().OpenCL) {
5619     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5620     QualType NR = R;
5621     while (NR->isPointerType()) {
5622       if (NR->isFunctionPointerType()) {
5623         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5624         D.setInvalidType();
5625         break;
5626       }
5627       NR = NR->getPointeeType();
5628     }
5629 
5630     if (!getOpenCLOptions().cl_khr_fp16) {
5631       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5632       // half array type (unless the cl_khr_fp16 extension is enabled).
5633       if (Context.getBaseElementType(R)->isHalfType()) {
5634         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5635         D.setInvalidType();
5636       }
5637     }
5638   }
5639 
5640   if (SCSpec == DeclSpec::SCS_mutable) {
5641     // mutable can only appear on non-static class members, so it's always
5642     // an error here
5643     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5644     D.setInvalidType();
5645     SC = SC_None;
5646   }
5647 
5648   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5649       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5650                               D.getDeclSpec().getStorageClassSpecLoc())) {
5651     // In C++11, the 'register' storage class specifier is deprecated.
5652     // Suppress the warning in system macros, it's used in macros in some
5653     // popular C system headers, such as in glibc's htonl() macro.
5654     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5655          diag::warn_deprecated_register)
5656       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5657   }
5658 
5659   IdentifierInfo *II = Name.getAsIdentifierInfo();
5660   if (!II) {
5661     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5662       << Name;
5663     return nullptr;
5664   }
5665 
5666   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5667 
5668   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5669     // C99 6.9p2: The storage-class specifiers auto and register shall not
5670     // appear in the declaration specifiers in an external declaration.
5671     // Global Register+Asm is a GNU extension we support.
5672     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5673       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5674       D.setInvalidType();
5675     }
5676   }
5677 
5678   if (getLangOpts().OpenCL) {
5679     // Set up the special work-group-local storage class for variables in the
5680     // OpenCL __local address space.
5681     if (R.getAddressSpace() == LangAS::opencl_local) {
5682       SC = SC_OpenCLWorkGroupLocal;
5683     }
5684 
5685     // OpenCL v1.2 s6.9.b p4:
5686     // The sampler type cannot be used with the __local and __global address
5687     // space qualifiers.
5688     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5689       R.getAddressSpace() == LangAS::opencl_global)) {
5690       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5691     }
5692 
5693     // OpenCL 1.2 spec, p6.9 r:
5694     // The event type cannot be used to declare a program scope variable.
5695     // The event type cannot be used with the __local, __constant and __global
5696     // address space qualifiers.
5697     if (R->isEventT()) {
5698       if (S->getParent() == nullptr) {
5699         Diag(D.getLocStart(), diag::err_event_t_global_var);
5700         D.setInvalidType();
5701       }
5702 
5703       if (R.getAddressSpace()) {
5704         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5705         D.setInvalidType();
5706       }
5707     }
5708   }
5709 
5710   bool IsExplicitSpecialization = false;
5711   bool IsVariableTemplateSpecialization = false;
5712   bool IsPartialSpecialization = false;
5713   bool IsVariableTemplate = false;
5714   VarDecl *NewVD = nullptr;
5715   VarTemplateDecl *NewTemplate = nullptr;
5716   TemplateParameterList *TemplateParams = nullptr;
5717   if (!getLangOpts().CPlusPlus) {
5718     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5719                             D.getIdentifierLoc(), II,
5720                             R, TInfo, SC);
5721 
5722     if (D.isInvalidType())
5723       NewVD->setInvalidDecl();
5724   } else {
5725     bool Invalid = false;
5726 
5727     if (DC->isRecord() && !CurContext->isRecord()) {
5728       // This is an out-of-line definition of a static data member.
5729       switch (SC) {
5730       case SC_None:
5731         break;
5732       case SC_Static:
5733         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5734              diag::err_static_out_of_line)
5735           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5736         break;
5737       case SC_Auto:
5738       case SC_Register:
5739       case SC_Extern:
5740         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5741         // to names of variables declared in a block or to function parameters.
5742         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5743         // of class members
5744 
5745         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5746              diag::err_storage_class_for_static_member)
5747           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5748         break;
5749       case SC_PrivateExtern:
5750         llvm_unreachable("C storage class in c++!");
5751       case SC_OpenCLWorkGroupLocal:
5752         llvm_unreachable("OpenCL storage class in c++!");
5753       }
5754     }
5755 
5756     if (SC == SC_Static && CurContext->isRecord()) {
5757       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5758         if (RD->isLocalClass())
5759           Diag(D.getIdentifierLoc(),
5760                diag::err_static_data_member_not_allowed_in_local_class)
5761             << Name << RD->getDeclName();
5762 
5763         // C++98 [class.union]p1: If a union contains a static data member,
5764         // the program is ill-formed. C++11 drops this restriction.
5765         if (RD->isUnion())
5766           Diag(D.getIdentifierLoc(),
5767                getLangOpts().CPlusPlus11
5768                  ? diag::warn_cxx98_compat_static_data_member_in_union
5769                  : diag::ext_static_data_member_in_union) << Name;
5770         // We conservatively disallow static data members in anonymous structs.
5771         else if (!RD->getDeclName())
5772           Diag(D.getIdentifierLoc(),
5773                diag::err_static_data_member_not_allowed_in_anon_struct)
5774             << Name << RD->isUnion();
5775       }
5776     }
5777 
5778     // Match up the template parameter lists with the scope specifier, then
5779     // determine whether we have a template or a template specialization.
5780     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5781         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5782         D.getCXXScopeSpec(),
5783         D.getName().getKind() == UnqualifiedId::IK_TemplateId
5784             ? D.getName().TemplateId
5785             : nullptr,
5786         TemplateParamLists,
5787         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5788 
5789     if (TemplateParams) {
5790       if (!TemplateParams->size() &&
5791           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5792         // There is an extraneous 'template<>' for this variable. Complain
5793         // about it, but allow the declaration of the variable.
5794         Diag(TemplateParams->getTemplateLoc(),
5795              diag::err_template_variable_noparams)
5796           << II
5797           << SourceRange(TemplateParams->getTemplateLoc(),
5798                          TemplateParams->getRAngleLoc());
5799         TemplateParams = nullptr;
5800       } else {
5801         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5802           // This is an explicit specialization or a partial specialization.
5803           // FIXME: Check that we can declare a specialization here.
5804           IsVariableTemplateSpecialization = true;
5805           IsPartialSpecialization = TemplateParams->size() > 0;
5806         } else { // if (TemplateParams->size() > 0)
5807           // This is a template declaration.
5808           IsVariableTemplate = true;
5809 
5810           // Check that we can declare a template here.
5811           if (CheckTemplateDeclScope(S, TemplateParams))
5812             return nullptr;
5813 
5814           // Only C++1y supports variable templates (N3651).
5815           Diag(D.getIdentifierLoc(),
5816                getLangOpts().CPlusPlus14
5817                    ? diag::warn_cxx11_compat_variable_template
5818                    : diag::ext_variable_template);
5819         }
5820       }
5821     } else {
5822       assert(
5823           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5824           "should have a 'template<>' for this decl");
5825     }
5826 
5827     if (IsVariableTemplateSpecialization) {
5828       SourceLocation TemplateKWLoc =
5829           TemplateParamLists.size() > 0
5830               ? TemplateParamLists[0]->getTemplateLoc()
5831               : SourceLocation();
5832       DeclResult Res = ActOnVarTemplateSpecialization(
5833           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5834           IsPartialSpecialization);
5835       if (Res.isInvalid())
5836         return nullptr;
5837       NewVD = cast<VarDecl>(Res.get());
5838       AddToScope = false;
5839     } else
5840       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5841                               D.getIdentifierLoc(), II, R, TInfo, SC);
5842 
5843     // If this is supposed to be a variable template, create it as such.
5844     if (IsVariableTemplate) {
5845       NewTemplate =
5846           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5847                                   TemplateParams, NewVD);
5848       NewVD->setDescribedVarTemplate(NewTemplate);
5849     }
5850 
5851     // If this decl has an auto type in need of deduction, make a note of the
5852     // Decl so we can diagnose uses of it in its own initializer.
5853     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5854       ParsingInitForAutoVars.insert(NewVD);
5855 
5856     if (D.isInvalidType() || Invalid) {
5857       NewVD->setInvalidDecl();
5858       if (NewTemplate)
5859         NewTemplate->setInvalidDecl();
5860     }
5861 
5862     SetNestedNameSpecifier(NewVD, D);
5863 
5864     // If we have any template parameter lists that don't directly belong to
5865     // the variable (matching the scope specifier), store them.
5866     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5867     if (TemplateParamLists.size() > VDTemplateParamLists)
5868       NewVD->setTemplateParameterListsInfo(
5869           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
5870 
5871     if (D.getDeclSpec().isConstexprSpecified())
5872       NewVD->setConstexpr(true);
5873 
5874     if (D.getDeclSpec().isConceptSpecified())
5875       NewVD->setConcept(true);
5876   }
5877 
5878   // Set the lexical context. If the declarator has a C++ scope specifier, the
5879   // lexical context will be different from the semantic context.
5880   NewVD->setLexicalDeclContext(CurContext);
5881   if (NewTemplate)
5882     NewTemplate->setLexicalDeclContext(CurContext);
5883 
5884   if (IsLocalExternDecl)
5885     NewVD->setLocalExternDecl();
5886 
5887   bool EmitTLSUnsupportedError = false;
5888   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5889     // C++11 [dcl.stc]p4:
5890     //   When thread_local is applied to a variable of block scope the
5891     //   storage-class-specifier static is implied if it does not appear
5892     //   explicitly.
5893     // Core issue: 'static' is not implied if the variable is declared
5894     //   'extern'.
5895     if (NewVD->hasLocalStorage() &&
5896         (SCSpec != DeclSpec::SCS_unspecified ||
5897          TSCS != DeclSpec::TSCS_thread_local ||
5898          !DC->isFunctionOrMethod()))
5899       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5900            diag::err_thread_non_global)
5901         << DeclSpec::getSpecifierName(TSCS);
5902     else if (!Context.getTargetInfo().isTLSSupported()) {
5903       if (getLangOpts().CUDA) {
5904         // Postpone error emission until we've collected attributes required to
5905         // figure out whether it's a host or device variable and whether the
5906         // error should be ignored.
5907         EmitTLSUnsupportedError = true;
5908         // We still need to mark the variable as TLS so it shows up in AST with
5909         // proper storage class for other tools to use even if we're not going
5910         // to emit any code for it.
5911         NewVD->setTSCSpec(TSCS);
5912       } else
5913         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5914              diag::err_thread_unsupported);
5915     } else
5916       NewVD->setTSCSpec(TSCS);
5917   }
5918 
5919   // C99 6.7.4p3
5920   //   An inline definition of a function with external linkage shall
5921   //   not contain a definition of a modifiable object with static or
5922   //   thread storage duration...
5923   // We only apply this when the function is required to be defined
5924   // elsewhere, i.e. when the function is not 'extern inline'.  Note
5925   // that a local variable with thread storage duration still has to
5926   // be marked 'static'.  Also note that it's possible to get these
5927   // semantics in C++ using __attribute__((gnu_inline)).
5928   if (SC == SC_Static && S->getFnParent() != nullptr &&
5929       !NewVD->getType().isConstQualified()) {
5930     FunctionDecl *CurFD = getCurFunctionDecl();
5931     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5932       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5933            diag::warn_static_local_in_extern_inline);
5934       MaybeSuggestAddingStaticToDecl(CurFD);
5935     }
5936   }
5937 
5938   if (D.getDeclSpec().isModulePrivateSpecified()) {
5939     if (IsVariableTemplateSpecialization)
5940       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5941           << (IsPartialSpecialization ? 1 : 0)
5942           << FixItHint::CreateRemoval(
5943                  D.getDeclSpec().getModulePrivateSpecLoc());
5944     else if (IsExplicitSpecialization)
5945       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5946         << 2
5947         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5948     else if (NewVD->hasLocalStorage())
5949       Diag(NewVD->getLocation(), diag::err_module_private_local)
5950         << 0 << NewVD->getDeclName()
5951         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5952         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5953     else {
5954       NewVD->setModulePrivate();
5955       if (NewTemplate)
5956         NewTemplate->setModulePrivate();
5957     }
5958   }
5959 
5960   // Handle attributes prior to checking for duplicates in MergeVarDecl
5961   ProcessDeclAttributes(S, NewVD, D);
5962 
5963   if (getLangOpts().CUDA) {
5964     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
5965       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5966            diag::err_thread_unsupported);
5967     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5968     // storage [duration]."
5969     if (SC == SC_None && S->getFnParent() != nullptr &&
5970         (NewVD->hasAttr<CUDASharedAttr>() ||
5971          NewVD->hasAttr<CUDAConstantAttr>())) {
5972       NewVD->setStorageClass(SC_Static);
5973     }
5974   }
5975 
5976   // Ensure that dllimport globals without explicit storage class are treated as
5977   // extern. The storage class is set above using parsed attributes. Now we can
5978   // check the VarDecl itself.
5979   assert(!NewVD->hasAttr<DLLImportAttr>() ||
5980          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
5981          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
5982 
5983   // In auto-retain/release, infer strong retension for variables of
5984   // retainable type.
5985   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5986     NewVD->setInvalidDecl();
5987 
5988   // Handle GNU asm-label extension (encoded as an attribute).
5989   if (Expr *E = (Expr*)D.getAsmLabel()) {
5990     // The parser guarantees this is a string.
5991     StringLiteral *SE = cast<StringLiteral>(E);
5992     StringRef Label = SE->getString();
5993     if (S->getFnParent() != nullptr) {
5994       switch (SC) {
5995       case SC_None:
5996       case SC_Auto:
5997         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5998         break;
5999       case SC_Register:
6000         // Local Named register
6001         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6002             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6003           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6004         break;
6005       case SC_Static:
6006       case SC_Extern:
6007       case SC_PrivateExtern:
6008       case SC_OpenCLWorkGroupLocal:
6009         break;
6010       }
6011     } else if (SC == SC_Register) {
6012       // Global Named register
6013       if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6014           DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6015         Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6016       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6017         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6018         NewVD->setInvalidDecl(true);
6019       }
6020     }
6021 
6022     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6023                                                 Context, Label, 0));
6024   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6025     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6026       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6027     if (I != ExtnameUndeclaredIdentifiers.end()) {
6028       if (isDeclExternC(NewVD)) {
6029         NewVD->addAttr(I->second);
6030         ExtnameUndeclaredIdentifiers.erase(I);
6031       } else
6032         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6033             << /*Variable*/1 << NewVD;
6034     }
6035   }
6036 
6037   // Diagnose shadowed variables before filtering for scope.
6038   if (D.getCXXScopeSpec().isEmpty())
6039     CheckShadow(S, NewVD, Previous);
6040 
6041   // Don't consider existing declarations that are in a different
6042   // scope and are out-of-semantic-context declarations (if the new
6043   // declaration has linkage).
6044   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6045                        D.getCXXScopeSpec().isNotEmpty() ||
6046                        IsExplicitSpecialization ||
6047                        IsVariableTemplateSpecialization);
6048 
6049   // Check whether the previous declaration is in the same block scope. This
6050   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6051   if (getLangOpts().CPlusPlus &&
6052       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6053     NewVD->setPreviousDeclInSameBlockScope(
6054         Previous.isSingleResult() && !Previous.isShadowed() &&
6055         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6056 
6057   if (!getLangOpts().CPlusPlus) {
6058     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6059   } else {
6060     // If this is an explicit specialization of a static data member, check it.
6061     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6062         CheckMemberSpecialization(NewVD, Previous))
6063       NewVD->setInvalidDecl();
6064 
6065     // Merge the decl with the existing one if appropriate.
6066     if (!Previous.empty()) {
6067       if (Previous.isSingleResult() &&
6068           isa<FieldDecl>(Previous.getFoundDecl()) &&
6069           D.getCXXScopeSpec().isSet()) {
6070         // The user tried to define a non-static data member
6071         // out-of-line (C++ [dcl.meaning]p1).
6072         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6073           << D.getCXXScopeSpec().getRange();
6074         Previous.clear();
6075         NewVD->setInvalidDecl();
6076       }
6077     } else if (D.getCXXScopeSpec().isSet()) {
6078       // No previous declaration in the qualifying scope.
6079       Diag(D.getIdentifierLoc(), diag::err_no_member)
6080         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6081         << D.getCXXScopeSpec().getRange();
6082       NewVD->setInvalidDecl();
6083     }
6084 
6085     if (!IsVariableTemplateSpecialization)
6086       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6087 
6088     if (NewTemplate) {
6089       VarTemplateDecl *PrevVarTemplate =
6090           NewVD->getPreviousDecl()
6091               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6092               : nullptr;
6093 
6094       // Check the template parameter list of this declaration, possibly
6095       // merging in the template parameter list from the previous variable
6096       // template declaration.
6097       if (CheckTemplateParameterList(
6098               TemplateParams,
6099               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6100                               : nullptr,
6101               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6102                DC->isDependentContext())
6103                   ? TPC_ClassTemplateMember
6104                   : TPC_VarTemplate))
6105         NewVD->setInvalidDecl();
6106 
6107       // If we are providing an explicit specialization of a static variable
6108       // template, make a note of that.
6109       if (PrevVarTemplate &&
6110           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6111         PrevVarTemplate->setMemberSpecialization();
6112     }
6113   }
6114 
6115   ProcessPragmaWeak(S, NewVD);
6116 
6117   // If this is the first declaration of an extern C variable, update
6118   // the map of such variables.
6119   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6120       isIncompleteDeclExternC(*this, NewVD))
6121     RegisterLocallyScopedExternCDecl(NewVD, S);
6122 
6123   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6124     Decl *ManglingContextDecl;
6125     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6126             NewVD->getDeclContext(), ManglingContextDecl)) {
6127       Context.setManglingNumber(
6128           NewVD, MCtx->getManglingNumber(
6129                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6130       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6131     }
6132   }
6133 
6134   // Special handling of variable named 'main'.
6135   if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6136       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6137       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6138 
6139     // C++ [basic.start.main]p3
6140     // A program that declares a variable main at global scope is ill-formed.
6141     if (getLangOpts().CPlusPlus)
6142       Diag(D.getLocStart(), diag::err_main_global_variable);
6143 
6144     // In C, and external-linkage variable named main results in undefined
6145     // behavior.
6146     else if (NewVD->hasExternalFormalLinkage())
6147       Diag(D.getLocStart(), diag::warn_main_redefined);
6148   }
6149 
6150   if (D.isRedeclaration() && !Previous.empty()) {
6151     checkDLLAttributeRedeclaration(
6152         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6153         IsExplicitSpecialization);
6154   }
6155 
6156   if (NewTemplate) {
6157     if (NewVD->isInvalidDecl())
6158       NewTemplate->setInvalidDecl();
6159     ActOnDocumentableDecl(NewTemplate);
6160     return NewTemplate;
6161   }
6162 
6163   return NewVD;
6164 }
6165 
6166 /// \brief Diagnose variable or built-in function shadowing.  Implements
6167 /// -Wshadow.
6168 ///
6169 /// This method is called whenever a VarDecl is added to a "useful"
6170 /// scope.
6171 ///
6172 /// \param S the scope in which the shadowing name is being declared
6173 /// \param R the lookup of the name
6174 ///
6175 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6176   // Return if warning is ignored.
6177   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6178     return;
6179 
6180   // Don't diagnose declarations at file scope.
6181   if (D->hasGlobalStorage())
6182     return;
6183 
6184   DeclContext *NewDC = D->getDeclContext();
6185 
6186   // Only diagnose if we're shadowing an unambiguous field or variable.
6187   if (R.getResultKind() != LookupResult::Found)
6188     return;
6189 
6190   NamedDecl* ShadowedDecl = R.getFoundDecl();
6191   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6192     return;
6193 
6194   // Fields are not shadowed by variables in C++ static methods.
6195   if (isa<FieldDecl>(ShadowedDecl))
6196     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6197       if (MD->isStatic())
6198         return;
6199 
6200   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6201     if (shadowedVar->isExternC()) {
6202       // For shadowing external vars, make sure that we point to the global
6203       // declaration, not a locally scoped extern declaration.
6204       for (auto I : shadowedVar->redecls())
6205         if (I->isFileVarDecl()) {
6206           ShadowedDecl = I;
6207           break;
6208         }
6209     }
6210 
6211   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6212 
6213   // Only warn about certain kinds of shadowing for class members.
6214   if (NewDC && NewDC->isRecord()) {
6215     // In particular, don't warn about shadowing non-class members.
6216     if (!OldDC->isRecord())
6217       return;
6218 
6219     // TODO: should we warn about static data members shadowing
6220     // static data members from base classes?
6221 
6222     // TODO: don't diagnose for inaccessible shadowed members.
6223     // This is hard to do perfectly because we might friend the
6224     // shadowing context, but that's just a false negative.
6225   }
6226 
6227   // Determine what kind of declaration we're shadowing.
6228   unsigned Kind;
6229   if (isa<RecordDecl>(OldDC)) {
6230     if (isa<FieldDecl>(ShadowedDecl))
6231       Kind = 3; // field
6232     else
6233       Kind = 2; // static data member
6234   } else if (OldDC->isFileContext())
6235     Kind = 1; // global
6236   else
6237     Kind = 0; // local
6238 
6239   DeclarationName Name = R.getLookupName();
6240 
6241   // Emit warning and note.
6242   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6243     return;
6244   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6245   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6246 }
6247 
6248 /// \brief Check -Wshadow without the advantage of a previous lookup.
6249 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6250   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6251     return;
6252 
6253   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6254                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6255   LookupName(R, S);
6256   CheckShadow(S, D, R);
6257 }
6258 
6259 /// Check for conflict between this global or extern "C" declaration and
6260 /// previous global or extern "C" declarations. This is only used in C++.
6261 template<typename T>
6262 static bool checkGlobalOrExternCConflict(
6263     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6264   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6265   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6266 
6267   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6268     // The common case: this global doesn't conflict with any extern "C"
6269     // declaration.
6270     return false;
6271   }
6272 
6273   if (Prev) {
6274     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6275       // Both the old and new declarations have C language linkage. This is a
6276       // redeclaration.
6277       Previous.clear();
6278       Previous.addDecl(Prev);
6279       return true;
6280     }
6281 
6282     // This is a global, non-extern "C" declaration, and there is a previous
6283     // non-global extern "C" declaration. Diagnose if this is a variable
6284     // declaration.
6285     if (!isa<VarDecl>(ND))
6286       return false;
6287   } else {
6288     // The declaration is extern "C". Check for any declaration in the
6289     // translation unit which might conflict.
6290     if (IsGlobal) {
6291       // We have already performed the lookup into the translation unit.
6292       IsGlobal = false;
6293       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6294            I != E; ++I) {
6295         if (isa<VarDecl>(*I)) {
6296           Prev = *I;
6297           break;
6298         }
6299       }
6300     } else {
6301       DeclContext::lookup_result R =
6302           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6303       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6304            I != E; ++I) {
6305         if (isa<VarDecl>(*I)) {
6306           Prev = *I;
6307           break;
6308         }
6309         // FIXME: If we have any other entity with this name in global scope,
6310         // the declaration is ill-formed, but that is a defect: it breaks the
6311         // 'stat' hack, for instance. Only variables can have mangled name
6312         // clashes with extern "C" declarations, so only they deserve a
6313         // diagnostic.
6314       }
6315     }
6316 
6317     if (!Prev)
6318       return false;
6319   }
6320 
6321   // Use the first declaration's location to ensure we point at something which
6322   // is lexically inside an extern "C" linkage-spec.
6323   assert(Prev && "should have found a previous declaration to diagnose");
6324   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6325     Prev = FD->getFirstDecl();
6326   else
6327     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6328 
6329   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6330     << IsGlobal << ND;
6331   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6332     << IsGlobal;
6333   return false;
6334 }
6335 
6336 /// Apply special rules for handling extern "C" declarations. Returns \c true
6337 /// if we have found that this is a redeclaration of some prior entity.
6338 ///
6339 /// Per C++ [dcl.link]p6:
6340 ///   Two declarations [for a function or variable] with C language linkage
6341 ///   with the same name that appear in different scopes refer to the same
6342 ///   [entity]. An entity with C language linkage shall not be declared with
6343 ///   the same name as an entity in global scope.
6344 template<typename T>
6345 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6346                                                   LookupResult &Previous) {
6347   if (!S.getLangOpts().CPlusPlus) {
6348     // In C, when declaring a global variable, look for a corresponding 'extern'
6349     // variable declared in function scope. We don't need this in C++, because
6350     // we find local extern decls in the surrounding file-scope DeclContext.
6351     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6352       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6353         Previous.clear();
6354         Previous.addDecl(Prev);
6355         return true;
6356       }
6357     }
6358     return false;
6359   }
6360 
6361   // A declaration in the translation unit can conflict with an extern "C"
6362   // declaration.
6363   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6364     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6365 
6366   // An extern "C" declaration can conflict with a declaration in the
6367   // translation unit or can be a redeclaration of an extern "C" declaration
6368   // in another scope.
6369   if (isIncompleteDeclExternC(S,ND))
6370     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6371 
6372   // Neither global nor extern "C": nothing to do.
6373   return false;
6374 }
6375 
6376 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6377   // If the decl is already known invalid, don't check it.
6378   if (NewVD->isInvalidDecl())
6379     return;
6380 
6381   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6382   QualType T = TInfo->getType();
6383 
6384   // Defer checking an 'auto' type until its initializer is attached.
6385   if (T->isUndeducedType())
6386     return;
6387 
6388   if (NewVD->hasAttrs())
6389     CheckAlignasUnderalignment(NewVD);
6390 
6391   if (T->isObjCObjectType()) {
6392     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6393       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6394     T = Context.getObjCObjectPointerType(T);
6395     NewVD->setType(T);
6396   }
6397 
6398   // Emit an error if an address space was applied to decl with local storage.
6399   // This includes arrays of objects with address space qualifiers, but not
6400   // automatic variables that point to other address spaces.
6401   // ISO/IEC TR 18037 S5.1.2
6402   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6403     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6404     NewVD->setInvalidDecl();
6405     return;
6406   }
6407 
6408   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6409   // __constant address space.
6410   if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
6411       && T.getAddressSpace() != LangAS::opencl_constant
6412       && !T->isSamplerT()){
6413     Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
6414     NewVD->setInvalidDecl();
6415     return;
6416   }
6417 
6418   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6419   // scope.
6420   if ((getLangOpts().OpenCLVersion >= 120)
6421       && NewVD->isStaticLocal()) {
6422     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6423     NewVD->setInvalidDecl();
6424     return;
6425   }
6426 
6427   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6428       && !NewVD->hasAttr<BlocksAttr>()) {
6429     if (getLangOpts().getGC() != LangOptions::NonGC)
6430       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6431     else {
6432       assert(!getLangOpts().ObjCAutoRefCount);
6433       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6434     }
6435   }
6436 
6437   bool isVM = T->isVariablyModifiedType();
6438   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6439       NewVD->hasAttr<BlocksAttr>())
6440     getCurFunction()->setHasBranchProtectedScope();
6441 
6442   if ((isVM && NewVD->hasLinkage()) ||
6443       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6444     bool SizeIsNegative;
6445     llvm::APSInt Oversized;
6446     TypeSourceInfo *FixedTInfo =
6447       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6448                                                     SizeIsNegative, Oversized);
6449     if (!FixedTInfo && T->isVariableArrayType()) {
6450       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6451       // FIXME: This won't give the correct result for
6452       // int a[10][n];
6453       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6454 
6455       if (NewVD->isFileVarDecl())
6456         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6457         << SizeRange;
6458       else if (NewVD->isStaticLocal())
6459         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6460         << SizeRange;
6461       else
6462         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6463         << SizeRange;
6464       NewVD->setInvalidDecl();
6465       return;
6466     }
6467 
6468     if (!FixedTInfo) {
6469       if (NewVD->isFileVarDecl())
6470         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6471       else
6472         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6473       NewVD->setInvalidDecl();
6474       return;
6475     }
6476 
6477     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6478     NewVD->setType(FixedTInfo->getType());
6479     NewVD->setTypeSourceInfo(FixedTInfo);
6480   }
6481 
6482   if (T->isVoidType()) {
6483     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6484     //                    of objects and functions.
6485     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6486       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6487         << T;
6488       NewVD->setInvalidDecl();
6489       return;
6490     }
6491   }
6492 
6493   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6494     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6495     NewVD->setInvalidDecl();
6496     return;
6497   }
6498 
6499   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6500     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6501     NewVD->setInvalidDecl();
6502     return;
6503   }
6504 
6505   if (NewVD->isConstexpr() && !T->isDependentType() &&
6506       RequireLiteralType(NewVD->getLocation(), T,
6507                          diag::err_constexpr_var_non_literal)) {
6508     NewVD->setInvalidDecl();
6509     return;
6510   }
6511 }
6512 
6513 /// \brief Perform semantic checking on a newly-created variable
6514 /// declaration.
6515 ///
6516 /// This routine performs all of the type-checking required for a
6517 /// variable declaration once it has been built. It is used both to
6518 /// check variables after they have been parsed and their declarators
6519 /// have been translated into a declaration, and to check variables
6520 /// that have been instantiated from a template.
6521 ///
6522 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6523 ///
6524 /// Returns true if the variable declaration is a redeclaration.
6525 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6526   CheckVariableDeclarationType(NewVD);
6527 
6528   // If the decl is already known invalid, don't check it.
6529   if (NewVD->isInvalidDecl())
6530     return false;
6531 
6532   // If we did not find anything by this name, look for a non-visible
6533   // extern "C" declaration with the same name.
6534   if (Previous.empty() &&
6535       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6536     Previous.setShadowed();
6537 
6538   if (!Previous.empty()) {
6539     MergeVarDecl(NewVD, Previous);
6540     return true;
6541   }
6542   return false;
6543 }
6544 
6545 namespace {
6546 struct FindOverriddenMethod {
6547   Sema *S;
6548   CXXMethodDecl *Method;
6549 
6550   /// Member lookup function that determines whether a given C++
6551   /// method overrides a method in a base class, to be used with
6552   /// CXXRecordDecl::lookupInBases().
6553   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6554     RecordDecl *BaseRecord =
6555         Specifier->getType()->getAs<RecordType>()->getDecl();
6556 
6557     DeclarationName Name = Method->getDeclName();
6558 
6559     // FIXME: Do we care about other names here too?
6560     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6561       // We really want to find the base class destructor here.
6562       QualType T = S->Context.getTypeDeclType(BaseRecord);
6563       CanQualType CT = S->Context.getCanonicalType(T);
6564 
6565       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
6566     }
6567 
6568     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6569          Path.Decls = Path.Decls.slice(1)) {
6570       NamedDecl *D = Path.Decls.front();
6571       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6572         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
6573           return true;
6574       }
6575     }
6576 
6577     return false;
6578   }
6579 };
6580 
6581 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6582 } // end anonymous namespace
6583 
6584 /// \brief Report an error regarding overriding, along with any relevant
6585 /// overriden methods.
6586 ///
6587 /// \param DiagID the primary error to report.
6588 /// \param MD the overriding method.
6589 /// \param OEK which overrides to include as notes.
6590 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6591                             OverrideErrorKind OEK = OEK_All) {
6592   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6593   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6594                                       E = MD->end_overridden_methods();
6595        I != E; ++I) {
6596     // This check (& the OEK parameter) could be replaced by a predicate, but
6597     // without lambdas that would be overkill. This is still nicer than writing
6598     // out the diag loop 3 times.
6599     if ((OEK == OEK_All) ||
6600         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6601         (OEK == OEK_Deleted && (*I)->isDeleted()))
6602       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6603   }
6604 }
6605 
6606 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6607 /// and if so, check that it's a valid override and remember it.
6608 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6609   // Look for methods in base classes that this method might override.
6610   CXXBasePaths Paths;
6611   FindOverriddenMethod FOM;
6612   FOM.Method = MD;
6613   FOM.S = this;
6614   bool hasDeletedOverridenMethods = false;
6615   bool hasNonDeletedOverridenMethods = false;
6616   bool AddedAny = false;
6617   if (DC->lookupInBases(FOM, Paths)) {
6618     for (auto *I : Paths.found_decls()) {
6619       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6620         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6621         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6622             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6623             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6624             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6625           hasDeletedOverridenMethods |= OldMD->isDeleted();
6626           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6627           AddedAny = true;
6628         }
6629       }
6630     }
6631   }
6632 
6633   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6634     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6635   }
6636   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6637     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6638   }
6639 
6640   return AddedAny;
6641 }
6642 
6643 namespace {
6644   // Struct for holding all of the extra arguments needed by
6645   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6646   struct ActOnFDArgs {
6647     Scope *S;
6648     Declarator &D;
6649     MultiTemplateParamsArg TemplateParamLists;
6650     bool AddToScope;
6651   };
6652 }
6653 
6654 namespace {
6655 
6656 // Callback to only accept typo corrections that have a non-zero edit distance.
6657 // Also only accept corrections that have the same parent decl.
6658 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6659  public:
6660   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6661                             CXXRecordDecl *Parent)
6662       : Context(Context), OriginalFD(TypoFD),
6663         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6664 
6665   bool ValidateCandidate(const TypoCorrection &candidate) override {
6666     if (candidate.getEditDistance() == 0)
6667       return false;
6668 
6669     SmallVector<unsigned, 1> MismatchedParams;
6670     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6671                                           CDeclEnd = candidate.end();
6672          CDecl != CDeclEnd; ++CDecl) {
6673       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6674 
6675       if (FD && !FD->hasBody() &&
6676           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6677         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6678           CXXRecordDecl *Parent = MD->getParent();
6679           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6680             return true;
6681         } else if (!ExpectedParent) {
6682           return true;
6683         }
6684       }
6685     }
6686 
6687     return false;
6688   }
6689 
6690  private:
6691   ASTContext &Context;
6692   FunctionDecl *OriginalFD;
6693   CXXRecordDecl *ExpectedParent;
6694 };
6695 
6696 }
6697 
6698 /// \brief Generate diagnostics for an invalid function redeclaration.
6699 ///
6700 /// This routine handles generating the diagnostic messages for an invalid
6701 /// function redeclaration, including finding possible similar declarations
6702 /// or performing typo correction if there are no previous declarations with
6703 /// the same name.
6704 ///
6705 /// Returns a NamedDecl iff typo correction was performed and substituting in
6706 /// the new declaration name does not cause new errors.
6707 static NamedDecl *DiagnoseInvalidRedeclaration(
6708     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6709     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6710   DeclarationName Name = NewFD->getDeclName();
6711   DeclContext *NewDC = NewFD->getDeclContext();
6712   SmallVector<unsigned, 1> MismatchedParams;
6713   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6714   TypoCorrection Correction;
6715   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6716   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6717                                    : diag::err_member_decl_does_not_match;
6718   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6719                     IsLocalFriend ? Sema::LookupLocalFriendName
6720                                   : Sema::LookupOrdinaryName,
6721                     Sema::ForRedeclaration);
6722 
6723   NewFD->setInvalidDecl();
6724   if (IsLocalFriend)
6725     SemaRef.LookupName(Prev, S);
6726   else
6727     SemaRef.LookupQualifiedName(Prev, NewDC);
6728   assert(!Prev.isAmbiguous() &&
6729          "Cannot have an ambiguity in previous-declaration lookup");
6730   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6731   if (!Prev.empty()) {
6732     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6733          Func != FuncEnd; ++Func) {
6734       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6735       if (FD &&
6736           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6737         // Add 1 to the index so that 0 can mean the mismatch didn't
6738         // involve a parameter
6739         unsigned ParamNum =
6740             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6741         NearMatches.push_back(std::make_pair(FD, ParamNum));
6742       }
6743     }
6744   // If the qualified name lookup yielded nothing, try typo correction
6745   } else if ((Correction = SemaRef.CorrectTypo(
6746                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6747                   &ExtraArgs.D.getCXXScopeSpec(),
6748                   llvm::make_unique<DifferentNameValidatorCCC>(
6749                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
6750                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6751     // Set up everything for the call to ActOnFunctionDeclarator
6752     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6753                               ExtraArgs.D.getIdentifierLoc());
6754     Previous.clear();
6755     Previous.setLookupName(Correction.getCorrection());
6756     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6757                                     CDeclEnd = Correction.end();
6758          CDecl != CDeclEnd; ++CDecl) {
6759       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6760       if (FD && !FD->hasBody() &&
6761           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6762         Previous.addDecl(FD);
6763       }
6764     }
6765     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6766 
6767     NamedDecl *Result;
6768     // Retry building the function declaration with the new previous
6769     // declarations, and with errors suppressed.
6770     {
6771       // Trap errors.
6772       Sema::SFINAETrap Trap(SemaRef);
6773 
6774       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6775       // pieces need to verify the typo-corrected C++ declaration and hopefully
6776       // eliminate the need for the parameter pack ExtraArgs.
6777       Result = SemaRef.ActOnFunctionDeclarator(
6778           ExtraArgs.S, ExtraArgs.D,
6779           Correction.getCorrectionDecl()->getDeclContext(),
6780           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6781           ExtraArgs.AddToScope);
6782 
6783       if (Trap.hasErrorOccurred())
6784         Result = nullptr;
6785     }
6786 
6787     if (Result) {
6788       // Determine which correction we picked.
6789       Decl *Canonical = Result->getCanonicalDecl();
6790       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6791            I != E; ++I)
6792         if ((*I)->getCanonicalDecl() == Canonical)
6793           Correction.setCorrectionDecl(*I);
6794 
6795       SemaRef.diagnoseTypo(
6796           Correction,
6797           SemaRef.PDiag(IsLocalFriend
6798                           ? diag::err_no_matching_local_friend_suggest
6799                           : diag::err_member_decl_does_not_match_suggest)
6800             << Name << NewDC << IsDefinition);
6801       return Result;
6802     }
6803 
6804     // Pretend the typo correction never occurred
6805     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6806                               ExtraArgs.D.getIdentifierLoc());
6807     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6808     Previous.clear();
6809     Previous.setLookupName(Name);
6810   }
6811 
6812   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6813       << Name << NewDC << IsDefinition << NewFD->getLocation();
6814 
6815   bool NewFDisConst = false;
6816   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6817     NewFDisConst = NewMD->isConst();
6818 
6819   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6820        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6821        NearMatch != NearMatchEnd; ++NearMatch) {
6822     FunctionDecl *FD = NearMatch->first;
6823     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6824     bool FDisConst = MD && MD->isConst();
6825     bool IsMember = MD || !IsLocalFriend;
6826 
6827     // FIXME: These notes are poorly worded for the local friend case.
6828     if (unsigned Idx = NearMatch->second) {
6829       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6830       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6831       if (Loc.isInvalid()) Loc = FD->getLocation();
6832       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6833                                  : diag::note_local_decl_close_param_match)
6834         << Idx << FDParam->getType()
6835         << NewFD->getParamDecl(Idx - 1)->getType();
6836     } else if (FDisConst != NewFDisConst) {
6837       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6838           << NewFDisConst << FD->getSourceRange().getEnd();
6839     } else
6840       SemaRef.Diag(FD->getLocation(),
6841                    IsMember ? diag::note_member_def_close_match
6842                             : diag::note_local_decl_close_match);
6843   }
6844   return nullptr;
6845 }
6846 
6847 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
6848   switch (D.getDeclSpec().getStorageClassSpec()) {
6849   default: llvm_unreachable("Unknown storage class!");
6850   case DeclSpec::SCS_auto:
6851   case DeclSpec::SCS_register:
6852   case DeclSpec::SCS_mutable:
6853     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6854                  diag::err_typecheck_sclass_func);
6855     D.setInvalidType();
6856     break;
6857   case DeclSpec::SCS_unspecified: break;
6858   case DeclSpec::SCS_extern:
6859     if (D.getDeclSpec().isExternInLinkageSpec())
6860       return SC_None;
6861     return SC_Extern;
6862   case DeclSpec::SCS_static: {
6863     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6864       // C99 6.7.1p5:
6865       //   The declaration of an identifier for a function that has
6866       //   block scope shall have no explicit storage-class specifier
6867       //   other than extern
6868       // See also (C++ [dcl.stc]p4).
6869       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6870                    diag::err_static_block_func);
6871       break;
6872     } else
6873       return SC_Static;
6874   }
6875   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6876   }
6877 
6878   // No explicit storage class has already been returned
6879   return SC_None;
6880 }
6881 
6882 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6883                                            DeclContext *DC, QualType &R,
6884                                            TypeSourceInfo *TInfo,
6885                                            StorageClass SC,
6886                                            bool &IsVirtualOkay) {
6887   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6888   DeclarationName Name = NameInfo.getName();
6889 
6890   FunctionDecl *NewFD = nullptr;
6891   bool isInline = D.getDeclSpec().isInlineSpecified();
6892 
6893   if (!SemaRef.getLangOpts().CPlusPlus) {
6894     // Determine whether the function was written with a
6895     // prototype. This true when:
6896     //   - there is a prototype in the declarator, or
6897     //   - the type R of the function is some kind of typedef or other reference
6898     //     to a type name (which eventually refers to a function type).
6899     bool HasPrototype =
6900       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6901       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6902 
6903     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6904                                  D.getLocStart(), NameInfo, R,
6905                                  TInfo, SC, isInline,
6906                                  HasPrototype, false);
6907     if (D.isInvalidType())
6908       NewFD->setInvalidDecl();
6909 
6910     return NewFD;
6911   }
6912 
6913   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6914   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6915 
6916   // Check that the return type is not an abstract class type.
6917   // For record types, this is done by the AbstractClassUsageDiagnoser once
6918   // the class has been completely parsed.
6919   if (!DC->isRecord() &&
6920       SemaRef.RequireNonAbstractType(
6921           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6922           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
6923     D.setInvalidType();
6924 
6925   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6926     // This is a C++ constructor declaration.
6927     assert(DC->isRecord() &&
6928            "Constructors can only be declared in a member context");
6929 
6930     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6931     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6932                                       D.getLocStart(), NameInfo,
6933                                       R, TInfo, isExplicit, isInline,
6934                                       /*isImplicitlyDeclared=*/false,
6935                                       isConstexpr);
6936 
6937   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6938     // This is a C++ destructor declaration.
6939     if (DC->isRecord()) {
6940       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6941       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6942       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6943                                         SemaRef.Context, Record,
6944                                         D.getLocStart(),
6945                                         NameInfo, R, TInfo, isInline,
6946                                         /*isImplicitlyDeclared=*/false);
6947 
6948       // If the class is complete, then we now create the implicit exception
6949       // specification. If the class is incomplete or dependent, we can't do
6950       // it yet.
6951       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6952           Record->getDefinition() && !Record->isBeingDefined() &&
6953           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6954         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6955       }
6956 
6957       IsVirtualOkay = true;
6958       return NewDD;
6959 
6960     } else {
6961       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6962       D.setInvalidType();
6963 
6964       // Create a FunctionDecl to satisfy the function definition parsing
6965       // code path.
6966       return FunctionDecl::Create(SemaRef.Context, DC,
6967                                   D.getLocStart(),
6968                                   D.getIdentifierLoc(), Name, R, TInfo,
6969                                   SC, isInline,
6970                                   /*hasPrototype=*/true, isConstexpr);
6971     }
6972 
6973   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6974     if (!DC->isRecord()) {
6975       SemaRef.Diag(D.getIdentifierLoc(),
6976            diag::err_conv_function_not_member);
6977       return nullptr;
6978     }
6979 
6980     SemaRef.CheckConversionDeclarator(D, R, SC);
6981     IsVirtualOkay = true;
6982     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6983                                      D.getLocStart(), NameInfo,
6984                                      R, TInfo, isInline, isExplicit,
6985                                      isConstexpr, SourceLocation());
6986 
6987   } else if (DC->isRecord()) {
6988     // If the name of the function is the same as the name of the record,
6989     // then this must be an invalid constructor that has a return type.
6990     // (The parser checks for a return type and makes the declarator a
6991     // constructor if it has no return type).
6992     if (Name.getAsIdentifierInfo() &&
6993         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6994       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6995         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6996         << SourceRange(D.getIdentifierLoc());
6997       return nullptr;
6998     }
6999 
7000     // This is a C++ method declaration.
7001     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7002                                                cast<CXXRecordDecl>(DC),
7003                                                D.getLocStart(), NameInfo, R,
7004                                                TInfo, SC, isInline,
7005                                                isConstexpr, SourceLocation());
7006     IsVirtualOkay = !Ret->isStatic();
7007     return Ret;
7008   } else {
7009     bool isFriend =
7010         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7011     if (!isFriend && SemaRef.CurContext->isRecord())
7012       return nullptr;
7013 
7014     // Determine whether the function was written with a
7015     // prototype. This true when:
7016     //   - we're in C++ (where every function has a prototype),
7017     return FunctionDecl::Create(SemaRef.Context, DC,
7018                                 D.getLocStart(),
7019                                 NameInfo, R, TInfo, SC, isInline,
7020                                 true/*HasPrototype*/, isConstexpr);
7021   }
7022 }
7023 
7024 enum OpenCLParamType {
7025   ValidKernelParam,
7026   PtrPtrKernelParam,
7027   PtrKernelParam,
7028   PrivatePtrKernelParam,
7029   InvalidKernelParam,
7030   RecordKernelParam
7031 };
7032 
7033 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7034   if (PT->isPointerType()) {
7035     QualType PointeeType = PT->getPointeeType();
7036     if (PointeeType->isPointerType())
7037       return PtrPtrKernelParam;
7038     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7039                                               : PtrKernelParam;
7040   }
7041 
7042   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7043   // be used as builtin types.
7044 
7045   if (PT->isImageType())
7046     return PtrKernelParam;
7047 
7048   if (PT->isBooleanType())
7049     return InvalidKernelParam;
7050 
7051   if (PT->isEventT())
7052     return InvalidKernelParam;
7053 
7054   if (PT->isHalfType())
7055     return InvalidKernelParam;
7056 
7057   if (PT->isRecordType())
7058     return RecordKernelParam;
7059 
7060   return ValidKernelParam;
7061 }
7062 
7063 static void checkIsValidOpenCLKernelParameter(
7064   Sema &S,
7065   Declarator &D,
7066   ParmVarDecl *Param,
7067   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7068   QualType PT = Param->getType();
7069 
7070   // Cache the valid types we encounter to avoid rechecking structs that are
7071   // used again
7072   if (ValidTypes.count(PT.getTypePtr()))
7073     return;
7074 
7075   switch (getOpenCLKernelParameterType(PT)) {
7076   case PtrPtrKernelParam:
7077     // OpenCL v1.2 s6.9.a:
7078     // A kernel function argument cannot be declared as a
7079     // pointer to a pointer type.
7080     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7081     D.setInvalidType();
7082     return;
7083 
7084   case PrivatePtrKernelParam:
7085     // OpenCL v1.2 s6.9.a:
7086     // A kernel function argument cannot be declared as a
7087     // pointer to the private address space.
7088     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7089     D.setInvalidType();
7090     return;
7091 
7092     // OpenCL v1.2 s6.9.k:
7093     // Arguments to kernel functions in a program cannot be declared with the
7094     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7095     // uintptr_t or a struct and/or union that contain fields declared to be
7096     // one of these built-in scalar types.
7097 
7098   case InvalidKernelParam:
7099     // OpenCL v1.2 s6.8 n:
7100     // A kernel function argument cannot be declared
7101     // of event_t type.
7102     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7103     D.setInvalidType();
7104     return;
7105 
7106   case PtrKernelParam:
7107   case ValidKernelParam:
7108     ValidTypes.insert(PT.getTypePtr());
7109     return;
7110 
7111   case RecordKernelParam:
7112     break;
7113   }
7114 
7115   // Track nested structs we will inspect
7116   SmallVector<const Decl *, 4> VisitStack;
7117 
7118   // Track where we are in the nested structs. Items will migrate from
7119   // VisitStack to HistoryStack as we do the DFS for bad field.
7120   SmallVector<const FieldDecl *, 4> HistoryStack;
7121   HistoryStack.push_back(nullptr);
7122 
7123   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7124   VisitStack.push_back(PD);
7125 
7126   assert(VisitStack.back() && "First decl null?");
7127 
7128   do {
7129     const Decl *Next = VisitStack.pop_back_val();
7130     if (!Next) {
7131       assert(!HistoryStack.empty());
7132       // Found a marker, we have gone up a level
7133       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7134         ValidTypes.insert(Hist->getType().getTypePtr());
7135 
7136       continue;
7137     }
7138 
7139     // Adds everything except the original parameter declaration (which is not a
7140     // field itself) to the history stack.
7141     const RecordDecl *RD;
7142     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7143       HistoryStack.push_back(Field);
7144       RD = Field->getType()->castAs<RecordType>()->getDecl();
7145     } else {
7146       RD = cast<RecordDecl>(Next);
7147     }
7148 
7149     // Add a null marker so we know when we've gone back up a level
7150     VisitStack.push_back(nullptr);
7151 
7152     for (const auto *FD : RD->fields()) {
7153       QualType QT = FD->getType();
7154 
7155       if (ValidTypes.count(QT.getTypePtr()))
7156         continue;
7157 
7158       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7159       if (ParamType == ValidKernelParam)
7160         continue;
7161 
7162       if (ParamType == RecordKernelParam) {
7163         VisitStack.push_back(FD);
7164         continue;
7165       }
7166 
7167       // OpenCL v1.2 s6.9.p:
7168       // Arguments to kernel functions that are declared to be a struct or union
7169       // do not allow OpenCL objects to be passed as elements of the struct or
7170       // union.
7171       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7172           ParamType == PrivatePtrKernelParam) {
7173         S.Diag(Param->getLocation(),
7174                diag::err_record_with_pointers_kernel_param)
7175           << PT->isUnionType()
7176           << PT;
7177       } else {
7178         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7179       }
7180 
7181       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7182         << PD->getDeclName();
7183 
7184       // We have an error, now let's go back up through history and show where
7185       // the offending field came from
7186       for (ArrayRef<const FieldDecl *>::const_iterator
7187                I = HistoryStack.begin() + 1,
7188                E = HistoryStack.end();
7189            I != E; ++I) {
7190         const FieldDecl *OuterField = *I;
7191         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7192           << OuterField->getType();
7193       }
7194 
7195       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7196         << QT->isPointerType()
7197         << QT;
7198       D.setInvalidType();
7199       return;
7200     }
7201   } while (!VisitStack.empty());
7202 }
7203 
7204 NamedDecl*
7205 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7206                               TypeSourceInfo *TInfo, LookupResult &Previous,
7207                               MultiTemplateParamsArg TemplateParamLists,
7208                               bool &AddToScope) {
7209   QualType R = TInfo->getType();
7210 
7211   assert(R.getTypePtr()->isFunctionType());
7212 
7213   // TODO: consider using NameInfo for diagnostic.
7214   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7215   DeclarationName Name = NameInfo.getName();
7216   StorageClass SC = getFunctionStorageClass(*this, D);
7217 
7218   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7219     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7220          diag::err_invalid_thread)
7221       << DeclSpec::getSpecifierName(TSCS);
7222 
7223   if (D.isFirstDeclarationOfMember())
7224     adjustMemberFunctionCC(R, D.isStaticMember());
7225 
7226   bool isFriend = false;
7227   FunctionTemplateDecl *FunctionTemplate = nullptr;
7228   bool isExplicitSpecialization = false;
7229   bool isFunctionTemplateSpecialization = false;
7230 
7231   bool isDependentClassScopeExplicitSpecialization = false;
7232   bool HasExplicitTemplateArgs = false;
7233   TemplateArgumentListInfo TemplateArgs;
7234 
7235   bool isVirtualOkay = false;
7236 
7237   DeclContext *OriginalDC = DC;
7238   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7239 
7240   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7241                                               isVirtualOkay);
7242   if (!NewFD) return nullptr;
7243 
7244   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7245     NewFD->setTopLevelDeclInObjCContainer();
7246 
7247   // Set the lexical context. If this is a function-scope declaration, or has a
7248   // C++ scope specifier, or is the object of a friend declaration, the lexical
7249   // context will be different from the semantic context.
7250   NewFD->setLexicalDeclContext(CurContext);
7251 
7252   if (IsLocalExternDecl)
7253     NewFD->setLocalExternDecl();
7254 
7255   if (getLangOpts().CPlusPlus) {
7256     bool isInline = D.getDeclSpec().isInlineSpecified();
7257     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7258     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7259     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7260     bool isConcept = D.getDeclSpec().isConceptSpecified();
7261     isFriend = D.getDeclSpec().isFriendSpecified();
7262     if (isFriend && !isInline && D.isFunctionDefinition()) {
7263       // C++ [class.friend]p5
7264       //   A function can be defined in a friend declaration of a
7265       //   class . . . . Such a function is implicitly inline.
7266       NewFD->setImplicitlyInline();
7267     }
7268 
7269     // If this is a method defined in an __interface, and is not a constructor
7270     // or an overloaded operator, then set the pure flag (isVirtual will already
7271     // return true).
7272     if (const CXXRecordDecl *Parent =
7273           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7274       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7275         NewFD->setPure(true);
7276 
7277       // C++ [class.union]p2
7278       //   A union can have member functions, but not virtual functions.
7279       if (isVirtual && Parent->isUnion())
7280         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7281     }
7282 
7283     SetNestedNameSpecifier(NewFD, D);
7284     isExplicitSpecialization = false;
7285     isFunctionTemplateSpecialization = false;
7286     if (D.isInvalidType())
7287       NewFD->setInvalidDecl();
7288 
7289     // Match up the template parameter lists with the scope specifier, then
7290     // determine whether we have a template or a template specialization.
7291     bool Invalid = false;
7292     if (TemplateParameterList *TemplateParams =
7293             MatchTemplateParametersToScopeSpecifier(
7294                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7295                 D.getCXXScopeSpec(),
7296                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7297                     ? D.getName().TemplateId
7298                     : nullptr,
7299                 TemplateParamLists, isFriend, isExplicitSpecialization,
7300                 Invalid)) {
7301       if (TemplateParams->size() > 0) {
7302         // This is a function template
7303 
7304         // Check that we can declare a template here.
7305         if (CheckTemplateDeclScope(S, TemplateParams))
7306           NewFD->setInvalidDecl();
7307 
7308         // A destructor cannot be a template.
7309         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7310           Diag(NewFD->getLocation(), diag::err_destructor_template);
7311           NewFD->setInvalidDecl();
7312         }
7313 
7314         // If we're adding a template to a dependent context, we may need to
7315         // rebuilding some of the types used within the template parameter list,
7316         // now that we know what the current instantiation is.
7317         if (DC->isDependentContext()) {
7318           ContextRAII SavedContext(*this, DC);
7319           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7320             Invalid = true;
7321         }
7322 
7323 
7324         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7325                                                         NewFD->getLocation(),
7326                                                         Name, TemplateParams,
7327                                                         NewFD);
7328         FunctionTemplate->setLexicalDeclContext(CurContext);
7329         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7330 
7331         // For source fidelity, store the other template param lists.
7332         if (TemplateParamLists.size() > 1) {
7333           NewFD->setTemplateParameterListsInfo(Context,
7334                                                TemplateParamLists.drop_back(1));
7335         }
7336       } else {
7337         // This is a function template specialization.
7338         isFunctionTemplateSpecialization = true;
7339         // For source fidelity, store all the template param lists.
7340         if (TemplateParamLists.size() > 0)
7341           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7342 
7343         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7344         if (isFriend) {
7345           // We want to remove the "template<>", found here.
7346           SourceRange RemoveRange = TemplateParams->getSourceRange();
7347 
7348           // If we remove the template<> and the name is not a
7349           // template-id, we're actually silently creating a problem:
7350           // the friend declaration will refer to an untemplated decl,
7351           // and clearly the user wants a template specialization.  So
7352           // we need to insert '<>' after the name.
7353           SourceLocation InsertLoc;
7354           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7355             InsertLoc = D.getName().getSourceRange().getEnd();
7356             InsertLoc = getLocForEndOfToken(InsertLoc);
7357           }
7358 
7359           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7360             << Name << RemoveRange
7361             << FixItHint::CreateRemoval(RemoveRange)
7362             << FixItHint::CreateInsertion(InsertLoc, "<>");
7363         }
7364       }
7365     }
7366     else {
7367       // All template param lists were matched against the scope specifier:
7368       // this is NOT (an explicit specialization of) a template.
7369       if (TemplateParamLists.size() > 0)
7370         // For source fidelity, store all the template param lists.
7371         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7372     }
7373 
7374     if (Invalid) {
7375       NewFD->setInvalidDecl();
7376       if (FunctionTemplate)
7377         FunctionTemplate->setInvalidDecl();
7378     }
7379 
7380     // C++ [dcl.fct.spec]p5:
7381     //   The virtual specifier shall only be used in declarations of
7382     //   nonstatic class member functions that appear within a
7383     //   member-specification of a class declaration; see 10.3.
7384     //
7385     if (isVirtual && !NewFD->isInvalidDecl()) {
7386       if (!isVirtualOkay) {
7387         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7388              diag::err_virtual_non_function);
7389       } else if (!CurContext->isRecord()) {
7390         // 'virtual' was specified outside of the class.
7391         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7392              diag::err_virtual_out_of_class)
7393           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7394       } else if (NewFD->getDescribedFunctionTemplate()) {
7395         // C++ [temp.mem]p3:
7396         //  A member function template shall not be virtual.
7397         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7398              diag::err_virtual_member_function_template)
7399           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7400       } else {
7401         // Okay: Add virtual to the method.
7402         NewFD->setVirtualAsWritten(true);
7403       }
7404 
7405       if (getLangOpts().CPlusPlus14 &&
7406           NewFD->getReturnType()->isUndeducedType())
7407         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7408     }
7409 
7410     if (getLangOpts().CPlusPlus14 &&
7411         (NewFD->isDependentContext() ||
7412          (isFriend && CurContext->isDependentContext())) &&
7413         NewFD->getReturnType()->isUndeducedType()) {
7414       // If the function template is referenced directly (for instance, as a
7415       // member of the current instantiation), pretend it has a dependent type.
7416       // This is not really justified by the standard, but is the only sane
7417       // thing to do.
7418       // FIXME: For a friend function, we have not marked the function as being
7419       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7420       const FunctionProtoType *FPT =
7421           NewFD->getType()->castAs<FunctionProtoType>();
7422       QualType Result =
7423           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7424       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7425                                              FPT->getExtProtoInfo()));
7426     }
7427 
7428     // C++ [dcl.fct.spec]p3:
7429     //  The inline specifier shall not appear on a block scope function
7430     //  declaration.
7431     if (isInline && !NewFD->isInvalidDecl()) {
7432       if (CurContext->isFunctionOrMethod()) {
7433         // 'inline' is not allowed on block scope function declaration.
7434         Diag(D.getDeclSpec().getInlineSpecLoc(),
7435              diag::err_inline_declaration_block_scope) << Name
7436           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7437       }
7438     }
7439 
7440     // C++ [dcl.fct.spec]p6:
7441     //  The explicit specifier shall be used only in the declaration of a
7442     //  constructor or conversion function within its class definition;
7443     //  see 12.3.1 and 12.3.2.
7444     if (isExplicit && !NewFD->isInvalidDecl()) {
7445       if (!CurContext->isRecord()) {
7446         // 'explicit' was specified outside of the class.
7447         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7448              diag::err_explicit_out_of_class)
7449           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7450       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7451                  !isa<CXXConversionDecl>(NewFD)) {
7452         // 'explicit' was specified on a function that wasn't a constructor
7453         // or conversion function.
7454         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7455              diag::err_explicit_non_ctor_or_conv_function)
7456           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7457       }
7458     }
7459 
7460     if (isConstexpr) {
7461       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7462       // are implicitly inline.
7463       NewFD->setImplicitlyInline();
7464 
7465       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7466       // be either constructors or to return a literal type. Therefore,
7467       // destructors cannot be declared constexpr.
7468       if (isa<CXXDestructorDecl>(NewFD))
7469         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7470     }
7471 
7472     if (isConcept) {
7473       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7474       // applied only to the definition of a function template [...]
7475       if (!D.isFunctionDefinition()) {
7476         Diag(D.getDeclSpec().getConceptSpecLoc(),
7477              diag::err_function_concept_not_defined);
7478         NewFD->setInvalidDecl();
7479       }
7480 
7481       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7482       // have no exception-specification and is treated as if it were specified
7483       // with noexcept(true) (15.4). [...]
7484       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7485         if (FPT->hasExceptionSpec()) {
7486           SourceRange Range;
7487           if (D.isFunctionDeclarator())
7488             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7489           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7490               << FixItHint::CreateRemoval(Range);
7491           NewFD->setInvalidDecl();
7492         } else {
7493           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7494         }
7495       }
7496 
7497       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7498       // implicity defined to be a constexpr declaration (implicitly inline)
7499       NewFD->setImplicitlyInline();
7500     }
7501 
7502     // If __module_private__ was specified, mark the function accordingly.
7503     if (D.getDeclSpec().isModulePrivateSpecified()) {
7504       if (isFunctionTemplateSpecialization) {
7505         SourceLocation ModulePrivateLoc
7506           = D.getDeclSpec().getModulePrivateSpecLoc();
7507         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7508           << 0
7509           << FixItHint::CreateRemoval(ModulePrivateLoc);
7510       } else {
7511         NewFD->setModulePrivate();
7512         if (FunctionTemplate)
7513           FunctionTemplate->setModulePrivate();
7514       }
7515     }
7516 
7517     if (isFriend) {
7518       if (FunctionTemplate) {
7519         FunctionTemplate->setObjectOfFriendDecl();
7520         FunctionTemplate->setAccess(AS_public);
7521       }
7522       NewFD->setObjectOfFriendDecl();
7523       NewFD->setAccess(AS_public);
7524     }
7525 
7526     // If a function is defined as defaulted or deleted, mark it as such now.
7527     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7528     // definition kind to FDK_Definition.
7529     switch (D.getFunctionDefinitionKind()) {
7530       case FDK_Declaration:
7531       case FDK_Definition:
7532         break;
7533 
7534       case FDK_Defaulted:
7535         NewFD->setDefaulted();
7536         break;
7537 
7538       case FDK_Deleted:
7539         NewFD->setDeletedAsWritten();
7540         break;
7541     }
7542 
7543     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7544         D.isFunctionDefinition()) {
7545       // C++ [class.mfct]p2:
7546       //   A member function may be defined (8.4) in its class definition, in
7547       //   which case it is an inline member function (7.1.2)
7548       NewFD->setImplicitlyInline();
7549     }
7550 
7551     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7552         !CurContext->isRecord()) {
7553       // C++ [class.static]p1:
7554       //   A data or function member of a class may be declared static
7555       //   in a class definition, in which case it is a static member of
7556       //   the class.
7557 
7558       // Complain about the 'static' specifier if it's on an out-of-line
7559       // member function definition.
7560       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7561            diag::err_static_out_of_line)
7562         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7563     }
7564 
7565     // C++11 [except.spec]p15:
7566     //   A deallocation function with no exception-specification is treated
7567     //   as if it were specified with noexcept(true).
7568     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7569     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7570          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7571         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7572       NewFD->setType(Context.getFunctionType(
7573           FPT->getReturnType(), FPT->getParamTypes(),
7574           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7575   }
7576 
7577   // Filter out previous declarations that don't match the scope.
7578   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7579                        D.getCXXScopeSpec().isNotEmpty() ||
7580                        isExplicitSpecialization ||
7581                        isFunctionTemplateSpecialization);
7582 
7583   // Handle GNU asm-label extension (encoded as an attribute).
7584   if (Expr *E = (Expr*) D.getAsmLabel()) {
7585     // The parser guarantees this is a string.
7586     StringLiteral *SE = cast<StringLiteral>(E);
7587     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7588                                                 SE->getString(), 0));
7589   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7590     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7591       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7592     if (I != ExtnameUndeclaredIdentifiers.end()) {
7593       if (isDeclExternC(NewFD)) {
7594         NewFD->addAttr(I->second);
7595         ExtnameUndeclaredIdentifiers.erase(I);
7596       } else
7597         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
7598             << /*Variable*/0 << NewFD;
7599     }
7600   }
7601 
7602   // Copy the parameter declarations from the declarator D to the function
7603   // declaration NewFD, if they are available.  First scavenge them into Params.
7604   SmallVector<ParmVarDecl*, 16> Params;
7605   if (D.isFunctionDeclarator()) {
7606     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7607 
7608     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7609     // function that takes no arguments, not a function that takes a
7610     // single void argument.
7611     // We let through "const void" here because Sema::GetTypeForDeclarator
7612     // already checks for that case.
7613     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7614       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7615         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7616         assert(Param->getDeclContext() != NewFD && "Was set before ?");
7617         Param->setDeclContext(NewFD);
7618         Params.push_back(Param);
7619 
7620         if (Param->isInvalidDecl())
7621           NewFD->setInvalidDecl();
7622       }
7623     }
7624 
7625   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7626     // When we're declaring a function with a typedef, typeof, etc as in the
7627     // following example, we'll need to synthesize (unnamed)
7628     // parameters for use in the declaration.
7629     //
7630     // @code
7631     // typedef void fn(int);
7632     // fn f;
7633     // @endcode
7634 
7635     // Synthesize a parameter for each argument type.
7636     for (const auto &AI : FT->param_types()) {
7637       ParmVarDecl *Param =
7638           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7639       Param->setScopeInfo(0, Params.size());
7640       Params.push_back(Param);
7641     }
7642   } else {
7643     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7644            "Should not need args for typedef of non-prototype fn");
7645   }
7646 
7647   // Finally, we know we have the right number of parameters, install them.
7648   NewFD->setParams(Params);
7649 
7650   // Find all anonymous symbols defined during the declaration of this function
7651   // and add to NewFD. This lets us track decls such 'enum Y' in:
7652   //
7653   //   void f(enum Y {AA} x) {}
7654   //
7655   // which would otherwise incorrectly end up in the translation unit scope.
7656   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7657   DeclsInPrototypeScope.clear();
7658 
7659   if (D.getDeclSpec().isNoreturnSpecified())
7660     NewFD->addAttr(
7661         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7662                                        Context, 0));
7663 
7664   // Functions returning a variably modified type violate C99 6.7.5.2p2
7665   // because all functions have linkage.
7666   if (!NewFD->isInvalidDecl() &&
7667       NewFD->getReturnType()->isVariablyModifiedType()) {
7668     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7669     NewFD->setInvalidDecl();
7670   }
7671 
7672   // Apply an implicit SectionAttr if #pragma code_seg is active.
7673   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
7674       !NewFD->hasAttr<SectionAttr>()) {
7675     NewFD->addAttr(
7676         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7677                                     CodeSegStack.CurrentValue->getString(),
7678                                     CodeSegStack.CurrentPragmaLocation));
7679     if (UnifySection(CodeSegStack.CurrentValue->getString(),
7680                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
7681                          ASTContext::PSF_Read,
7682                      NewFD))
7683       NewFD->dropAttr<SectionAttr>();
7684   }
7685 
7686   // Handle attributes.
7687   ProcessDeclAttributes(S, NewFD, D);
7688 
7689   if (getLangOpts().OpenCL) {
7690     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7691     // type declaration will generate a compilation error.
7692     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
7693     if (AddressSpace == LangAS::opencl_local ||
7694         AddressSpace == LangAS::opencl_global ||
7695         AddressSpace == LangAS::opencl_constant) {
7696       Diag(NewFD->getLocation(),
7697            diag::err_opencl_return_value_with_address_space);
7698       NewFD->setInvalidDecl();
7699     }
7700   }
7701 
7702   if (!getLangOpts().CPlusPlus) {
7703     // Perform semantic checking on the function declaration.
7704     bool isExplicitSpecialization=false;
7705     if (!NewFD->isInvalidDecl() && NewFD->isMain())
7706       CheckMain(NewFD, D.getDeclSpec());
7707 
7708     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7709       CheckMSVCRTEntryPoint(NewFD);
7710 
7711     if (!NewFD->isInvalidDecl())
7712       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7713                                                   isExplicitSpecialization));
7714     else if (!Previous.empty())
7715       // Recover gracefully from an invalid redeclaration.
7716       D.setRedeclaration(true);
7717     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7718             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7719            "previous declaration set still overloaded");
7720 
7721     // Diagnose no-prototype function declarations with calling conventions that
7722     // don't support variadic calls. Only do this in C and do it after merging
7723     // possibly prototyped redeclarations.
7724     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
7725     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
7726       CallingConv CC = FT->getExtInfo().getCC();
7727       if (!supportsVariadicCall(CC)) {
7728         // Windows system headers sometimes accidentally use stdcall without
7729         // (void) parameters, so we relax this to a warning.
7730         int DiagID =
7731             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
7732         Diag(NewFD->getLocation(), DiagID)
7733             << FunctionType::getNameForCallConv(CC);
7734       }
7735     }
7736   } else {
7737     // C++11 [replacement.functions]p3:
7738     //  The program's definitions shall not be specified as inline.
7739     //
7740     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7741     //
7742     // Suppress the diagnostic if the function is __attribute__((used)), since
7743     // that forces an external definition to be emitted.
7744     if (D.getDeclSpec().isInlineSpecified() &&
7745         NewFD->isReplaceableGlobalAllocationFunction() &&
7746         !NewFD->hasAttr<UsedAttr>())
7747       Diag(D.getDeclSpec().getInlineSpecLoc(),
7748            diag::ext_operator_new_delete_declared_inline)
7749         << NewFD->getDeclName();
7750 
7751     // If the declarator is a template-id, translate the parser's template
7752     // argument list into our AST format.
7753     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7754       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7755       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7756       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7757       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7758                                          TemplateId->NumArgs);
7759       translateTemplateArguments(TemplateArgsPtr,
7760                                  TemplateArgs);
7761 
7762       HasExplicitTemplateArgs = true;
7763 
7764       if (NewFD->isInvalidDecl()) {
7765         HasExplicitTemplateArgs = false;
7766       } else if (FunctionTemplate) {
7767         // Function template with explicit template arguments.
7768         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7769           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7770 
7771         HasExplicitTemplateArgs = false;
7772       } else {
7773         assert((isFunctionTemplateSpecialization ||
7774                 D.getDeclSpec().isFriendSpecified()) &&
7775                "should have a 'template<>' for this decl");
7776         // "friend void foo<>(int);" is an implicit specialization decl.
7777         isFunctionTemplateSpecialization = true;
7778       }
7779     } else if (isFriend && isFunctionTemplateSpecialization) {
7780       // This combination is only possible in a recovery case;  the user
7781       // wrote something like:
7782       //   template <> friend void foo(int);
7783       // which we're recovering from as if the user had written:
7784       //   friend void foo<>(int);
7785       // Go ahead and fake up a template id.
7786       HasExplicitTemplateArgs = true;
7787       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7788       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7789     }
7790 
7791     // If it's a friend (and only if it's a friend), it's possible
7792     // that either the specialized function type or the specialized
7793     // template is dependent, and therefore matching will fail.  In
7794     // this case, don't check the specialization yet.
7795     bool InstantiationDependent = false;
7796     if (isFunctionTemplateSpecialization && isFriend &&
7797         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7798          TemplateSpecializationType::anyDependentTemplateArguments(
7799             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7800             InstantiationDependent))) {
7801       assert(HasExplicitTemplateArgs &&
7802              "friend function specialization without template args");
7803       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7804                                                        Previous))
7805         NewFD->setInvalidDecl();
7806     } else if (isFunctionTemplateSpecialization) {
7807       if (CurContext->isDependentContext() && CurContext->isRecord()
7808           && !isFriend) {
7809         isDependentClassScopeExplicitSpecialization = true;
7810         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7811           diag::ext_function_specialization_in_class :
7812           diag::err_function_specialization_in_class)
7813           << NewFD->getDeclName();
7814       } else if (CheckFunctionTemplateSpecialization(NewFD,
7815                                   (HasExplicitTemplateArgs ? &TemplateArgs
7816                                                            : nullptr),
7817                                                      Previous))
7818         NewFD->setInvalidDecl();
7819 
7820       // C++ [dcl.stc]p1:
7821       //   A storage-class-specifier shall not be specified in an explicit
7822       //   specialization (14.7.3)
7823       FunctionTemplateSpecializationInfo *Info =
7824           NewFD->getTemplateSpecializationInfo();
7825       if (Info && SC != SC_None) {
7826         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7827           Diag(NewFD->getLocation(),
7828                diag::err_explicit_specialization_inconsistent_storage_class)
7829             << SC
7830             << FixItHint::CreateRemoval(
7831                                       D.getDeclSpec().getStorageClassSpecLoc());
7832 
7833         else
7834           Diag(NewFD->getLocation(),
7835                diag::ext_explicit_specialization_storage_class)
7836             << FixItHint::CreateRemoval(
7837                                       D.getDeclSpec().getStorageClassSpecLoc());
7838       }
7839 
7840     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7841       if (CheckMemberSpecialization(NewFD, Previous))
7842           NewFD->setInvalidDecl();
7843     }
7844 
7845     // Perform semantic checking on the function declaration.
7846     if (!isDependentClassScopeExplicitSpecialization) {
7847       if (!NewFD->isInvalidDecl() && NewFD->isMain())
7848         CheckMain(NewFD, D.getDeclSpec());
7849 
7850       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7851         CheckMSVCRTEntryPoint(NewFD);
7852 
7853       if (!NewFD->isInvalidDecl())
7854         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7855                                                     isExplicitSpecialization));
7856       else if (!Previous.empty())
7857         // Recover gracefully from an invalid redeclaration.
7858         D.setRedeclaration(true);
7859     }
7860 
7861     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7862             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7863            "previous declaration set still overloaded");
7864 
7865     NamedDecl *PrincipalDecl = (FunctionTemplate
7866                                 ? cast<NamedDecl>(FunctionTemplate)
7867                                 : NewFD);
7868 
7869     if (isFriend && D.isRedeclaration()) {
7870       AccessSpecifier Access = AS_public;
7871       if (!NewFD->isInvalidDecl())
7872         Access = NewFD->getPreviousDecl()->getAccess();
7873 
7874       NewFD->setAccess(Access);
7875       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7876     }
7877 
7878     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7879         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7880       PrincipalDecl->setNonMemberOperator();
7881 
7882     // If we have a function template, check the template parameter
7883     // list. This will check and merge default template arguments.
7884     if (FunctionTemplate) {
7885       FunctionTemplateDecl *PrevTemplate =
7886                                      FunctionTemplate->getPreviousDecl();
7887       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7888                        PrevTemplate ? PrevTemplate->getTemplateParameters()
7889                                     : nullptr,
7890                             D.getDeclSpec().isFriendSpecified()
7891                               ? (D.isFunctionDefinition()
7892                                    ? TPC_FriendFunctionTemplateDefinition
7893                                    : TPC_FriendFunctionTemplate)
7894                               : (D.getCXXScopeSpec().isSet() &&
7895                                  DC && DC->isRecord() &&
7896                                  DC->isDependentContext())
7897                                   ? TPC_ClassTemplateMember
7898                                   : TPC_FunctionTemplate);
7899     }
7900 
7901     if (NewFD->isInvalidDecl()) {
7902       // Ignore all the rest of this.
7903     } else if (!D.isRedeclaration()) {
7904       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7905                                        AddToScope };
7906       // Fake up an access specifier if it's supposed to be a class member.
7907       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7908         NewFD->setAccess(AS_public);
7909 
7910       // Qualified decls generally require a previous declaration.
7911       if (D.getCXXScopeSpec().isSet()) {
7912         // ...with the major exception of templated-scope or
7913         // dependent-scope friend declarations.
7914 
7915         // TODO: we currently also suppress this check in dependent
7916         // contexts because (1) the parameter depth will be off when
7917         // matching friend templates and (2) we might actually be
7918         // selecting a friend based on a dependent factor.  But there
7919         // are situations where these conditions don't apply and we
7920         // can actually do this check immediately.
7921         if (isFriend &&
7922             (TemplateParamLists.size() ||
7923              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7924              CurContext->isDependentContext())) {
7925           // ignore these
7926         } else {
7927           // The user tried to provide an out-of-line definition for a
7928           // function that is a member of a class or namespace, but there
7929           // was no such member function declared (C++ [class.mfct]p2,
7930           // C++ [namespace.memdef]p2). For example:
7931           //
7932           // class X {
7933           //   void f() const;
7934           // };
7935           //
7936           // void X::f() { } // ill-formed
7937           //
7938           // Complain about this problem, and attempt to suggest close
7939           // matches (e.g., those that differ only in cv-qualifiers and
7940           // whether the parameter types are references).
7941 
7942           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7943                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
7944             AddToScope = ExtraArgs.AddToScope;
7945             return Result;
7946           }
7947         }
7948 
7949         // Unqualified local friend declarations are required to resolve
7950         // to something.
7951       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7952         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7953                 *this, Previous, NewFD, ExtraArgs, true, S)) {
7954           AddToScope = ExtraArgs.AddToScope;
7955           return Result;
7956         }
7957       }
7958 
7959     } else if (!D.isFunctionDefinition() &&
7960                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
7961                !isFriend && !isFunctionTemplateSpecialization &&
7962                !isExplicitSpecialization) {
7963       // An out-of-line member function declaration must also be a
7964       // definition (C++ [class.mfct]p2).
7965       // Note that this is not the case for explicit specializations of
7966       // function templates or member functions of class templates, per
7967       // C++ [temp.expl.spec]p2. We also allow these declarations as an
7968       // extension for compatibility with old SWIG code which likes to
7969       // generate them.
7970       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7971         << D.getCXXScopeSpec().getRange();
7972     }
7973   }
7974 
7975   ProcessPragmaWeak(S, NewFD);
7976   checkAttributesAfterMerging(*this, *NewFD);
7977 
7978   AddKnownFunctionAttributes(NewFD);
7979 
7980   if (NewFD->hasAttr<OverloadableAttr>() &&
7981       !NewFD->getType()->getAs<FunctionProtoType>()) {
7982     Diag(NewFD->getLocation(),
7983          diag::err_attribute_overloadable_no_prototype)
7984       << NewFD;
7985 
7986     // Turn this into a variadic function with no parameters.
7987     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7988     FunctionProtoType::ExtProtoInfo EPI(
7989         Context.getDefaultCallingConvention(true, false));
7990     EPI.Variadic = true;
7991     EPI.ExtInfo = FT->getExtInfo();
7992 
7993     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
7994     NewFD->setType(R);
7995   }
7996 
7997   // If there's a #pragma GCC visibility in scope, and this isn't a class
7998   // member, set the visibility of this function.
7999   if (!DC->isRecord() && NewFD->isExternallyVisible())
8000     AddPushedVisibilityAttribute(NewFD);
8001 
8002   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8003   // marking the function.
8004   AddCFAuditedAttribute(NewFD);
8005 
8006   // If this is a function definition, check if we have to apply optnone due to
8007   // a pragma.
8008   if(D.isFunctionDefinition())
8009     AddRangeBasedOptnone(NewFD);
8010 
8011   // If this is the first declaration of an extern C variable, update
8012   // the map of such variables.
8013   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8014       isIncompleteDeclExternC(*this, NewFD))
8015     RegisterLocallyScopedExternCDecl(NewFD, S);
8016 
8017   // Set this FunctionDecl's range up to the right paren.
8018   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8019 
8020   if (D.isRedeclaration() && !Previous.empty()) {
8021     checkDLLAttributeRedeclaration(
8022         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8023         isExplicitSpecialization || isFunctionTemplateSpecialization);
8024   }
8025 
8026   if (getLangOpts().CPlusPlus) {
8027     if (FunctionTemplate) {
8028       if (NewFD->isInvalidDecl())
8029         FunctionTemplate->setInvalidDecl();
8030       return FunctionTemplate;
8031     }
8032   }
8033 
8034   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8035     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8036     if ((getLangOpts().OpenCLVersion >= 120)
8037         && (SC == SC_Static)) {
8038       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8039       D.setInvalidType();
8040     }
8041 
8042     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8043     if (!NewFD->getReturnType()->isVoidType()) {
8044       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8045       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8046           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8047                                 : FixItHint());
8048       D.setInvalidType();
8049     }
8050 
8051     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8052     for (auto Param : NewFD->params())
8053       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8054   }
8055 
8056   MarkUnusedFileScopedDecl(NewFD);
8057 
8058   if (getLangOpts().CUDA)
8059     if (IdentifierInfo *II = NewFD->getIdentifier())
8060       if (!NewFD->isInvalidDecl() &&
8061           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8062         if (II->isStr("cudaConfigureCall")) {
8063           if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8064             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8065 
8066           Context.setcudaConfigureCallDecl(NewFD);
8067         }
8068       }
8069 
8070   // Here we have an function template explicit specialization at class scope.
8071   // The actually specialization will be postponed to template instatiation
8072   // time via the ClassScopeFunctionSpecializationDecl node.
8073   if (isDependentClassScopeExplicitSpecialization) {
8074     ClassScopeFunctionSpecializationDecl *NewSpec =
8075                          ClassScopeFunctionSpecializationDecl::Create(
8076                                 Context, CurContext, SourceLocation(),
8077                                 cast<CXXMethodDecl>(NewFD),
8078                                 HasExplicitTemplateArgs, TemplateArgs);
8079     CurContext->addDecl(NewSpec);
8080     AddToScope = false;
8081   }
8082 
8083   return NewFD;
8084 }
8085 
8086 /// \brief Perform semantic checking of a new function declaration.
8087 ///
8088 /// Performs semantic analysis of the new function declaration
8089 /// NewFD. This routine performs all semantic checking that does not
8090 /// require the actual declarator involved in the declaration, and is
8091 /// used both for the declaration of functions as they are parsed
8092 /// (called via ActOnDeclarator) and for the declaration of functions
8093 /// that have been instantiated via C++ template instantiation (called
8094 /// via InstantiateDecl).
8095 ///
8096 /// \param IsExplicitSpecialization whether this new function declaration is
8097 /// an explicit specialization of the previous declaration.
8098 ///
8099 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8100 ///
8101 /// \returns true if the function declaration is a redeclaration.
8102 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8103                                     LookupResult &Previous,
8104                                     bool IsExplicitSpecialization) {
8105   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8106          "Variably modified return types are not handled here");
8107 
8108   // Determine whether the type of this function should be merged with
8109   // a previous visible declaration. This never happens for functions in C++,
8110   // and always happens in C if the previous declaration was visible.
8111   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8112                                !Previous.isShadowed();
8113 
8114   bool Redeclaration = false;
8115   NamedDecl *OldDecl = nullptr;
8116 
8117   // Merge or overload the declaration with an existing declaration of
8118   // the same name, if appropriate.
8119   if (!Previous.empty()) {
8120     // Determine whether NewFD is an overload of PrevDecl or
8121     // a declaration that requires merging. If it's an overload,
8122     // there's no more work to do here; we'll just add the new
8123     // function to the scope.
8124     if (!AllowOverloadingOfFunction(Previous, Context)) {
8125       NamedDecl *Candidate = Previous.getFoundDecl();
8126       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8127         Redeclaration = true;
8128         OldDecl = Candidate;
8129       }
8130     } else {
8131       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8132                             /*NewIsUsingDecl*/ false)) {
8133       case Ovl_Match:
8134         Redeclaration = true;
8135         break;
8136 
8137       case Ovl_NonFunction:
8138         Redeclaration = true;
8139         break;
8140 
8141       case Ovl_Overload:
8142         Redeclaration = false;
8143         break;
8144       }
8145 
8146       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8147         // If a function name is overloadable in C, then every function
8148         // with that name must be marked "overloadable".
8149         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8150           << Redeclaration << NewFD;
8151         NamedDecl *OverloadedDecl = nullptr;
8152         if (Redeclaration)
8153           OverloadedDecl = OldDecl;
8154         else if (!Previous.empty())
8155           OverloadedDecl = Previous.getRepresentativeDecl();
8156         if (OverloadedDecl)
8157           Diag(OverloadedDecl->getLocation(),
8158                diag::note_attribute_overloadable_prev_overload);
8159         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8160       }
8161     }
8162   }
8163 
8164   // Check for a previous extern "C" declaration with this name.
8165   if (!Redeclaration &&
8166       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8167     if (!Previous.empty()) {
8168       // This is an extern "C" declaration with the same name as a previous
8169       // declaration, and thus redeclares that entity...
8170       Redeclaration = true;
8171       OldDecl = Previous.getFoundDecl();
8172       MergeTypeWithPrevious = false;
8173 
8174       // ... except in the presence of __attribute__((overloadable)).
8175       if (OldDecl->hasAttr<OverloadableAttr>()) {
8176         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8177           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8178             << Redeclaration << NewFD;
8179           Diag(Previous.getFoundDecl()->getLocation(),
8180                diag::note_attribute_overloadable_prev_overload);
8181           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8182         }
8183         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8184           Redeclaration = false;
8185           OldDecl = nullptr;
8186         }
8187       }
8188     }
8189   }
8190 
8191   // C++11 [dcl.constexpr]p8:
8192   //   A constexpr specifier for a non-static member function that is not
8193   //   a constructor declares that member function to be const.
8194   //
8195   // This needs to be delayed until we know whether this is an out-of-line
8196   // definition of a static member function.
8197   //
8198   // This rule is not present in C++1y, so we produce a backwards
8199   // compatibility warning whenever it happens in C++11.
8200   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8201   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8202       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8203       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8204     CXXMethodDecl *OldMD = nullptr;
8205     if (OldDecl)
8206       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8207     if (!OldMD || !OldMD->isStatic()) {
8208       const FunctionProtoType *FPT =
8209         MD->getType()->castAs<FunctionProtoType>();
8210       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8211       EPI.TypeQuals |= Qualifiers::Const;
8212       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8213                                           FPT->getParamTypes(), EPI));
8214 
8215       // Warn that we did this, if we're not performing template instantiation.
8216       // In that case, we'll have warned already when the template was defined.
8217       if (ActiveTemplateInstantiations.empty()) {
8218         SourceLocation AddConstLoc;
8219         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8220                 .IgnoreParens().getAs<FunctionTypeLoc>())
8221           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8222 
8223         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8224           << FixItHint::CreateInsertion(AddConstLoc, " const");
8225       }
8226     }
8227   }
8228 
8229   if (Redeclaration) {
8230     // NewFD and OldDecl represent declarations that need to be
8231     // merged.
8232     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8233       NewFD->setInvalidDecl();
8234       return Redeclaration;
8235     }
8236 
8237     Previous.clear();
8238     Previous.addDecl(OldDecl);
8239 
8240     if (FunctionTemplateDecl *OldTemplateDecl
8241                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8242       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8243       FunctionTemplateDecl *NewTemplateDecl
8244         = NewFD->getDescribedFunctionTemplate();
8245       assert(NewTemplateDecl && "Template/non-template mismatch");
8246       if (CXXMethodDecl *Method
8247             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8248         Method->setAccess(OldTemplateDecl->getAccess());
8249         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8250       }
8251 
8252       // If this is an explicit specialization of a member that is a function
8253       // template, mark it as a member specialization.
8254       if (IsExplicitSpecialization &&
8255           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8256         NewTemplateDecl->setMemberSpecialization();
8257         assert(OldTemplateDecl->isMemberSpecialization());
8258       }
8259 
8260     } else {
8261       // This needs to happen first so that 'inline' propagates.
8262       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8263 
8264       if (isa<CXXMethodDecl>(NewFD))
8265         NewFD->setAccess(OldDecl->getAccess());
8266     }
8267   }
8268 
8269   // Semantic checking for this function declaration (in isolation).
8270 
8271   if (getLangOpts().CPlusPlus) {
8272     // C++-specific checks.
8273     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8274       CheckConstructor(Constructor);
8275     } else if (CXXDestructorDecl *Destructor =
8276                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8277       CXXRecordDecl *Record = Destructor->getParent();
8278       QualType ClassType = Context.getTypeDeclType(Record);
8279 
8280       // FIXME: Shouldn't we be able to perform this check even when the class
8281       // type is dependent? Both gcc and edg can handle that.
8282       if (!ClassType->isDependentType()) {
8283         DeclarationName Name
8284           = Context.DeclarationNames.getCXXDestructorName(
8285                                         Context.getCanonicalType(ClassType));
8286         if (NewFD->getDeclName() != Name) {
8287           Diag(NewFD->getLocation(), diag::err_destructor_name);
8288           NewFD->setInvalidDecl();
8289           return Redeclaration;
8290         }
8291       }
8292     } else if (CXXConversionDecl *Conversion
8293                = dyn_cast<CXXConversionDecl>(NewFD)) {
8294       ActOnConversionDeclarator(Conversion);
8295     }
8296 
8297     // Find any virtual functions that this function overrides.
8298     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8299       if (!Method->isFunctionTemplateSpecialization() &&
8300           !Method->getDescribedFunctionTemplate() &&
8301           Method->isCanonicalDecl()) {
8302         if (AddOverriddenMethods(Method->getParent(), Method)) {
8303           // If the function was marked as "static", we have a problem.
8304           if (NewFD->getStorageClass() == SC_Static) {
8305             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8306           }
8307         }
8308       }
8309 
8310       if (Method->isStatic())
8311         checkThisInStaticMemberFunctionType(Method);
8312     }
8313 
8314     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8315     if (NewFD->isOverloadedOperator() &&
8316         CheckOverloadedOperatorDeclaration(NewFD)) {
8317       NewFD->setInvalidDecl();
8318       return Redeclaration;
8319     }
8320 
8321     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8322     if (NewFD->getLiteralIdentifier() &&
8323         CheckLiteralOperatorDeclaration(NewFD)) {
8324       NewFD->setInvalidDecl();
8325       return Redeclaration;
8326     }
8327 
8328     // In C++, check default arguments now that we have merged decls. Unless
8329     // the lexical context is the class, because in this case this is done
8330     // during delayed parsing anyway.
8331     if (!CurContext->isRecord())
8332       CheckCXXDefaultArguments(NewFD);
8333 
8334     // If this function declares a builtin function, check the type of this
8335     // declaration against the expected type for the builtin.
8336     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8337       ASTContext::GetBuiltinTypeError Error;
8338       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8339       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8340       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8341         // The type of this function differs from the type of the builtin,
8342         // so forget about the builtin entirely.
8343         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8344       }
8345     }
8346 
8347     // If this function is declared as being extern "C", then check to see if
8348     // the function returns a UDT (class, struct, or union type) that is not C
8349     // compatible, and if it does, warn the user.
8350     // But, issue any diagnostic on the first declaration only.
8351     if (Previous.empty() && NewFD->isExternC()) {
8352       QualType R = NewFD->getReturnType();
8353       if (R->isIncompleteType() && !R->isVoidType())
8354         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8355             << NewFD << R;
8356       else if (!R.isPODType(Context) && !R->isVoidType() &&
8357                !R->isObjCObjectPointerType())
8358         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8359     }
8360   }
8361   return Redeclaration;
8362 }
8363 
8364 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8365   // C++11 [basic.start.main]p3:
8366   //   A program that [...] declares main to be inline, static or
8367   //   constexpr is ill-formed.
8368   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8369   //   appear in a declaration of main.
8370   // static main is not an error under C99, but we should warn about it.
8371   // We accept _Noreturn main as an extension.
8372   if (FD->getStorageClass() == SC_Static)
8373     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8374          ? diag::err_static_main : diag::warn_static_main)
8375       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8376   if (FD->isInlineSpecified())
8377     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8378       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8379   if (DS.isNoreturnSpecified()) {
8380     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8381     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8382     Diag(NoreturnLoc, diag::ext_noreturn_main);
8383     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8384       << FixItHint::CreateRemoval(NoreturnRange);
8385   }
8386   if (FD->isConstexpr()) {
8387     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8388       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8389     FD->setConstexpr(false);
8390   }
8391 
8392   if (getLangOpts().OpenCL) {
8393     Diag(FD->getLocation(), diag::err_opencl_no_main)
8394         << FD->hasAttr<OpenCLKernelAttr>();
8395     FD->setInvalidDecl();
8396     return;
8397   }
8398 
8399   QualType T = FD->getType();
8400   assert(T->isFunctionType() && "function decl is not of function type");
8401   const FunctionType* FT = T->castAs<FunctionType>();
8402 
8403   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8404     // In C with GNU extensions we allow main() to have non-integer return
8405     // type, but we should warn about the extension, and we disable the
8406     // implicit-return-zero rule.
8407 
8408     // GCC in C mode accepts qualified 'int'.
8409     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8410       FD->setHasImplicitReturnZero(true);
8411     else {
8412       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8413       SourceRange RTRange = FD->getReturnTypeSourceRange();
8414       if (RTRange.isValid())
8415         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8416             << FixItHint::CreateReplacement(RTRange, "int");
8417     }
8418   } else {
8419     // In C and C++, main magically returns 0 if you fall off the end;
8420     // set the flag which tells us that.
8421     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8422 
8423     // All the standards say that main() should return 'int'.
8424     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8425       FD->setHasImplicitReturnZero(true);
8426     else {
8427       // Otherwise, this is just a flat-out error.
8428       SourceRange RTRange = FD->getReturnTypeSourceRange();
8429       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8430           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8431                                 : FixItHint());
8432       FD->setInvalidDecl(true);
8433     }
8434   }
8435 
8436   // Treat protoless main() as nullary.
8437   if (isa<FunctionNoProtoType>(FT)) return;
8438 
8439   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8440   unsigned nparams = FTP->getNumParams();
8441   assert(FD->getNumParams() == nparams);
8442 
8443   bool HasExtraParameters = (nparams > 3);
8444 
8445   if (FTP->isVariadic()) {
8446     Diag(FD->getLocation(), diag::ext_variadic_main);
8447     // FIXME: if we had information about the location of the ellipsis, we
8448     // could add a FixIt hint to remove it as a parameter.
8449   }
8450 
8451   // Darwin passes an undocumented fourth argument of type char**.  If
8452   // other platforms start sprouting these, the logic below will start
8453   // getting shifty.
8454   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8455     HasExtraParameters = false;
8456 
8457   if (HasExtraParameters) {
8458     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8459     FD->setInvalidDecl(true);
8460     nparams = 3;
8461   }
8462 
8463   // FIXME: a lot of the following diagnostics would be improved
8464   // if we had some location information about types.
8465 
8466   QualType CharPP =
8467     Context.getPointerType(Context.getPointerType(Context.CharTy));
8468   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8469 
8470   for (unsigned i = 0; i < nparams; ++i) {
8471     QualType AT = FTP->getParamType(i);
8472 
8473     bool mismatch = true;
8474 
8475     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8476       mismatch = false;
8477     else if (Expected[i] == CharPP) {
8478       // As an extension, the following forms are okay:
8479       //   char const **
8480       //   char const * const *
8481       //   char * const *
8482 
8483       QualifierCollector qs;
8484       const PointerType* PT;
8485       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8486           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8487           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8488                               Context.CharTy)) {
8489         qs.removeConst();
8490         mismatch = !qs.empty();
8491       }
8492     }
8493 
8494     if (mismatch) {
8495       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8496       // TODO: suggest replacing given type with expected type
8497       FD->setInvalidDecl(true);
8498     }
8499   }
8500 
8501   if (nparams == 1 && !FD->isInvalidDecl()) {
8502     Diag(FD->getLocation(), diag::warn_main_one_arg);
8503   }
8504 
8505   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8506     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8507     FD->setInvalidDecl();
8508   }
8509 }
8510 
8511 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8512   QualType T = FD->getType();
8513   assert(T->isFunctionType() && "function decl is not of function type");
8514   const FunctionType *FT = T->castAs<FunctionType>();
8515 
8516   // Set an implicit return of 'zero' if the function can return some integral,
8517   // enumeration, pointer or nullptr type.
8518   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8519       FT->getReturnType()->isAnyPointerType() ||
8520       FT->getReturnType()->isNullPtrType())
8521     // DllMain is exempt because a return value of zero means it failed.
8522     if (FD->getName() != "DllMain")
8523       FD->setHasImplicitReturnZero(true);
8524 
8525   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8526     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8527     FD->setInvalidDecl();
8528   }
8529 }
8530 
8531 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8532   // FIXME: Need strict checking.  In C89, we need to check for
8533   // any assignment, increment, decrement, function-calls, or
8534   // commas outside of a sizeof.  In C99, it's the same list,
8535   // except that the aforementioned are allowed in unevaluated
8536   // expressions.  Everything else falls under the
8537   // "may accept other forms of constant expressions" exception.
8538   // (We never end up here for C++, so the constant expression
8539   // rules there don't matter.)
8540   const Expr *Culprit;
8541   if (Init->isConstantInitializer(Context, false, &Culprit))
8542     return false;
8543   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8544     << Culprit->getSourceRange();
8545   return true;
8546 }
8547 
8548 namespace {
8549   // Visits an initialization expression to see if OrigDecl is evaluated in
8550   // its own initialization and throws a warning if it does.
8551   class SelfReferenceChecker
8552       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8553     Sema &S;
8554     Decl *OrigDecl;
8555     bool isRecordType;
8556     bool isPODType;
8557     bool isReferenceType;
8558 
8559     bool isInitList;
8560     llvm::SmallVector<unsigned, 4> InitFieldIndex;
8561   public:
8562     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8563 
8564     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8565                                                     S(S), OrigDecl(OrigDecl) {
8566       isPODType = false;
8567       isRecordType = false;
8568       isReferenceType = false;
8569       isInitList = false;
8570       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8571         isPODType = VD->getType().isPODType(S.Context);
8572         isRecordType = VD->getType()->isRecordType();
8573         isReferenceType = VD->getType()->isReferenceType();
8574       }
8575     }
8576 
8577     // For most expressions, just call the visitor.  For initializer lists,
8578     // track the index of the field being initialized since fields are
8579     // initialized in order allowing use of previously initialized fields.
8580     void CheckExpr(Expr *E) {
8581       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8582       if (!InitList) {
8583         Visit(E);
8584         return;
8585       }
8586 
8587       // Track and increment the index here.
8588       isInitList = true;
8589       InitFieldIndex.push_back(0);
8590       for (auto Child : InitList->children()) {
8591         CheckExpr(cast<Expr>(Child));
8592         ++InitFieldIndex.back();
8593       }
8594       InitFieldIndex.pop_back();
8595     }
8596 
8597     // Returns true if MemberExpr is checked and no futher checking is needed.
8598     // Returns false if additional checking is required.
8599     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8600       llvm::SmallVector<FieldDecl*, 4> Fields;
8601       Expr *Base = E;
8602       bool ReferenceField = false;
8603 
8604       // Get the field memebers used.
8605       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8606         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8607         if (!FD)
8608           return false;
8609         Fields.push_back(FD);
8610         if (FD->getType()->isReferenceType())
8611           ReferenceField = true;
8612         Base = ME->getBase()->IgnoreParenImpCasts();
8613       }
8614 
8615       // Keep checking only if the base Decl is the same.
8616       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8617       if (!DRE || DRE->getDecl() != OrigDecl)
8618         return false;
8619 
8620       // A reference field can be bound to an unininitialized field.
8621       if (CheckReference && !ReferenceField)
8622         return true;
8623 
8624       // Convert FieldDecls to their index number.
8625       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8626       for (const FieldDecl *I : llvm::reverse(Fields))
8627         UsedFieldIndex.push_back(I->getFieldIndex());
8628 
8629       // See if a warning is needed by checking the first difference in index
8630       // numbers.  If field being used has index less than the field being
8631       // initialized, then the use is safe.
8632       for (auto UsedIter = UsedFieldIndex.begin(),
8633                 UsedEnd = UsedFieldIndex.end(),
8634                 OrigIter = InitFieldIndex.begin(),
8635                 OrigEnd = InitFieldIndex.end();
8636            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8637         if (*UsedIter < *OrigIter)
8638           return true;
8639         if (*UsedIter > *OrigIter)
8640           break;
8641       }
8642 
8643       // TODO: Add a different warning which will print the field names.
8644       HandleDeclRefExpr(DRE);
8645       return true;
8646     }
8647 
8648     // For most expressions, the cast is directly above the DeclRefExpr.
8649     // For conditional operators, the cast can be outside the conditional
8650     // operator if both expressions are DeclRefExpr's.
8651     void HandleValue(Expr *E) {
8652       E = E->IgnoreParens();
8653       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8654         HandleDeclRefExpr(DRE);
8655         return;
8656       }
8657 
8658       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8659         Visit(CO->getCond());
8660         HandleValue(CO->getTrueExpr());
8661         HandleValue(CO->getFalseExpr());
8662         return;
8663       }
8664 
8665       if (BinaryConditionalOperator *BCO =
8666               dyn_cast<BinaryConditionalOperator>(E)) {
8667         Visit(BCO->getCond());
8668         HandleValue(BCO->getFalseExpr());
8669         return;
8670       }
8671 
8672       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8673         HandleValue(OVE->getSourceExpr());
8674         return;
8675       }
8676 
8677       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8678         if (BO->getOpcode() == BO_Comma) {
8679           Visit(BO->getLHS());
8680           HandleValue(BO->getRHS());
8681           return;
8682         }
8683       }
8684 
8685       if (isa<MemberExpr>(E)) {
8686         if (isInitList) {
8687           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
8688                                       false /*CheckReference*/))
8689             return;
8690         }
8691 
8692         Expr *Base = E->IgnoreParenImpCasts();
8693         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8694           // Check for static member variables and don't warn on them.
8695           if (!isa<FieldDecl>(ME->getMemberDecl()))
8696             return;
8697           Base = ME->getBase()->IgnoreParenImpCasts();
8698         }
8699         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8700           HandleDeclRefExpr(DRE);
8701         return;
8702       }
8703 
8704       Visit(E);
8705     }
8706 
8707     // Reference types not handled in HandleValue are handled here since all
8708     // uses of references are bad, not just r-value uses.
8709     void VisitDeclRefExpr(DeclRefExpr *E) {
8710       if (isReferenceType)
8711         HandleDeclRefExpr(E);
8712     }
8713 
8714     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8715       if (E->getCastKind() == CK_LValueToRValue) {
8716         HandleValue(E->getSubExpr());
8717         return;
8718       }
8719 
8720       Inherited::VisitImplicitCastExpr(E);
8721     }
8722 
8723     void VisitMemberExpr(MemberExpr *E) {
8724       if (isInitList) {
8725         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
8726           return;
8727       }
8728 
8729       // Don't warn on arrays since they can be treated as pointers.
8730       if (E->getType()->canDecayToPointerType()) return;
8731 
8732       // Warn when a non-static method call is followed by non-static member
8733       // field accesses, which is followed by a DeclRefExpr.
8734       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8735       bool Warn = (MD && !MD->isStatic());
8736       Expr *Base = E->getBase()->IgnoreParenImpCasts();
8737       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8738         if (!isa<FieldDecl>(ME->getMemberDecl()))
8739           Warn = false;
8740         Base = ME->getBase()->IgnoreParenImpCasts();
8741       }
8742 
8743       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8744         if (Warn)
8745           HandleDeclRefExpr(DRE);
8746         return;
8747       }
8748 
8749       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8750       // Visit that expression.
8751       Visit(Base);
8752     }
8753 
8754     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8755       Expr *Callee = E->getCallee();
8756 
8757       if (isa<UnresolvedLookupExpr>(Callee))
8758         return Inherited::VisitCXXOperatorCallExpr(E);
8759 
8760       Visit(Callee);
8761       for (auto Arg: E->arguments())
8762         HandleValue(Arg->IgnoreParenImpCasts());
8763     }
8764 
8765     void VisitUnaryOperator(UnaryOperator *E) {
8766       // For POD record types, addresses of its own members are well-defined.
8767       if (E->getOpcode() == UO_AddrOf && isRecordType &&
8768           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8769         if (!isPODType)
8770           HandleValue(E->getSubExpr());
8771         return;
8772       }
8773 
8774       if (E->isIncrementDecrementOp()) {
8775         HandleValue(E->getSubExpr());
8776         return;
8777       }
8778 
8779       Inherited::VisitUnaryOperator(E);
8780     }
8781 
8782     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8783 
8784     void VisitCXXConstructExpr(CXXConstructExpr *E) {
8785       if (E->getConstructor()->isCopyConstructor()) {
8786         Expr *ArgExpr = E->getArg(0);
8787         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
8788           if (ILE->getNumInits() == 1)
8789             ArgExpr = ILE->getInit(0);
8790         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8791           if (ICE->getCastKind() == CK_NoOp)
8792             ArgExpr = ICE->getSubExpr();
8793         HandleValue(ArgExpr);
8794         return;
8795       }
8796       Inherited::VisitCXXConstructExpr(E);
8797     }
8798 
8799     void VisitCallExpr(CallExpr *E) {
8800       // Treat std::move as a use.
8801       if (E->getNumArgs() == 1) {
8802         if (FunctionDecl *FD = E->getDirectCallee()) {
8803           if (FD->isInStdNamespace() && FD->getIdentifier() &&
8804               FD->getIdentifier()->isStr("move")) {
8805             HandleValue(E->getArg(0));
8806             return;
8807           }
8808         }
8809       }
8810 
8811       Inherited::VisitCallExpr(E);
8812     }
8813 
8814     void VisitBinaryOperator(BinaryOperator *E) {
8815       if (E->isCompoundAssignmentOp()) {
8816         HandleValue(E->getLHS());
8817         Visit(E->getRHS());
8818         return;
8819       }
8820 
8821       Inherited::VisitBinaryOperator(E);
8822     }
8823 
8824     // A custom visitor for BinaryConditionalOperator is needed because the
8825     // regular visitor would check the condition and true expression separately
8826     // but both point to the same place giving duplicate diagnostics.
8827     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
8828       Visit(E->getCond());
8829       Visit(E->getFalseExpr());
8830     }
8831 
8832     void HandleDeclRefExpr(DeclRefExpr *DRE) {
8833       Decl* ReferenceDecl = DRE->getDecl();
8834       if (OrigDecl != ReferenceDecl) return;
8835       unsigned diag;
8836       if (isReferenceType) {
8837         diag = diag::warn_uninit_self_reference_in_reference_init;
8838       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8839         diag = diag::warn_static_self_reference_in_init;
8840       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
8841                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
8842                  DRE->getDecl()->getType()->isRecordType()) {
8843         diag = diag::warn_uninit_self_reference_in_init;
8844       } else {
8845         // Local variables will be handled by the CFG analysis.
8846         return;
8847       }
8848 
8849       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
8850                             S.PDiag(diag)
8851                               << DRE->getNameInfo().getName()
8852                               << OrigDecl->getLocation()
8853                               << DRE->getSourceRange());
8854     }
8855   };
8856 
8857   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8858   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8859                                  bool DirectInit) {
8860     // Parameters arguments are occassionially constructed with itself,
8861     // for instance, in recursive functions.  Skip them.
8862     if (isa<ParmVarDecl>(OrigDecl))
8863       return;
8864 
8865     E = E->IgnoreParens();
8866 
8867     // Skip checking T a = a where T is not a record or reference type.
8868     // Doing so is a way to silence uninitialized warnings.
8869     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8870       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8871         if (ICE->getCastKind() == CK_LValueToRValue)
8872           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8873             if (DRE->getDecl() == OrigDecl)
8874               return;
8875 
8876     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
8877   }
8878 }
8879 
8880 /// AddInitializerToDecl - Adds the initializer Init to the
8881 /// declaration dcl. If DirectInit is true, this is C++ direct
8882 /// initialization rather than copy initialization.
8883 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8884                                 bool DirectInit, bool TypeMayContainAuto) {
8885   // If there is no declaration, there was an error parsing it.  Just ignore
8886   // the initializer.
8887   if (!RealDecl || RealDecl->isInvalidDecl()) {
8888     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
8889     return;
8890   }
8891 
8892   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8893     // Pure-specifiers are handled in ActOnPureSpecifier.
8894     Diag(Method->getLocation(), diag::err_member_function_initialization)
8895       << Method->getDeclName() << Init->getSourceRange();
8896     Method->setInvalidDecl();
8897     return;
8898   }
8899 
8900   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8901   if (!VDecl) {
8902     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8903     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8904     RealDecl->setInvalidDecl();
8905     return;
8906   }
8907   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8908 
8909   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8910   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
8911     // Attempt typo correction early so that the type of the init expression can
8912     // be deduced based on the chosen correction:if the original init contains a
8913     // TypoExpr.
8914     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
8915     if (!Res.isUsable()) {
8916       RealDecl->setInvalidDecl();
8917       return;
8918     }
8919 
8920     if (Res.get() != Init) {
8921       Init = Res.get();
8922       if (CXXDirectInit)
8923         CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8924     }
8925 
8926     Expr *DeduceInit = Init;
8927     // Initializer could be a C++ direct-initializer. Deduction only works if it
8928     // contains exactly one expression.
8929     if (CXXDirectInit) {
8930       if (CXXDirectInit->getNumExprs() == 0) {
8931         // It isn't possible to write this directly, but it is possible to
8932         // end up in this situation with "auto x(some_pack...);"
8933         Diag(CXXDirectInit->getLocStart(),
8934              VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8935                                     : diag::err_auto_var_init_no_expression)
8936           << VDecl->getDeclName() << VDecl->getType()
8937           << VDecl->getSourceRange();
8938         RealDecl->setInvalidDecl();
8939         return;
8940       } else if (CXXDirectInit->getNumExprs() > 1) {
8941         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
8942              VDecl->isInitCapture()
8943                  ? diag::err_init_capture_multiple_expressions
8944                  : diag::err_auto_var_init_multiple_expressions)
8945           << VDecl->getDeclName() << VDecl->getType()
8946           << VDecl->getSourceRange();
8947         RealDecl->setInvalidDecl();
8948         return;
8949       } else {
8950         DeduceInit = CXXDirectInit->getExpr(0);
8951         if (isa<InitListExpr>(DeduceInit))
8952           Diag(CXXDirectInit->getLocStart(),
8953                diag::err_auto_var_init_paren_braces)
8954             << VDecl->getDeclName() << VDecl->getType()
8955             << VDecl->getSourceRange();
8956       }
8957     }
8958 
8959     // Expressions default to 'id' when we're in a debugger.
8960     bool DefaultedToAuto = false;
8961     if (getLangOpts().DebuggerCastResultToId &&
8962         Init->getType() == Context.UnknownAnyTy) {
8963       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8964       if (Result.isInvalid()) {
8965         VDecl->setInvalidDecl();
8966         return;
8967       }
8968       Init = Result.get();
8969       DefaultedToAuto = true;
8970     }
8971 
8972     QualType DeducedType;
8973     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8974             DAR_Failed)
8975       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8976     if (DeducedType.isNull()) {
8977       RealDecl->setInvalidDecl();
8978       return;
8979     }
8980     VDecl->setType(DeducedType);
8981     assert(VDecl->isLinkageValid());
8982 
8983     // In ARC, infer lifetime.
8984     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8985       VDecl->setInvalidDecl();
8986 
8987     // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8988     // 'id' instead of a specific object type prevents most of our usual checks.
8989     // We only want to warn outside of template instantiations, though:
8990     // inside a template, the 'id' could have come from a parameter.
8991     if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8992         DeducedType->isObjCIdType()) {
8993       SourceLocation Loc =
8994           VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
8995       Diag(Loc, diag::warn_auto_var_is_id)
8996         << VDecl->getDeclName() << DeduceInit->getSourceRange();
8997     }
8998 
8999     // If this is a redeclaration, check that the type we just deduced matches
9000     // the previously declared type.
9001     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9002       // We never need to merge the type, because we cannot form an incomplete
9003       // array of auto, nor deduce such a type.
9004       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
9005     }
9006 
9007     // Check the deduced type is valid for a variable declaration.
9008     CheckVariableDeclarationType(VDecl);
9009     if (VDecl->isInvalidDecl())
9010       return;
9011 
9012     // If all looks well, warn if this is a case that will change meaning when
9013     // we implement N3922.
9014     if (DirectInit && !CXXDirectInit && isa<InitListExpr>(Init)) {
9015       Diag(Init->getLocStart(),
9016            diag::warn_auto_var_direct_list_init)
9017         << FixItHint::CreateInsertion(Init->getLocStart(), "=");
9018     }
9019   }
9020 
9021   // dllimport cannot be used on variable definitions.
9022   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9023     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9024     VDecl->setInvalidDecl();
9025     return;
9026   }
9027 
9028   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9029     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9030     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9031     VDecl->setInvalidDecl();
9032     return;
9033   }
9034 
9035   if (!VDecl->getType()->isDependentType()) {
9036     // A definition must end up with a complete type, which means it must be
9037     // complete with the restriction that an array type might be completed by
9038     // the initializer; note that later code assumes this restriction.
9039     QualType BaseDeclType = VDecl->getType();
9040     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9041       BaseDeclType = Array->getElementType();
9042     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9043                             diag::err_typecheck_decl_incomplete_type)) {
9044       RealDecl->setInvalidDecl();
9045       return;
9046     }
9047 
9048     // The variable can not have an abstract class type.
9049     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9050                                diag::err_abstract_type_in_decl,
9051                                AbstractVariableType))
9052       VDecl->setInvalidDecl();
9053   }
9054 
9055   VarDecl *Def;
9056   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9057     NamedDecl *Hidden = nullptr;
9058     if (!hasVisibleDefinition(Def, &Hidden) &&
9059         (VDecl->getFormalLinkage() == InternalLinkage ||
9060          VDecl->getDescribedVarTemplate() ||
9061          VDecl->getNumTemplateParameterLists() ||
9062          VDecl->getDeclContext()->isDependentContext())) {
9063       // The previous definition is hidden, and multiple definitions are
9064       // permitted (in separate TUs). Form another definition of it.
9065     } else {
9066       Diag(VDecl->getLocation(), diag::err_redefinition)
9067         << VDecl->getDeclName();
9068       Diag(Def->getLocation(), diag::note_previous_definition);
9069       VDecl->setInvalidDecl();
9070       return;
9071     }
9072   }
9073 
9074   if (getLangOpts().CPlusPlus) {
9075     // C++ [class.static.data]p4
9076     //   If a static data member is of const integral or const
9077     //   enumeration type, its declaration in the class definition can
9078     //   specify a constant-initializer which shall be an integral
9079     //   constant expression (5.19). In that case, the member can appear
9080     //   in integral constant expressions. The member shall still be
9081     //   defined in a namespace scope if it is used in the program and the
9082     //   namespace scope definition shall not contain an initializer.
9083     //
9084     // We already performed a redefinition check above, but for static
9085     // data members we also need to check whether there was an in-class
9086     // declaration with an initializer.
9087     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9088       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9089           << VDecl->getDeclName();
9090       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9091            diag::note_previous_initializer)
9092           << 0;
9093       return;
9094     }
9095 
9096     if (VDecl->hasLocalStorage())
9097       getCurFunction()->setHasBranchProtectedScope();
9098 
9099     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9100       VDecl->setInvalidDecl();
9101       return;
9102     }
9103   }
9104 
9105   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9106   // a kernel function cannot be initialized."
9107   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
9108     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9109     VDecl->setInvalidDecl();
9110     return;
9111   }
9112 
9113   // Get the decls type and save a reference for later, since
9114   // CheckInitializerTypes may change it.
9115   QualType DclT = VDecl->getType(), SavT = DclT;
9116 
9117   // Expressions default to 'id' when we're in a debugger
9118   // and we are assigning it to a variable of Objective-C pointer type.
9119   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9120       Init->getType() == Context.UnknownAnyTy) {
9121     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9122     if (Result.isInvalid()) {
9123       VDecl->setInvalidDecl();
9124       return;
9125     }
9126     Init = Result.get();
9127   }
9128 
9129   // Perform the initialization.
9130   if (!VDecl->isInvalidDecl()) {
9131     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9132     InitializationKind Kind
9133       = DirectInit ?
9134           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
9135                                                            Init->getLocStart(),
9136                                                            Init->getLocEnd())
9137                         : InitializationKind::CreateDirectList(
9138                                                           VDecl->getLocation())
9139                    : InitializationKind::CreateCopy(VDecl->getLocation(),
9140                                                     Init->getLocStart());
9141 
9142     MultiExprArg Args = Init;
9143     if (CXXDirectInit)
9144       Args = MultiExprArg(CXXDirectInit->getExprs(),
9145                           CXXDirectInit->getNumExprs());
9146 
9147     // Try to correct any TypoExprs in the initialization arguments.
9148     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9149       ExprResult Res = CorrectDelayedTyposInExpr(
9150           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9151             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9152             return Init.Failed() ? ExprError() : E;
9153           });
9154       if (Res.isInvalid()) {
9155         VDecl->setInvalidDecl();
9156       } else if (Res.get() != Args[Idx]) {
9157         Args[Idx] = Res.get();
9158       }
9159     }
9160     if (VDecl->isInvalidDecl())
9161       return;
9162 
9163     InitializationSequence InitSeq(*this, Entity, Kind, Args);
9164     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9165     if (Result.isInvalid()) {
9166       VDecl->setInvalidDecl();
9167       return;
9168     }
9169 
9170     Init = Result.getAs<Expr>();
9171   }
9172 
9173   // Check for self-references within variable initializers.
9174   // Variables declared within a function/method body (except for references)
9175   // are handled by a dataflow analysis.
9176   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9177       VDecl->getType()->isReferenceType()) {
9178     CheckSelfReference(*this, RealDecl, Init, DirectInit);
9179   }
9180 
9181   // If the type changed, it means we had an incomplete type that was
9182   // completed by the initializer. For example:
9183   //   int ary[] = { 1, 3, 5 };
9184   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9185   if (!VDecl->isInvalidDecl() && (DclT != SavT))
9186     VDecl->setType(DclT);
9187 
9188   if (!VDecl->isInvalidDecl()) {
9189     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9190 
9191     if (VDecl->hasAttr<BlocksAttr>())
9192       checkRetainCycles(VDecl, Init);
9193 
9194     // It is safe to assign a weak reference into a strong variable.
9195     // Although this code can still have problems:
9196     //   id x = self.weakProp;
9197     //   id y = self.weakProp;
9198     // we do not warn to warn spuriously when 'x' and 'y' are on separate
9199     // paths through the function. This should be revisited if
9200     // -Wrepeated-use-of-weak is made flow-sensitive.
9201     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9202         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9203                          Init->getLocStart()))
9204         getCurFunction()->markSafeWeakUse(Init);
9205   }
9206 
9207   // The initialization is usually a full-expression.
9208   //
9209   // FIXME: If this is a braced initialization of an aggregate, it is not
9210   // an expression, and each individual field initializer is a separate
9211   // full-expression. For instance, in:
9212   //
9213   //   struct Temp { ~Temp(); };
9214   //   struct S { S(Temp); };
9215   //   struct T { S a, b; } t = { Temp(), Temp() }
9216   //
9217   // we should destroy the first Temp before constructing the second.
9218   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9219                                           false,
9220                                           VDecl->isConstexpr());
9221   if (Result.isInvalid()) {
9222     VDecl->setInvalidDecl();
9223     return;
9224   }
9225   Init = Result.get();
9226 
9227   // Attach the initializer to the decl.
9228   VDecl->setInit(Init);
9229 
9230   if (VDecl->isLocalVarDecl()) {
9231     // C99 6.7.8p4: All the expressions in an initializer for an object that has
9232     // static storage duration shall be constant expressions or string literals.
9233     // C++ does not have this restriction.
9234     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9235       const Expr *Culprit;
9236       if (VDecl->getStorageClass() == SC_Static)
9237         CheckForConstantInitializer(Init, DclT);
9238       // C89 is stricter than C99 for non-static aggregate types.
9239       // C89 6.5.7p3: All the expressions [...] in an initializer list
9240       // for an object that has aggregate or union type shall be
9241       // constant expressions.
9242       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9243                isa<InitListExpr>(Init) &&
9244                !Init->isConstantInitializer(Context, false, &Culprit))
9245         Diag(Culprit->getExprLoc(),
9246              diag::ext_aggregate_init_not_constant)
9247           << Culprit->getSourceRange();
9248     }
9249   } else if (VDecl->isStaticDataMember() &&
9250              VDecl->getLexicalDeclContext()->isRecord()) {
9251     // This is an in-class initialization for a static data member, e.g.,
9252     //
9253     // struct S {
9254     //   static const int value = 17;
9255     // };
9256 
9257     // C++ [class.mem]p4:
9258     //   A member-declarator can contain a constant-initializer only
9259     //   if it declares a static member (9.4) of const integral or
9260     //   const enumeration type, see 9.4.2.
9261     //
9262     // C++11 [class.static.data]p3:
9263     //   If a non-volatile const static data member is of integral or
9264     //   enumeration type, its declaration in the class definition can
9265     //   specify a brace-or-equal-initializer in which every initalizer-clause
9266     //   that is an assignment-expression is a constant expression. A static
9267     //   data member of literal type can be declared in the class definition
9268     //   with the constexpr specifier; if so, its declaration shall specify a
9269     //   brace-or-equal-initializer in which every initializer-clause that is
9270     //   an assignment-expression is a constant expression.
9271 
9272     // Do nothing on dependent types.
9273     if (DclT->isDependentType()) {
9274 
9275     // Allow any 'static constexpr' members, whether or not they are of literal
9276     // type. We separately check that every constexpr variable is of literal
9277     // type.
9278     } else if (VDecl->isConstexpr()) {
9279 
9280     // Require constness.
9281     } else if (!DclT.isConstQualified()) {
9282       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9283         << Init->getSourceRange();
9284       VDecl->setInvalidDecl();
9285 
9286     // We allow integer constant expressions in all cases.
9287     } else if (DclT->isIntegralOrEnumerationType()) {
9288       // Check whether the expression is a constant expression.
9289       SourceLocation Loc;
9290       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9291         // In C++11, a non-constexpr const static data member with an
9292         // in-class initializer cannot be volatile.
9293         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9294       else if (Init->isValueDependent())
9295         ; // Nothing to check.
9296       else if (Init->isIntegerConstantExpr(Context, &Loc))
9297         ; // Ok, it's an ICE!
9298       else if (Init->isEvaluatable(Context)) {
9299         // If we can constant fold the initializer through heroics, accept it,
9300         // but report this as a use of an extension for -pedantic.
9301         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9302           << Init->getSourceRange();
9303       } else {
9304         // Otherwise, this is some crazy unknown case.  Report the issue at the
9305         // location provided by the isIntegerConstantExpr failed check.
9306         Diag(Loc, diag::err_in_class_initializer_non_constant)
9307           << Init->getSourceRange();
9308         VDecl->setInvalidDecl();
9309       }
9310 
9311     // We allow foldable floating-point constants as an extension.
9312     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9313       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9314       // it anyway and provide a fixit to add the 'constexpr'.
9315       if (getLangOpts().CPlusPlus11) {
9316         Diag(VDecl->getLocation(),
9317              diag::ext_in_class_initializer_float_type_cxx11)
9318             << DclT << Init->getSourceRange();
9319         Diag(VDecl->getLocStart(),
9320              diag::note_in_class_initializer_float_type_cxx11)
9321             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9322       } else {
9323         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9324           << DclT << Init->getSourceRange();
9325 
9326         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9327           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9328             << Init->getSourceRange();
9329           VDecl->setInvalidDecl();
9330         }
9331       }
9332 
9333     // Suggest adding 'constexpr' in C++11 for literal types.
9334     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9335       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9336         << DclT << Init->getSourceRange()
9337         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9338       VDecl->setConstexpr(true);
9339 
9340     } else {
9341       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9342         << DclT << Init->getSourceRange();
9343       VDecl->setInvalidDecl();
9344     }
9345   } else if (VDecl->isFileVarDecl()) {
9346     if (VDecl->getStorageClass() == SC_Extern &&
9347         (!getLangOpts().CPlusPlus ||
9348          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9349            VDecl->isExternC())) &&
9350         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9351       Diag(VDecl->getLocation(), diag::warn_extern_init);
9352 
9353     // C99 6.7.8p4. All file scoped initializers need to be constant.
9354     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9355       CheckForConstantInitializer(Init, DclT);
9356   }
9357 
9358   // We will represent direct-initialization similarly to copy-initialization:
9359   //    int x(1);  -as-> int x = 1;
9360   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9361   //
9362   // Clients that want to distinguish between the two forms, can check for
9363   // direct initializer using VarDecl::getInitStyle().
9364   // A major benefit is that clients that don't particularly care about which
9365   // exactly form was it (like the CodeGen) can handle both cases without
9366   // special case code.
9367 
9368   // C++ 8.5p11:
9369   // The form of initialization (using parentheses or '=') is generally
9370   // insignificant, but does matter when the entity being initialized has a
9371   // class type.
9372   if (CXXDirectInit) {
9373     assert(DirectInit && "Call-style initializer must be direct init.");
9374     VDecl->setInitStyle(VarDecl::CallInit);
9375   } else if (DirectInit) {
9376     // This must be list-initialization. No other way is direct-initialization.
9377     VDecl->setInitStyle(VarDecl::ListInit);
9378   }
9379 
9380   CheckCompleteVariableDeclaration(VDecl);
9381 }
9382 
9383 /// ActOnInitializerError - Given that there was an error parsing an
9384 /// initializer for the given declaration, try to return to some form
9385 /// of sanity.
9386 void Sema::ActOnInitializerError(Decl *D) {
9387   // Our main concern here is re-establishing invariants like "a
9388   // variable's type is either dependent or complete".
9389   if (!D || D->isInvalidDecl()) return;
9390 
9391   VarDecl *VD = dyn_cast<VarDecl>(D);
9392   if (!VD) return;
9393 
9394   // Auto types are meaningless if we can't make sense of the initializer.
9395   if (ParsingInitForAutoVars.count(D)) {
9396     D->setInvalidDecl();
9397     return;
9398   }
9399 
9400   QualType Ty = VD->getType();
9401   if (Ty->isDependentType()) return;
9402 
9403   // Require a complete type.
9404   if (RequireCompleteType(VD->getLocation(),
9405                           Context.getBaseElementType(Ty),
9406                           diag::err_typecheck_decl_incomplete_type)) {
9407     VD->setInvalidDecl();
9408     return;
9409   }
9410 
9411   // Require a non-abstract type.
9412   if (RequireNonAbstractType(VD->getLocation(), Ty,
9413                              diag::err_abstract_type_in_decl,
9414                              AbstractVariableType)) {
9415     VD->setInvalidDecl();
9416     return;
9417   }
9418 
9419   // Don't bother complaining about constructors or destructors,
9420   // though.
9421 }
9422 
9423 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9424                                   bool TypeMayContainAuto) {
9425   // If there is no declaration, there was an error parsing it. Just ignore it.
9426   if (!RealDecl)
9427     return;
9428 
9429   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9430     QualType Type = Var->getType();
9431 
9432     // C++11 [dcl.spec.auto]p3
9433     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9434       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9435         << Var->getDeclName() << Type;
9436       Var->setInvalidDecl();
9437       return;
9438     }
9439 
9440     // C++11 [class.static.data]p3: A static data member can be declared with
9441     // the constexpr specifier; if so, its declaration shall specify
9442     // a brace-or-equal-initializer.
9443     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9444     // the definition of a variable [...] or the declaration of a static data
9445     // member.
9446     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9447       if (Var->isStaticDataMember())
9448         Diag(Var->getLocation(),
9449              diag::err_constexpr_static_mem_var_requires_init)
9450           << Var->getDeclName();
9451       else
9452         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9453       Var->setInvalidDecl();
9454       return;
9455     }
9456 
9457     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
9458     // definition having the concept specifier is called a variable concept. A
9459     // concept definition refers to [...] a variable concept and its initializer.
9460     if (Var->isConcept()) {
9461       Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
9462       Var->setInvalidDecl();
9463       return;
9464     }
9465 
9466     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9467     // be initialized.
9468     if (!Var->isInvalidDecl() &&
9469         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9470         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9471       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9472       Var->setInvalidDecl();
9473       return;
9474     }
9475 
9476     switch (Var->isThisDeclarationADefinition()) {
9477     case VarDecl::Definition:
9478       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9479         break;
9480 
9481       // We have an out-of-line definition of a static data member
9482       // that has an in-class initializer, so we type-check this like
9483       // a declaration.
9484       //
9485       // Fall through
9486 
9487     case VarDecl::DeclarationOnly:
9488       // It's only a declaration.
9489 
9490       // Block scope. C99 6.7p7: If an identifier for an object is
9491       // declared with no linkage (C99 6.2.2p6), the type for the
9492       // object shall be complete.
9493       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9494           !Var->hasLinkage() && !Var->isInvalidDecl() &&
9495           RequireCompleteType(Var->getLocation(), Type,
9496                               diag::err_typecheck_decl_incomplete_type))
9497         Var->setInvalidDecl();
9498 
9499       // Make sure that the type is not abstract.
9500       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9501           RequireNonAbstractType(Var->getLocation(), Type,
9502                                  diag::err_abstract_type_in_decl,
9503                                  AbstractVariableType))
9504         Var->setInvalidDecl();
9505       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9506           Var->getStorageClass() == SC_PrivateExtern) {
9507         Diag(Var->getLocation(), diag::warn_private_extern);
9508         Diag(Var->getLocation(), diag::note_private_extern);
9509       }
9510 
9511       return;
9512 
9513     case VarDecl::TentativeDefinition:
9514       // File scope. C99 6.9.2p2: A declaration of an identifier for an
9515       // object that has file scope without an initializer, and without a
9516       // storage-class specifier or with the storage-class specifier "static",
9517       // constitutes a tentative definition. Note: A tentative definition with
9518       // external linkage is valid (C99 6.2.2p5).
9519       if (!Var->isInvalidDecl()) {
9520         if (const IncompleteArrayType *ArrayT
9521                                     = Context.getAsIncompleteArrayType(Type)) {
9522           if (RequireCompleteType(Var->getLocation(),
9523                                   ArrayT->getElementType(),
9524                                   diag::err_illegal_decl_array_incomplete_type))
9525             Var->setInvalidDecl();
9526         } else if (Var->getStorageClass() == SC_Static) {
9527           // C99 6.9.2p3: If the declaration of an identifier for an object is
9528           // a tentative definition and has internal linkage (C99 6.2.2p3), the
9529           // declared type shall not be an incomplete type.
9530           // NOTE: code such as the following
9531           //     static struct s;
9532           //     struct s { int a; };
9533           // is accepted by gcc. Hence here we issue a warning instead of
9534           // an error and we do not invalidate the static declaration.
9535           // NOTE: to avoid multiple warnings, only check the first declaration.
9536           if (Var->isFirstDecl())
9537             RequireCompleteType(Var->getLocation(), Type,
9538                                 diag::ext_typecheck_decl_incomplete_type);
9539         }
9540       }
9541 
9542       // Record the tentative definition; we're done.
9543       if (!Var->isInvalidDecl())
9544         TentativeDefinitions.push_back(Var);
9545       return;
9546     }
9547 
9548     // Provide a specific diagnostic for uninitialized variable
9549     // definitions with incomplete array type.
9550     if (Type->isIncompleteArrayType()) {
9551       Diag(Var->getLocation(),
9552            diag::err_typecheck_incomplete_array_needs_initializer);
9553       Var->setInvalidDecl();
9554       return;
9555     }
9556 
9557     // Provide a specific diagnostic for uninitialized variable
9558     // definitions with reference type.
9559     if (Type->isReferenceType()) {
9560       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9561         << Var->getDeclName()
9562         << SourceRange(Var->getLocation(), Var->getLocation());
9563       Var->setInvalidDecl();
9564       return;
9565     }
9566 
9567     // Do not attempt to type-check the default initializer for a
9568     // variable with dependent type.
9569     if (Type->isDependentType())
9570       return;
9571 
9572     if (Var->isInvalidDecl())
9573       return;
9574 
9575     if (!Var->hasAttr<AliasAttr>()) {
9576       if (RequireCompleteType(Var->getLocation(),
9577                               Context.getBaseElementType(Type),
9578                               diag::err_typecheck_decl_incomplete_type)) {
9579         Var->setInvalidDecl();
9580         return;
9581       }
9582     } else {
9583       return;
9584     }
9585 
9586     // The variable can not have an abstract class type.
9587     if (RequireNonAbstractType(Var->getLocation(), Type,
9588                                diag::err_abstract_type_in_decl,
9589                                AbstractVariableType)) {
9590       Var->setInvalidDecl();
9591       return;
9592     }
9593 
9594     // Check for jumps past the implicit initializer.  C++0x
9595     // clarifies that this applies to a "variable with automatic
9596     // storage duration", not a "local variable".
9597     // C++11 [stmt.dcl]p3
9598     //   A program that jumps from a point where a variable with automatic
9599     //   storage duration is not in scope to a point where it is in scope is
9600     //   ill-formed unless the variable has scalar type, class type with a
9601     //   trivial default constructor and a trivial destructor, a cv-qualified
9602     //   version of one of these types, or an array of one of the preceding
9603     //   types and is declared without an initializer.
9604     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9605       if (const RecordType *Record
9606             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
9607         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9608         // Mark the function for further checking even if the looser rules of
9609         // C++11 do not require such checks, so that we can diagnose
9610         // incompatibilities with C++98.
9611         if (!CXXRecord->isPOD())
9612           getCurFunction()->setHasBranchProtectedScope();
9613       }
9614     }
9615 
9616     // C++03 [dcl.init]p9:
9617     //   If no initializer is specified for an object, and the
9618     //   object is of (possibly cv-qualified) non-POD class type (or
9619     //   array thereof), the object shall be default-initialized; if
9620     //   the object is of const-qualified type, the underlying class
9621     //   type shall have a user-declared default
9622     //   constructor. Otherwise, if no initializer is specified for
9623     //   a non- static object, the object and its subobjects, if
9624     //   any, have an indeterminate initial value); if the object
9625     //   or any of its subobjects are of const-qualified type, the
9626     //   program is ill-formed.
9627     // C++0x [dcl.init]p11:
9628     //   If no initializer is specified for an object, the object is
9629     //   default-initialized; [...].
9630     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
9631     InitializationKind Kind
9632       = InitializationKind::CreateDefault(Var->getLocation());
9633 
9634     InitializationSequence InitSeq(*this, Entity, Kind, None);
9635     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
9636     if (Init.isInvalid())
9637       Var->setInvalidDecl();
9638     else if (Init.get()) {
9639       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
9640       // This is important for template substitution.
9641       Var->setInitStyle(VarDecl::CallInit);
9642     }
9643 
9644     CheckCompleteVariableDeclaration(Var);
9645   }
9646 }
9647 
9648 void Sema::ActOnCXXForRangeDecl(Decl *D) {
9649   VarDecl *VD = dyn_cast<VarDecl>(D);
9650   if (!VD) {
9651     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9652     D->setInvalidDecl();
9653     return;
9654   }
9655 
9656   VD->setCXXForRangeDecl(true);
9657 
9658   // for-range-declaration cannot be given a storage class specifier.
9659   int Error = -1;
9660   switch (VD->getStorageClass()) {
9661   case SC_None:
9662     break;
9663   case SC_Extern:
9664     Error = 0;
9665     break;
9666   case SC_Static:
9667     Error = 1;
9668     break;
9669   case SC_PrivateExtern:
9670     Error = 2;
9671     break;
9672   case SC_Auto:
9673     Error = 3;
9674     break;
9675   case SC_Register:
9676     Error = 4;
9677     break;
9678   case SC_OpenCLWorkGroupLocal:
9679     llvm_unreachable("Unexpected storage class");
9680   }
9681   if (Error != -1) {
9682     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
9683       << VD->getDeclName() << Error;
9684     D->setInvalidDecl();
9685   }
9686 }
9687 
9688 StmtResult
9689 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
9690                                  IdentifierInfo *Ident,
9691                                  ParsedAttributes &Attrs,
9692                                  SourceLocation AttrEnd) {
9693   // C++1y [stmt.iter]p1:
9694   //   A range-based for statement of the form
9695   //      for ( for-range-identifier : for-range-initializer ) statement
9696   //   is equivalent to
9697   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
9698   DeclSpec DS(Attrs.getPool().getFactory());
9699 
9700   const char *PrevSpec;
9701   unsigned DiagID;
9702   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
9703                      getPrintingPolicy());
9704 
9705   Declarator D(DS, Declarator::ForContext);
9706   D.SetIdentifier(Ident, IdentLoc);
9707   D.takeAttributes(Attrs, AttrEnd);
9708 
9709   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
9710   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
9711                 EmptyAttrs, IdentLoc);
9712   Decl *Var = ActOnDeclarator(S, D);
9713   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
9714   FinalizeDeclaration(Var);
9715   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
9716                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
9717 }
9718 
9719 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
9720   if (var->isInvalidDecl()) return;
9721 
9722   // In ARC, don't allow jumps past the implicit initialization of a
9723   // local retaining variable.
9724   if (getLangOpts().ObjCAutoRefCount &&
9725       var->hasLocalStorage()) {
9726     switch (var->getType().getObjCLifetime()) {
9727     case Qualifiers::OCL_None:
9728     case Qualifiers::OCL_ExplicitNone:
9729     case Qualifiers::OCL_Autoreleasing:
9730       break;
9731 
9732     case Qualifiers::OCL_Weak:
9733     case Qualifiers::OCL_Strong:
9734       getCurFunction()->setHasBranchProtectedScope();
9735       break;
9736     }
9737   }
9738 
9739   // Warn about externally-visible variables being defined without a
9740   // prior declaration.  We only want to do this for global
9741   // declarations, but we also specifically need to avoid doing it for
9742   // class members because the linkage of an anonymous class can
9743   // change if it's later given a typedef name.
9744   if (var->isThisDeclarationADefinition() &&
9745       var->getDeclContext()->getRedeclContext()->isFileContext() &&
9746       var->isExternallyVisible() && var->hasLinkage() &&
9747       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
9748                                   var->getLocation())) {
9749     // Find a previous declaration that's not a definition.
9750     VarDecl *prev = var->getPreviousDecl();
9751     while (prev && prev->isThisDeclarationADefinition())
9752       prev = prev->getPreviousDecl();
9753 
9754     if (!prev)
9755       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
9756   }
9757 
9758   if (var->getTLSKind() == VarDecl::TLS_Static) {
9759     const Expr *Culprit;
9760     if (var->getType().isDestructedType()) {
9761       // GNU C++98 edits for __thread, [basic.start.term]p3:
9762       //   The type of an object with thread storage duration shall not
9763       //   have a non-trivial destructor.
9764       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
9765       if (getLangOpts().CPlusPlus11)
9766         Diag(var->getLocation(), diag::note_use_thread_local);
9767     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
9768                !var->getInit()->isConstantInitializer(
9769                    Context, var->getType()->isReferenceType(), &Culprit)) {
9770       // GNU C++98 edits for __thread, [basic.start.init]p4:
9771       //   An object of thread storage duration shall not require dynamic
9772       //   initialization.
9773       // FIXME: Need strict checking here.
9774       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
9775         << Culprit->getSourceRange();
9776       if (getLangOpts().CPlusPlus11)
9777         Diag(var->getLocation(), diag::note_use_thread_local);
9778     }
9779 
9780   }
9781 
9782   // Apply section attributes and pragmas to global variables.
9783   bool GlobalStorage = var->hasGlobalStorage();
9784   if (GlobalStorage && var->isThisDeclarationADefinition() &&
9785       ActiveTemplateInstantiations.empty()) {
9786     PragmaStack<StringLiteral *> *Stack = nullptr;
9787     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
9788     if (var->getType().isConstQualified())
9789       Stack = &ConstSegStack;
9790     else if (!var->getInit()) {
9791       Stack = &BSSSegStack;
9792       SectionFlags |= ASTContext::PSF_Write;
9793     } else {
9794       Stack = &DataSegStack;
9795       SectionFlags |= ASTContext::PSF_Write;
9796     }
9797     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
9798       var->addAttr(SectionAttr::CreateImplicit(
9799           Context, SectionAttr::Declspec_allocate,
9800           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
9801     }
9802     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
9803       if (UnifySection(SA->getName(), SectionFlags, var))
9804         var->dropAttr<SectionAttr>();
9805 
9806     // Apply the init_seg attribute if this has an initializer.  If the
9807     // initializer turns out to not be dynamic, we'll end up ignoring this
9808     // attribute.
9809     if (CurInitSeg && var->getInit())
9810       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
9811                                                CurInitSegLoc));
9812   }
9813 
9814   // All the following checks are C++ only.
9815   if (!getLangOpts().CPlusPlus) return;
9816 
9817   QualType type = var->getType();
9818   if (type->isDependentType()) return;
9819 
9820   // __block variables might require us to capture a copy-initializer.
9821   if (var->hasAttr<BlocksAttr>()) {
9822     // It's currently invalid to ever have a __block variable with an
9823     // array type; should we diagnose that here?
9824 
9825     // Regardless, we don't want to ignore array nesting when
9826     // constructing this copy.
9827     if (type->isStructureOrClassType()) {
9828       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
9829       SourceLocation poi = var->getLocation();
9830       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
9831       ExprResult result
9832         = PerformMoveOrCopyInitialization(
9833             InitializedEntity::InitializeBlock(poi, type, false),
9834             var, var->getType(), varRef, /*AllowNRVO=*/true);
9835       if (!result.isInvalid()) {
9836         result = MaybeCreateExprWithCleanups(result);
9837         Expr *init = result.getAs<Expr>();
9838         Context.setBlockVarCopyInits(var, init);
9839       }
9840     }
9841   }
9842 
9843   Expr *Init = var->getInit();
9844   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
9845   QualType baseType = Context.getBaseElementType(type);
9846 
9847   if (!var->getDeclContext()->isDependentContext() &&
9848       Init && !Init->isValueDependent()) {
9849     if (IsGlobal && !var->isConstexpr() &&
9850         !getDiagnostics().isIgnored(diag::warn_global_constructor,
9851                                     var->getLocation())) {
9852       // Warn about globals which don't have a constant initializer.  Don't
9853       // warn about globals with a non-trivial destructor because we already
9854       // warned about them.
9855       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
9856       if (!(RD && !RD->hasTrivialDestructor()) &&
9857           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
9858         Diag(var->getLocation(), diag::warn_global_constructor)
9859           << Init->getSourceRange();
9860     }
9861 
9862     if (var->isConstexpr()) {
9863       SmallVector<PartialDiagnosticAt, 8> Notes;
9864       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
9865         SourceLocation DiagLoc = var->getLocation();
9866         // If the note doesn't add any useful information other than a source
9867         // location, fold it into the primary diagnostic.
9868         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9869               diag::note_invalid_subexpr_in_const_expr) {
9870           DiagLoc = Notes[0].first;
9871           Notes.clear();
9872         }
9873         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
9874           << var << Init->getSourceRange();
9875         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9876           Diag(Notes[I].first, Notes[I].second);
9877       }
9878     } else if (var->isUsableInConstantExpressions(Context)) {
9879       // Check whether the initializer of a const variable of integral or
9880       // enumeration type is an ICE now, since we can't tell whether it was
9881       // initialized by a constant expression if we check later.
9882       var->checkInitIsICE();
9883     }
9884   }
9885 
9886   // Require the destructor.
9887   if (const RecordType *recordType = baseType->getAs<RecordType>())
9888     FinalizeVarWithDestructor(var, recordType);
9889 }
9890 
9891 /// \brief Determines if a variable's alignment is dependent.
9892 static bool hasDependentAlignment(VarDecl *VD) {
9893   if (VD->getType()->isDependentType())
9894     return true;
9895   for (auto *I : VD->specific_attrs<AlignedAttr>())
9896     if (I->isAlignmentDependent())
9897       return true;
9898   return false;
9899 }
9900 
9901 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
9902 /// any semantic actions necessary after any initializer has been attached.
9903 void
9904 Sema::FinalizeDeclaration(Decl *ThisDecl) {
9905   // Note that we are no longer parsing the initializer for this declaration.
9906   ParsingInitForAutoVars.erase(ThisDecl);
9907 
9908   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
9909   if (!VD)
9910     return;
9911 
9912   checkAttributesAfterMerging(*this, *VD);
9913 
9914   // Perform TLS alignment check here after attributes attached to the variable
9915   // which may affect the alignment have been processed. Only perform the check
9916   // if the target has a maximum TLS alignment (zero means no constraints).
9917   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
9918     // Protect the check so that it's not performed on dependent types and
9919     // dependent alignments (we can't determine the alignment in that case).
9920     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
9921       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
9922       if (Context.getDeclAlign(VD) > MaxAlignChars) {
9923         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
9924           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
9925           << (unsigned)MaxAlignChars.getQuantity();
9926       }
9927     }
9928   }
9929 
9930   // Static locals inherit dll attributes from their function.
9931   if (VD->isStaticLocal()) {
9932     if (FunctionDecl *FD =
9933             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
9934       if (Attr *A = getDLLAttr(FD)) {
9935         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
9936         NewAttr->setInherited(true);
9937         VD->addAttr(NewAttr);
9938       }
9939     }
9940   }
9941 
9942   // Grab the dllimport or dllexport attribute off of the VarDecl.
9943   const InheritableAttr *DLLAttr = getDLLAttr(VD);
9944 
9945   // Imported static data members cannot be defined out-of-line.
9946   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
9947     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
9948         VD->isThisDeclarationADefinition()) {
9949       // We allow definitions of dllimport class template static data members
9950       // with a warning.
9951       CXXRecordDecl *Context =
9952         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
9953       bool IsClassTemplateMember =
9954           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
9955           Context->getDescribedClassTemplate();
9956 
9957       Diag(VD->getLocation(),
9958            IsClassTemplateMember
9959                ? diag::warn_attribute_dllimport_static_field_definition
9960                : diag::err_attribute_dllimport_static_field_definition);
9961       Diag(IA->getLocation(), diag::note_attribute);
9962       if (!IsClassTemplateMember)
9963         VD->setInvalidDecl();
9964     }
9965   }
9966 
9967   // dllimport/dllexport variables cannot be thread local, their TLS index
9968   // isn't exported with the variable.
9969   if (DLLAttr && VD->getTLSKind()) {
9970     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
9971     if (F && getDLLAttr(F)) {
9972       assert(VD->isStaticLocal());
9973       // But if this is a static local in a dlimport/dllexport function, the
9974       // function will never be inlined, which means the var would never be
9975       // imported, so having it marked import/export is safe.
9976     } else {
9977       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
9978                                                                     << DLLAttr;
9979       VD->setInvalidDecl();
9980     }
9981   }
9982 
9983   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
9984     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
9985       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
9986       VD->dropAttr<UsedAttr>();
9987     }
9988   }
9989 
9990   const DeclContext *DC = VD->getDeclContext();
9991   // If there's a #pragma GCC visibility in scope, and this isn't a class
9992   // member, set the visibility of this variable.
9993   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
9994     AddPushedVisibilityAttribute(VD);
9995 
9996   // FIXME: Warn on unused templates.
9997   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
9998       !isa<VarTemplatePartialSpecializationDecl>(VD))
9999     MarkUnusedFileScopedDecl(VD);
10000 
10001   // Now we have parsed the initializer and can update the table of magic
10002   // tag values.
10003   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10004       !VD->getType()->isIntegralOrEnumerationType())
10005     return;
10006 
10007   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10008     const Expr *MagicValueExpr = VD->getInit();
10009     if (!MagicValueExpr) {
10010       continue;
10011     }
10012     llvm::APSInt MagicValueInt;
10013     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10014       Diag(I->getRange().getBegin(),
10015            diag::err_type_tag_for_datatype_not_ice)
10016         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10017       continue;
10018     }
10019     if (MagicValueInt.getActiveBits() > 64) {
10020       Diag(I->getRange().getBegin(),
10021            diag::err_type_tag_for_datatype_too_large)
10022         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10023       continue;
10024     }
10025     uint64_t MagicValue = MagicValueInt.getZExtValue();
10026     RegisterTypeTagForDatatype(I->getArgumentKind(),
10027                                MagicValue,
10028                                I->getMatchingCType(),
10029                                I->getLayoutCompatible(),
10030                                I->getMustBeNull());
10031   }
10032 }
10033 
10034 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10035                                                    ArrayRef<Decl *> Group) {
10036   SmallVector<Decl*, 8> Decls;
10037 
10038   if (DS.isTypeSpecOwned())
10039     Decls.push_back(DS.getRepAsDecl());
10040 
10041   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10042   for (unsigned i = 0, e = Group.size(); i != e; ++i)
10043     if (Decl *D = Group[i]) {
10044       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10045         if (!FirstDeclaratorInGroup)
10046           FirstDeclaratorInGroup = DD;
10047       Decls.push_back(D);
10048     }
10049 
10050   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10051     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10052       handleTagNumbering(Tag, S);
10053       if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
10054         Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
10055     }
10056   }
10057 
10058   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10059 }
10060 
10061 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10062 /// group, performing any necessary semantic checking.
10063 Sema::DeclGroupPtrTy
10064 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10065                            bool TypeMayContainAuto) {
10066   // C++0x [dcl.spec.auto]p7:
10067   //   If the type deduced for the template parameter U is not the same in each
10068   //   deduction, the program is ill-formed.
10069   // FIXME: When initializer-list support is added, a distinction is needed
10070   // between the deduced type U and the deduced type which 'auto' stands for.
10071   //   auto a = 0, b = { 1, 2, 3 };
10072   // is legal because the deduced type U is 'int' in both cases.
10073   if (TypeMayContainAuto && Group.size() > 1) {
10074     QualType Deduced;
10075     CanQualType DeducedCanon;
10076     VarDecl *DeducedDecl = nullptr;
10077     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10078       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10079         AutoType *AT = D->getType()->getContainedAutoType();
10080         // Don't reissue diagnostics when instantiating a template.
10081         if (AT && D->isInvalidDecl())
10082           break;
10083         QualType U = AT ? AT->getDeducedType() : QualType();
10084         if (!U.isNull()) {
10085           CanQualType UCanon = Context.getCanonicalType(U);
10086           if (Deduced.isNull()) {
10087             Deduced = U;
10088             DeducedCanon = UCanon;
10089             DeducedDecl = D;
10090           } else if (DeducedCanon != UCanon) {
10091             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10092                  diag::err_auto_different_deductions)
10093               << (AT->isDecltypeAuto() ? 1 : 0)
10094               << Deduced << DeducedDecl->getDeclName()
10095               << U << D->getDeclName()
10096               << DeducedDecl->getInit()->getSourceRange()
10097               << D->getInit()->getSourceRange();
10098             D->setInvalidDecl();
10099             break;
10100           }
10101         }
10102       }
10103     }
10104   }
10105 
10106   ActOnDocumentableDecls(Group);
10107 
10108   return DeclGroupPtrTy::make(
10109       DeclGroupRef::Create(Context, Group.data(), Group.size()));
10110 }
10111 
10112 void Sema::ActOnDocumentableDecl(Decl *D) {
10113   ActOnDocumentableDecls(D);
10114 }
10115 
10116 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10117   // Don't parse the comment if Doxygen diagnostics are ignored.
10118   if (Group.empty() || !Group[0])
10119     return;
10120 
10121   if (Diags.isIgnored(diag::warn_doc_param_not_found,
10122                       Group[0]->getLocation()) &&
10123       Diags.isIgnored(diag::warn_unknown_comment_command_name,
10124                       Group[0]->getLocation()))
10125     return;
10126 
10127   if (Group.size() >= 2) {
10128     // This is a decl group.  Normally it will contain only declarations
10129     // produced from declarator list.  But in case we have any definitions or
10130     // additional declaration references:
10131     //   'typedef struct S {} S;'
10132     //   'typedef struct S *S;'
10133     //   'struct S *pS;'
10134     // FinalizeDeclaratorGroup adds these as separate declarations.
10135     Decl *MaybeTagDecl = Group[0];
10136     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10137       Group = Group.slice(1);
10138     }
10139   }
10140 
10141   // See if there are any new comments that are not attached to a decl.
10142   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10143   if (!Comments.empty() &&
10144       !Comments.back()->isAttached()) {
10145     // There is at least one comment that not attached to a decl.
10146     // Maybe it should be attached to one of these decls?
10147     //
10148     // Note that this way we pick up not only comments that precede the
10149     // declaration, but also comments that *follow* the declaration -- thanks to
10150     // the lookahead in the lexer: we've consumed the semicolon and looked
10151     // ahead through comments.
10152     for (unsigned i = 0, e = Group.size(); i != e; ++i)
10153       Context.getCommentForDecl(Group[i], &PP);
10154   }
10155 }
10156 
10157 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10158 /// to introduce parameters into function prototype scope.
10159 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10160   const DeclSpec &DS = D.getDeclSpec();
10161 
10162   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10163 
10164   // C++03 [dcl.stc]p2 also permits 'auto'.
10165   StorageClass SC = SC_None;
10166   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10167     SC = SC_Register;
10168   } else if (getLangOpts().CPlusPlus &&
10169              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10170     SC = SC_Auto;
10171   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10172     Diag(DS.getStorageClassSpecLoc(),
10173          diag::err_invalid_storage_class_in_func_decl);
10174     D.getMutableDeclSpec().ClearStorageClassSpecs();
10175   }
10176 
10177   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10178     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10179       << DeclSpec::getSpecifierName(TSCS);
10180   if (DS.isConstexprSpecified())
10181     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10182       << 0;
10183 
10184   DiagnoseFunctionSpecifiers(DS);
10185 
10186   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10187   QualType parmDeclType = TInfo->getType();
10188 
10189   if (getLangOpts().CPlusPlus) {
10190     // Check that there are no default arguments inside the type of this
10191     // parameter.
10192     CheckExtraCXXDefaultArguments(D);
10193 
10194     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10195     if (D.getCXXScopeSpec().isSet()) {
10196       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10197         << D.getCXXScopeSpec().getRange();
10198       D.getCXXScopeSpec().clear();
10199     }
10200   }
10201 
10202   // Ensure we have a valid name
10203   IdentifierInfo *II = nullptr;
10204   if (D.hasName()) {
10205     II = D.getIdentifier();
10206     if (!II) {
10207       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10208         << GetNameForDeclarator(D).getName();
10209       D.setInvalidType(true);
10210     }
10211   }
10212 
10213   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10214   if (II) {
10215     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10216                    ForRedeclaration);
10217     LookupName(R, S);
10218     if (R.isSingleResult()) {
10219       NamedDecl *PrevDecl = R.getFoundDecl();
10220       if (PrevDecl->isTemplateParameter()) {
10221         // Maybe we will complain about the shadowed template parameter.
10222         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10223         // Just pretend that we didn't see the previous declaration.
10224         PrevDecl = nullptr;
10225       } else if (S->isDeclScope(PrevDecl)) {
10226         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10227         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10228 
10229         // Recover by removing the name
10230         II = nullptr;
10231         D.SetIdentifier(nullptr, D.getIdentifierLoc());
10232         D.setInvalidType(true);
10233       }
10234     }
10235   }
10236 
10237   // Temporarily put parameter variables in the translation unit, not
10238   // the enclosing context.  This prevents them from accidentally
10239   // looking like class members in C++.
10240   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10241                                     D.getLocStart(),
10242                                     D.getIdentifierLoc(), II,
10243                                     parmDeclType, TInfo,
10244                                     SC);
10245 
10246   if (D.isInvalidType())
10247     New->setInvalidDecl();
10248 
10249   assert(S->isFunctionPrototypeScope());
10250   assert(S->getFunctionPrototypeDepth() >= 1);
10251   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10252                     S->getNextFunctionPrototypeIndex());
10253 
10254   // Add the parameter declaration into this scope.
10255   S->AddDecl(New);
10256   if (II)
10257     IdResolver.AddDecl(New);
10258 
10259   ProcessDeclAttributes(S, New, D);
10260 
10261   if (D.getDeclSpec().isModulePrivateSpecified())
10262     Diag(New->getLocation(), diag::err_module_private_local)
10263       << 1 << New->getDeclName()
10264       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10265       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10266 
10267   if (New->hasAttr<BlocksAttr>()) {
10268     Diag(New->getLocation(), diag::err_block_on_nonlocal);
10269   }
10270   return New;
10271 }
10272 
10273 /// \brief Synthesizes a variable for a parameter arising from a
10274 /// typedef.
10275 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10276                                               SourceLocation Loc,
10277                                               QualType T) {
10278   /* FIXME: setting StartLoc == Loc.
10279      Would it be worth to modify callers so as to provide proper source
10280      location for the unnamed parameters, embedding the parameter's type? */
10281   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10282                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
10283                                            SC_None, nullptr);
10284   Param->setImplicit();
10285   return Param;
10286 }
10287 
10288 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
10289                                     ParmVarDecl * const *ParamEnd) {
10290   // Don't diagnose unused-parameter errors in template instantiations; we
10291   // will already have done so in the template itself.
10292   if (!ActiveTemplateInstantiations.empty())
10293     return;
10294 
10295   for (; Param != ParamEnd; ++Param) {
10296     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10297         !(*Param)->hasAttr<UnusedAttr>()) {
10298       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10299         << (*Param)->getDeclName();
10300     }
10301   }
10302 }
10303 
10304 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
10305                                                   ParmVarDecl * const *ParamEnd,
10306                                                   QualType ReturnTy,
10307                                                   NamedDecl *D) {
10308   if (LangOpts.NumLargeByValueCopy == 0) // No check.
10309     return;
10310 
10311   // Warn if the return value is pass-by-value and larger than the specified
10312   // threshold.
10313   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10314     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10315     if (Size > LangOpts.NumLargeByValueCopy)
10316       Diag(D->getLocation(), diag::warn_return_value_size)
10317           << D->getDeclName() << Size;
10318   }
10319 
10320   // Warn if any parameter is pass-by-value and larger than the specified
10321   // threshold.
10322   for (; Param != ParamEnd; ++Param) {
10323     QualType T = (*Param)->getType();
10324     if (T->isDependentType() || !T.isPODType(Context))
10325       continue;
10326     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10327     if (Size > LangOpts.NumLargeByValueCopy)
10328       Diag((*Param)->getLocation(), diag::warn_parameter_size)
10329           << (*Param)->getDeclName() << Size;
10330   }
10331 }
10332 
10333 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10334                                   SourceLocation NameLoc, IdentifierInfo *Name,
10335                                   QualType T, TypeSourceInfo *TSInfo,
10336                                   StorageClass SC) {
10337   // In ARC, infer a lifetime qualifier for appropriate parameter types.
10338   if (getLangOpts().ObjCAutoRefCount &&
10339       T.getObjCLifetime() == Qualifiers::OCL_None &&
10340       T->isObjCLifetimeType()) {
10341 
10342     Qualifiers::ObjCLifetime lifetime;
10343 
10344     // Special cases for arrays:
10345     //   - if it's const, use __unsafe_unretained
10346     //   - otherwise, it's an error
10347     if (T->isArrayType()) {
10348       if (!T.isConstQualified()) {
10349         DelayedDiagnostics.add(
10350             sema::DelayedDiagnostic::makeForbiddenType(
10351             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10352       }
10353       lifetime = Qualifiers::OCL_ExplicitNone;
10354     } else {
10355       lifetime = T->getObjCARCImplicitLifetime();
10356     }
10357     T = Context.getLifetimeQualifiedType(T, lifetime);
10358   }
10359 
10360   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10361                                          Context.getAdjustedParameterType(T),
10362                                          TSInfo, SC, nullptr);
10363 
10364   // Parameters can not be abstract class types.
10365   // For record types, this is done by the AbstractClassUsageDiagnoser once
10366   // the class has been completely parsed.
10367   if (!CurContext->isRecord() &&
10368       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10369                              AbstractParamType))
10370     New->setInvalidDecl();
10371 
10372   // Parameter declarators cannot be interface types. All ObjC objects are
10373   // passed by reference.
10374   if (T->isObjCObjectType()) {
10375     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10376     Diag(NameLoc,
10377          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10378       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10379     T = Context.getObjCObjectPointerType(T);
10380     New->setType(T);
10381   }
10382 
10383   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10384   // duration shall not be qualified by an address-space qualifier."
10385   // Since all parameters have automatic store duration, they can not have
10386   // an address space.
10387   if (T.getAddressSpace() != 0) {
10388     // OpenCL allows function arguments declared to be an array of a type
10389     // to be qualified with an address space.
10390     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10391       Diag(NameLoc, diag::err_arg_with_address_space);
10392       New->setInvalidDecl();
10393     }
10394   }
10395 
10396   return New;
10397 }
10398 
10399 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10400                                            SourceLocation LocAfterDecls) {
10401   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10402 
10403   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10404   // for a K&R function.
10405   if (!FTI.hasPrototype) {
10406     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10407       --i;
10408       if (FTI.Params[i].Param == nullptr) {
10409         SmallString<256> Code;
10410         llvm::raw_svector_ostream(Code)
10411             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10412         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10413             << FTI.Params[i].Ident
10414             << FixItHint::CreateInsertion(LocAfterDecls, Code);
10415 
10416         // Implicitly declare the argument as type 'int' for lack of a better
10417         // type.
10418         AttributeFactory attrs;
10419         DeclSpec DS(attrs);
10420         const char* PrevSpec; // unused
10421         unsigned DiagID; // unused
10422         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10423                            DiagID, Context.getPrintingPolicy());
10424         // Use the identifier location for the type source range.
10425         DS.SetRangeStart(FTI.Params[i].IdentLoc);
10426         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10427         Declarator ParamD(DS, Declarator::KNRTypeListContext);
10428         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10429         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10430       }
10431     }
10432   }
10433 }
10434 
10435 Decl *
10436 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
10437                               MultiTemplateParamsArg TemplateParameterLists,
10438                               SkipBodyInfo *SkipBody) {
10439   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10440   assert(D.isFunctionDeclarator() && "Not a function declarator!");
10441   Scope *ParentScope = FnBodyScope->getParent();
10442 
10443   D.setFunctionDefinitionKind(FDK_Definition);
10444   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
10445   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
10446 }
10447 
10448 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10449   Consumer.HandleInlineMethodDefinition(D);
10450 }
10451 
10452 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10453                              const FunctionDecl*& PossibleZeroParamPrototype) {
10454   // Don't warn about invalid declarations.
10455   if (FD->isInvalidDecl())
10456     return false;
10457 
10458   // Or declarations that aren't global.
10459   if (!FD->isGlobal())
10460     return false;
10461 
10462   // Don't warn about C++ member functions.
10463   if (isa<CXXMethodDecl>(FD))
10464     return false;
10465 
10466   // Don't warn about 'main'.
10467   if (FD->isMain())
10468     return false;
10469 
10470   // Don't warn about inline functions.
10471   if (FD->isInlined())
10472     return false;
10473 
10474   // Don't warn about function templates.
10475   if (FD->getDescribedFunctionTemplate())
10476     return false;
10477 
10478   // Don't warn about function template specializations.
10479   if (FD->isFunctionTemplateSpecialization())
10480     return false;
10481 
10482   // Don't warn for OpenCL kernels.
10483   if (FD->hasAttr<OpenCLKernelAttr>())
10484     return false;
10485 
10486   // Don't warn on explicitly deleted functions.
10487   if (FD->isDeleted())
10488     return false;
10489 
10490   bool MissingPrototype = true;
10491   for (const FunctionDecl *Prev = FD->getPreviousDecl();
10492        Prev; Prev = Prev->getPreviousDecl()) {
10493     // Ignore any declarations that occur in function or method
10494     // scope, because they aren't visible from the header.
10495     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10496       continue;
10497 
10498     MissingPrototype = !Prev->getType()->isFunctionProtoType();
10499     if (FD->getNumParams() == 0)
10500       PossibleZeroParamPrototype = Prev;
10501     break;
10502   }
10503 
10504   return MissingPrototype;
10505 }
10506 
10507 void
10508 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10509                                    const FunctionDecl *EffectiveDefinition,
10510                                    SkipBodyInfo *SkipBody) {
10511   // Don't complain if we're in GNU89 mode and the previous definition
10512   // was an extern inline function.
10513   const FunctionDecl *Definition = EffectiveDefinition;
10514   if (!Definition)
10515     if (!FD->isDefined(Definition))
10516       return;
10517 
10518   if (canRedefineFunction(Definition, getLangOpts()))
10519     return;
10520 
10521   // If we don't have a visible definition of the function, and it's inline or
10522   // a template, skip the new definition.
10523   if (SkipBody && !hasVisibleDefinition(Definition) &&
10524       (Definition->getFormalLinkage() == InternalLinkage ||
10525        Definition->isInlined() ||
10526        Definition->getDescribedFunctionTemplate() ||
10527        Definition->getNumTemplateParameterLists())) {
10528     SkipBody->ShouldSkip = true;
10529     if (auto *TD = Definition->getDescribedFunctionTemplate())
10530       makeMergedDefinitionVisible(TD, FD->getLocation());
10531     else
10532       makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
10533                                   FD->getLocation());
10534     return;
10535   }
10536 
10537   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10538       Definition->getStorageClass() == SC_Extern)
10539     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10540         << FD->getDeclName() << getLangOpts().CPlusPlus;
10541   else
10542     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10543 
10544   Diag(Definition->getLocation(), diag::note_previous_definition);
10545   FD->setInvalidDecl();
10546 }
10547 
10548 
10549 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10550                                    Sema &S) {
10551   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10552 
10553   LambdaScopeInfo *LSI = S.PushLambdaScope();
10554   LSI->CallOperator = CallOperator;
10555   LSI->Lambda = LambdaClass;
10556   LSI->ReturnType = CallOperator->getReturnType();
10557   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10558 
10559   if (LCD == LCD_None)
10560     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10561   else if (LCD == LCD_ByCopy)
10562     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10563   else if (LCD == LCD_ByRef)
10564     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10565   DeclarationNameInfo DNI = CallOperator->getNameInfo();
10566 
10567   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
10568   LSI->Mutable = !CallOperator->isConst();
10569 
10570   // Add the captures to the LSI so they can be noted as already
10571   // captured within tryCaptureVar.
10572   auto I = LambdaClass->field_begin();
10573   for (const auto &C : LambdaClass->captures()) {
10574     if (C.capturesVariable()) {
10575       VarDecl *VD = C.getCapturedVar();
10576       if (VD->isInitCapture())
10577         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10578       QualType CaptureType = VD->getType();
10579       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10580       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
10581           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
10582           /*EllipsisLoc*/C.isPackExpansion()
10583                          ? C.getEllipsisLoc() : SourceLocation(),
10584           CaptureType, /*Expr*/ nullptr);
10585 
10586     } else if (C.capturesThis()) {
10587       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
10588                               S.getCurrentThisType(), /*Expr*/ nullptr);
10589     } else {
10590       LSI->addVLATypeCapture(C.getLocation(), I->getType());
10591     }
10592     ++I;
10593   }
10594 }
10595 
10596 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
10597                                     SkipBodyInfo *SkipBody) {
10598   // Clear the last template instantiation error context.
10599   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10600 
10601   if (!D)
10602     return D;
10603   FunctionDecl *FD = nullptr;
10604 
10605   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10606     FD = FunTmpl->getTemplatedDecl();
10607   else
10608     FD = cast<FunctionDecl>(D);
10609 
10610   // See if this is a redefinition.
10611   if (!FD->isLateTemplateParsed()) {
10612     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
10613 
10614     // If we're skipping the body, we're done. Don't enter the scope.
10615     if (SkipBody && SkipBody->ShouldSkip)
10616       return D;
10617   }
10618 
10619   // If we are instantiating a generic lambda call operator, push
10620   // a LambdaScopeInfo onto the function stack.  But use the information
10621   // that's already been calculated (ActOnLambdaExpr) to prime the current
10622   // LambdaScopeInfo.
10623   // When the template operator is being specialized, the LambdaScopeInfo,
10624   // has to be properly restored so that tryCaptureVariable doesn't try
10625   // and capture any new variables. In addition when calculating potential
10626   // captures during transformation of nested lambdas, it is necessary to
10627   // have the LSI properly restored.
10628   if (isGenericLambdaCallOperatorSpecialization(FD)) {
10629     assert(ActiveTemplateInstantiations.size() &&
10630       "There should be an active template instantiation on the stack "
10631       "when instantiating a generic lambda!");
10632     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
10633   }
10634   else
10635     // Enter a new function scope
10636     PushFunctionScope();
10637 
10638   // Builtin functions cannot be defined.
10639   if (unsigned BuiltinID = FD->getBuiltinID()) {
10640     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10641         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
10642       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
10643       FD->setInvalidDecl();
10644     }
10645   }
10646 
10647   // The return type of a function definition must be complete
10648   // (C99 6.9.1p3, C++ [dcl.fct]p6).
10649   QualType ResultType = FD->getReturnType();
10650   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
10651       !FD->isInvalidDecl() &&
10652       RequireCompleteType(FD->getLocation(), ResultType,
10653                           diag::err_func_def_incomplete_result))
10654     FD->setInvalidDecl();
10655 
10656   if (FnBodyScope)
10657     PushDeclContext(FnBodyScope, FD);
10658 
10659   // Check the validity of our function parameters
10660   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10661                            /*CheckParameterNames=*/true);
10662 
10663   // Introduce our parameters into the function scope
10664   for (auto Param : FD->params()) {
10665     Param->setOwningFunction(FD);
10666 
10667     // If this has an identifier, add it to the scope stack.
10668     if (Param->getIdentifier() && FnBodyScope) {
10669       CheckShadow(FnBodyScope, Param);
10670 
10671       PushOnScopeChains(Param, FnBodyScope);
10672     }
10673   }
10674 
10675   // If we had any tags defined in the function prototype,
10676   // introduce them into the function scope.
10677   if (FnBodyScope) {
10678     for (ArrayRef<NamedDecl *>::iterator
10679              I = FD->getDeclsInPrototypeScope().begin(),
10680              E = FD->getDeclsInPrototypeScope().end();
10681          I != E; ++I) {
10682       NamedDecl *D = *I;
10683 
10684       // Some of these decls (like enums) may have been pinned to the
10685       // translation unit for lack of a real context earlier. If so, remove
10686       // from the translation unit and reattach to the current context.
10687       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
10688         // Is the decl actually in the context?
10689         for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
10690           if (DI == D) {
10691             Context.getTranslationUnitDecl()->removeDecl(D);
10692             break;
10693           }
10694         }
10695         // Either way, reassign the lexical decl context to our FunctionDecl.
10696         D->setLexicalDeclContext(CurContext);
10697       }
10698 
10699       // If the decl has a non-null name, make accessible in the current scope.
10700       if (!D->getName().empty())
10701         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10702 
10703       // Similarly, dive into enums and fish their constants out, making them
10704       // accessible in this scope.
10705       if (auto *ED = dyn_cast<EnumDecl>(D)) {
10706         for (auto *EI : ED->enumerators())
10707           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
10708       }
10709     }
10710   }
10711 
10712   // Ensure that the function's exception specification is instantiated.
10713   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10714     ResolveExceptionSpec(D->getLocation(), FPT);
10715 
10716   // dllimport cannot be applied to non-inline function definitions.
10717   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10718       !FD->isTemplateInstantiation()) {
10719     assert(!FD->hasAttr<DLLExportAttr>());
10720     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10721     FD->setInvalidDecl();
10722     return D;
10723   }
10724   // We want to attach documentation to original Decl (which might be
10725   // a function template).
10726   ActOnDocumentableDecl(D);
10727   if (getCurLexicalContext()->isObjCContainer() &&
10728       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10729       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10730     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10731 
10732   return D;
10733 }
10734 
10735 /// \brief Given the set of return statements within a function body,
10736 /// compute the variables that are subject to the named return value
10737 /// optimization.
10738 ///
10739 /// Each of the variables that is subject to the named return value
10740 /// optimization will be marked as NRVO variables in the AST, and any
10741 /// return statement that has a marked NRVO variable as its NRVO candidate can
10742 /// use the named return value optimization.
10743 ///
10744 /// This function applies a very simplistic algorithm for NRVO: if every return
10745 /// statement in the scope of a variable has the same NRVO candidate, that
10746 /// candidate is an NRVO variable.
10747 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
10748   ReturnStmt **Returns = Scope->Returns.data();
10749 
10750   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
10751     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
10752       if (!NRVOCandidate->isNRVOVariable())
10753         Returns[I]->setNRVOCandidate(nullptr);
10754     }
10755   }
10756 }
10757 
10758 bool Sema::canDelayFunctionBody(const Declarator &D) {
10759   // We can't delay parsing the body of a constexpr function template (yet).
10760   if (D.getDeclSpec().isConstexprSpecified())
10761     return false;
10762 
10763   // We can't delay parsing the body of a function template with a deduced
10764   // return type (yet).
10765   if (D.getDeclSpec().containsPlaceholderType()) {
10766     // If the placeholder introduces a non-deduced trailing return type,
10767     // we can still delay parsing it.
10768     if (D.getNumTypeObjects()) {
10769       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
10770       if (Outer.Kind == DeclaratorChunk::Function &&
10771           Outer.Fun.hasTrailingReturnType()) {
10772         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
10773         return Ty.isNull() || !Ty->isUndeducedType();
10774       }
10775     }
10776     return false;
10777   }
10778 
10779   return true;
10780 }
10781 
10782 bool Sema::canSkipFunctionBody(Decl *D) {
10783   // We cannot skip the body of a function (or function template) which is
10784   // constexpr, since we may need to evaluate its body in order to parse the
10785   // rest of the file.
10786   // We cannot skip the body of a function with an undeduced return type,
10787   // because any callers of that function need to know the type.
10788   if (const FunctionDecl *FD = D->getAsFunction())
10789     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
10790       return false;
10791   return Consumer.shouldSkipFunctionBody(D);
10792 }
10793 
10794 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
10795   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
10796     FD->setHasSkippedBody();
10797   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
10798     MD->setHasSkippedBody();
10799   return ActOnFinishFunctionBody(Decl, nullptr);
10800 }
10801 
10802 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
10803   return ActOnFinishFunctionBody(D, BodyArg, false);
10804 }
10805 
10806 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
10807                                     bool IsInstantiation) {
10808   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
10809 
10810   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10811   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
10812 
10813   if (FD) {
10814     FD->setBody(Body);
10815 
10816     if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
10817         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
10818       // If the function has a deduced result type but contains no 'return'
10819       // statements, the result type as written must be exactly 'auto', and
10820       // the deduced result type is 'void'.
10821       if (!FD->getReturnType()->getAs<AutoType>()) {
10822         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
10823             << FD->getReturnType();
10824         FD->setInvalidDecl();
10825       } else {
10826         // Substitute 'void' for the 'auto' in the type.
10827         TypeLoc ResultType = getReturnTypeLoc(FD);
10828         Context.adjustDeducedFunctionResultType(
10829             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
10830       }
10831     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
10832       auto *LSI = getCurLambda();
10833       if (LSI->HasImplicitReturnType) {
10834         deduceClosureReturnType(*LSI);
10835 
10836         // C++11 [expr.prim.lambda]p4:
10837         //   [...] if there are no return statements in the compound-statement
10838         //   [the deduced type is] the type void
10839         QualType RetType =
10840             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
10841 
10842         // Update the return type to the deduced type.
10843         const FunctionProtoType *Proto =
10844             FD->getType()->getAs<FunctionProtoType>();
10845         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
10846                                             Proto->getExtProtoInfo()));
10847       }
10848     }
10849 
10850     // The only way to be included in UndefinedButUsed is if there is an
10851     // ODR use before the definition. Avoid the expensive map lookup if this
10852     // is the first declaration.
10853     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
10854       if (!FD->isExternallyVisible())
10855         UndefinedButUsed.erase(FD);
10856       else if (FD->isInlined() &&
10857                !LangOpts.GNUInline &&
10858                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
10859         UndefinedButUsed.erase(FD);
10860     }
10861 
10862     // If the function implicitly returns zero (like 'main') or is naked,
10863     // don't complain about missing return statements.
10864     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
10865       WP.disableCheckFallThrough();
10866 
10867     // MSVC permits the use of pure specifier (=0) on function definition,
10868     // defined at class scope, warn about this non-standard construct.
10869     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
10870       Diag(FD->getLocation(), diag::ext_pure_function_definition);
10871 
10872     if (!FD->isInvalidDecl()) {
10873       // Don't diagnose unused parameters of defaulted or deleted functions.
10874       if (!FD->isDeleted() && !FD->isDefaulted())
10875         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
10876       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
10877                                              FD->getReturnType(), FD);
10878 
10879       // If this is a structor, we need a vtable.
10880       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
10881         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
10882       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
10883         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
10884 
10885       // Try to apply the named return value optimization. We have to check
10886       // if we can do this here because lambdas keep return statements around
10887       // to deduce an implicit return type.
10888       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
10889           !FD->isDependentContext())
10890         computeNRVO(Body, getCurFunction());
10891     }
10892 
10893     // GNU warning -Wmissing-prototypes:
10894     //   Warn if a global function is defined without a previous
10895     //   prototype declaration. This warning is issued even if the
10896     //   definition itself provides a prototype. The aim is to detect
10897     //   global functions that fail to be declared in header files.
10898     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
10899     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
10900       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
10901 
10902       if (PossibleZeroParamPrototype) {
10903         // We found a declaration that is not a prototype,
10904         // but that could be a zero-parameter prototype
10905         if (TypeSourceInfo *TI =
10906                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
10907           TypeLoc TL = TI->getTypeLoc();
10908           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
10909             Diag(PossibleZeroParamPrototype->getLocation(),
10910                  diag::note_declaration_not_a_prototype)
10911                 << PossibleZeroParamPrototype
10912                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
10913         }
10914       }
10915     }
10916 
10917     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
10918       const CXXMethodDecl *KeyFunction;
10919       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
10920           MD->isVirtual() &&
10921           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
10922           MD == KeyFunction->getCanonicalDecl()) {
10923         // Update the key-function state if necessary for this ABI.
10924         if (FD->isInlined() &&
10925             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
10926           Context.setNonKeyFunction(MD);
10927 
10928           // If the newly-chosen key function is already defined, then we
10929           // need to mark the vtable as used retroactively.
10930           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
10931           const FunctionDecl *Definition;
10932           if (KeyFunction && KeyFunction->isDefined(Definition))
10933             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
10934         } else {
10935           // We just defined they key function; mark the vtable as used.
10936           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
10937         }
10938       }
10939     }
10940 
10941     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
10942            "Function parsing confused");
10943   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
10944     assert(MD == getCurMethodDecl() && "Method parsing confused");
10945     MD->setBody(Body);
10946     if (!MD->isInvalidDecl()) {
10947       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
10948       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
10949                                              MD->getReturnType(), MD);
10950 
10951       if (Body)
10952         computeNRVO(Body, getCurFunction());
10953     }
10954     if (getCurFunction()->ObjCShouldCallSuper) {
10955       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
10956         << MD->getSelector().getAsString();
10957       getCurFunction()->ObjCShouldCallSuper = false;
10958     }
10959     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
10960       const ObjCMethodDecl *InitMethod = nullptr;
10961       bool isDesignated =
10962           MD->isDesignatedInitializerForTheInterface(&InitMethod);
10963       assert(isDesignated && InitMethod);
10964       (void)isDesignated;
10965 
10966       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
10967         auto IFace = MD->getClassInterface();
10968         if (!IFace)
10969           return false;
10970         auto SuperD = IFace->getSuperClass();
10971         if (!SuperD)
10972           return false;
10973         return SuperD->getIdentifier() ==
10974             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
10975       };
10976       // Don't issue this warning for unavailable inits or direct subclasses
10977       // of NSObject.
10978       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
10979         Diag(MD->getLocation(),
10980              diag::warn_objc_designated_init_missing_super_call);
10981         Diag(InitMethod->getLocation(),
10982              diag::note_objc_designated_init_marked_here);
10983       }
10984       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
10985     }
10986     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
10987       // Don't issue this warning for unavaialable inits.
10988       if (!MD->isUnavailable())
10989         Diag(MD->getLocation(),
10990              diag::warn_objc_secondary_init_missing_init_call);
10991       getCurFunction()->ObjCWarnForNoInitDelegation = false;
10992     }
10993   } else {
10994     return nullptr;
10995   }
10996 
10997   assert(!getCurFunction()->ObjCShouldCallSuper &&
10998          "This should only be set for ObjC methods, which should have been "
10999          "handled in the block above.");
11000 
11001   // Verify and clean out per-function state.
11002   if (Body && (!FD || !FD->isDefaulted())) {
11003     // C++ constructors that have function-try-blocks can't have return
11004     // statements in the handlers of that block. (C++ [except.handle]p14)
11005     // Verify this.
11006     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11007       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11008 
11009     // Verify that gotos and switch cases don't jump into scopes illegally.
11010     if (getCurFunction()->NeedsScopeChecking() &&
11011         !PP.isCodeCompletionEnabled())
11012       DiagnoseInvalidJumps(Body);
11013 
11014     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11015       if (!Destructor->getParent()->isDependentType())
11016         CheckDestructor(Destructor);
11017 
11018       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11019                                              Destructor->getParent());
11020     }
11021 
11022     // If any errors have occurred, clear out any temporaries that may have
11023     // been leftover. This ensures that these temporaries won't be picked up for
11024     // deletion in some later function.
11025     if (getDiagnostics().hasErrorOccurred() ||
11026         getDiagnostics().getSuppressAllDiagnostics()) {
11027       DiscardCleanupsInEvaluationContext();
11028     }
11029     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11030         !isa<FunctionTemplateDecl>(dcl)) {
11031       // Since the body is valid, issue any analysis-based warnings that are
11032       // enabled.
11033       ActivePolicy = &WP;
11034     }
11035 
11036     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11037         (!CheckConstexprFunctionDecl(FD) ||
11038          !CheckConstexprFunctionBody(FD, Body)))
11039       FD->setInvalidDecl();
11040 
11041     if (FD && FD->hasAttr<NakedAttr>()) {
11042       for (const Stmt *S : Body->children()) {
11043         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11044           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11045           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11046           FD->setInvalidDecl();
11047           break;
11048         }
11049       }
11050     }
11051 
11052     assert(ExprCleanupObjects.size() ==
11053                ExprEvalContexts.back().NumCleanupObjects &&
11054            "Leftover temporaries in function");
11055     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
11056     assert(MaybeODRUseExprs.empty() &&
11057            "Leftover expressions for odr-use checking");
11058   }
11059 
11060   if (!IsInstantiation)
11061     PopDeclContext();
11062 
11063   PopFunctionScopeInfo(ActivePolicy, dcl);
11064   // If any errors have occurred, clear out any temporaries that may have
11065   // been leftover. This ensures that these temporaries won't be picked up for
11066   // deletion in some later function.
11067   if (getDiagnostics().hasErrorOccurred()) {
11068     DiscardCleanupsInEvaluationContext();
11069   }
11070 
11071   return dcl;
11072 }
11073 
11074 
11075 /// When we finish delayed parsing of an attribute, we must attach it to the
11076 /// relevant Decl.
11077 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11078                                        ParsedAttributes &Attrs) {
11079   // Always attach attributes to the underlying decl.
11080   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11081     D = TD->getTemplatedDecl();
11082   ProcessDeclAttributeList(S, D, Attrs.getList());
11083 
11084   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11085     if (Method->isStatic())
11086       checkThisInStaticMemberFunctionAttributes(Method);
11087 }
11088 
11089 
11090 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11091 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11092 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11093                                           IdentifierInfo &II, Scope *S) {
11094   // Before we produce a declaration for an implicitly defined
11095   // function, see whether there was a locally-scoped declaration of
11096   // this name as a function or variable. If so, use that
11097   // (non-visible) declaration, and complain about it.
11098   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11099     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11100     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11101     return ExternCPrev;
11102   }
11103 
11104   // Extension in C99.  Legal in C90, but warn about it.
11105   unsigned diag_id;
11106   if (II.getName().startswith("__builtin_"))
11107     diag_id = diag::warn_builtin_unknown;
11108   else if (getLangOpts().C99)
11109     diag_id = diag::ext_implicit_function_decl;
11110   else
11111     diag_id = diag::warn_implicit_function_decl;
11112   Diag(Loc, diag_id) << &II;
11113 
11114   // Because typo correction is expensive, only do it if the implicit
11115   // function declaration is going to be treated as an error.
11116   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11117     TypoCorrection Corrected;
11118     if (S &&
11119         (Corrected = CorrectTypo(
11120              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11121              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11122       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11123                    /*ErrorRecovery*/false);
11124   }
11125 
11126   // Set a Declarator for the implicit definition: int foo();
11127   const char *Dummy;
11128   AttributeFactory attrFactory;
11129   DeclSpec DS(attrFactory);
11130   unsigned DiagID;
11131   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11132                                   Context.getPrintingPolicy());
11133   (void)Error; // Silence warning.
11134   assert(!Error && "Error setting up implicit decl!");
11135   SourceLocation NoLoc;
11136   Declarator D(DS, Declarator::BlockContext);
11137   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11138                                              /*IsAmbiguous=*/false,
11139                                              /*LParenLoc=*/NoLoc,
11140                                              /*Params=*/nullptr,
11141                                              /*NumParams=*/0,
11142                                              /*EllipsisLoc=*/NoLoc,
11143                                              /*RParenLoc=*/NoLoc,
11144                                              /*TypeQuals=*/0,
11145                                              /*RefQualifierIsLvalueRef=*/true,
11146                                              /*RefQualifierLoc=*/NoLoc,
11147                                              /*ConstQualifierLoc=*/NoLoc,
11148                                              /*VolatileQualifierLoc=*/NoLoc,
11149                                              /*RestrictQualifierLoc=*/NoLoc,
11150                                              /*MutableLoc=*/NoLoc,
11151                                              EST_None,
11152                                              /*ESpecRange=*/SourceRange(),
11153                                              /*Exceptions=*/nullptr,
11154                                              /*ExceptionRanges=*/nullptr,
11155                                              /*NumExceptions=*/0,
11156                                              /*NoexceptExpr=*/nullptr,
11157                                              /*ExceptionSpecTokens=*/nullptr,
11158                                              Loc, Loc, D),
11159                 DS.getAttributes(),
11160                 SourceLocation());
11161   D.SetIdentifier(&II, Loc);
11162 
11163   // Insert this function into translation-unit scope.
11164 
11165   DeclContext *PrevDC = CurContext;
11166   CurContext = Context.getTranslationUnitDecl();
11167 
11168   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11169   FD->setImplicit();
11170 
11171   CurContext = PrevDC;
11172 
11173   AddKnownFunctionAttributes(FD);
11174 
11175   return FD;
11176 }
11177 
11178 /// \brief Adds any function attributes that we know a priori based on
11179 /// the declaration of this function.
11180 ///
11181 /// These attributes can apply both to implicitly-declared builtins
11182 /// (like __builtin___printf_chk) or to library-declared functions
11183 /// like NSLog or printf.
11184 ///
11185 /// We need to check for duplicate attributes both here and where user-written
11186 /// attributes are applied to declarations.
11187 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11188   if (FD->isInvalidDecl())
11189     return;
11190 
11191   // If this is a built-in function, map its builtin attributes to
11192   // actual attributes.
11193   if (unsigned BuiltinID = FD->getBuiltinID()) {
11194     // Handle printf-formatting attributes.
11195     unsigned FormatIdx;
11196     bool HasVAListArg;
11197     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11198       if (!FD->hasAttr<FormatAttr>()) {
11199         const char *fmt = "printf";
11200         unsigned int NumParams = FD->getNumParams();
11201         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11202             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11203           fmt = "NSString";
11204         FD->addAttr(FormatAttr::CreateImplicit(Context,
11205                                                &Context.Idents.get(fmt),
11206                                                FormatIdx+1,
11207                                                HasVAListArg ? 0 : FormatIdx+2,
11208                                                FD->getLocation()));
11209       }
11210     }
11211     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11212                                              HasVAListArg)) {
11213      if (!FD->hasAttr<FormatAttr>())
11214        FD->addAttr(FormatAttr::CreateImplicit(Context,
11215                                               &Context.Idents.get("scanf"),
11216                                               FormatIdx+1,
11217                                               HasVAListArg ? 0 : FormatIdx+2,
11218                                               FD->getLocation()));
11219     }
11220 
11221     // Mark const if we don't care about errno and that is the only
11222     // thing preventing the function from being const. This allows
11223     // IRgen to use LLVM intrinsics for such functions.
11224     if (!getLangOpts().MathErrno &&
11225         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11226       if (!FD->hasAttr<ConstAttr>())
11227         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11228     }
11229 
11230     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11231         !FD->hasAttr<ReturnsTwiceAttr>())
11232       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11233                                          FD->getLocation()));
11234     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11235       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11236     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11237       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11238   }
11239 
11240   IdentifierInfo *Name = FD->getIdentifier();
11241   if (!Name)
11242     return;
11243   if ((!getLangOpts().CPlusPlus &&
11244        FD->getDeclContext()->isTranslationUnit()) ||
11245       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11246        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11247        LinkageSpecDecl::lang_c)) {
11248     // Okay: this could be a libc/libm/Objective-C function we know
11249     // about.
11250   } else
11251     return;
11252 
11253   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11254     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11255     // target-specific builtins, perhaps?
11256     if (!FD->hasAttr<FormatAttr>())
11257       FD->addAttr(FormatAttr::CreateImplicit(Context,
11258                                              &Context.Idents.get("printf"), 2,
11259                                              Name->isStr("vasprintf") ? 0 : 3,
11260                                              FD->getLocation()));
11261   }
11262 
11263   if (Name->isStr("__CFStringMakeConstantString")) {
11264     // We already have a __builtin___CFStringMakeConstantString,
11265     // but builds that use -fno-constant-cfstrings don't go through that.
11266     if (!FD->hasAttr<FormatArgAttr>())
11267       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11268                                                 FD->getLocation()));
11269   }
11270 }
11271 
11272 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11273                                     TypeSourceInfo *TInfo) {
11274   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11275   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11276 
11277   if (!TInfo) {
11278     assert(D.isInvalidType() && "no declarator info for valid type");
11279     TInfo = Context.getTrivialTypeSourceInfo(T);
11280   }
11281 
11282   // Scope manipulation handled by caller.
11283   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11284                                            D.getLocStart(),
11285                                            D.getIdentifierLoc(),
11286                                            D.getIdentifier(),
11287                                            TInfo);
11288 
11289   // Bail out immediately if we have an invalid declaration.
11290   if (D.isInvalidType()) {
11291     NewTD->setInvalidDecl();
11292     return NewTD;
11293   }
11294 
11295   if (D.getDeclSpec().isModulePrivateSpecified()) {
11296     if (CurContext->isFunctionOrMethod())
11297       Diag(NewTD->getLocation(), diag::err_module_private_local)
11298         << 2 << NewTD->getDeclName()
11299         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11300         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11301     else
11302       NewTD->setModulePrivate();
11303   }
11304 
11305   // C++ [dcl.typedef]p8:
11306   //   If the typedef declaration defines an unnamed class (or
11307   //   enum), the first typedef-name declared by the declaration
11308   //   to be that class type (or enum type) is used to denote the
11309   //   class type (or enum type) for linkage purposes only.
11310   // We need to check whether the type was declared in the declaration.
11311   switch (D.getDeclSpec().getTypeSpecType()) {
11312   case TST_enum:
11313   case TST_struct:
11314   case TST_interface:
11315   case TST_union:
11316   case TST_class: {
11317     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11318     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11319     break;
11320   }
11321 
11322   default:
11323     break;
11324   }
11325 
11326   return NewTD;
11327 }
11328 
11329 
11330 /// \brief Check that this is a valid underlying type for an enum declaration.
11331 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11332   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11333   QualType T = TI->getType();
11334 
11335   if (T->isDependentType())
11336     return false;
11337 
11338   if (const BuiltinType *BT = T->getAs<BuiltinType>())
11339     if (BT->isInteger())
11340       return false;
11341 
11342   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11343   return true;
11344 }
11345 
11346 /// Check whether this is a valid redeclaration of a previous enumeration.
11347 /// \return true if the redeclaration was invalid.
11348 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
11349                                   QualType EnumUnderlyingTy,
11350                                   const EnumDecl *Prev) {
11351   bool IsFixed = !EnumUnderlyingTy.isNull();
11352 
11353   if (IsScoped != Prev->isScoped()) {
11354     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11355       << Prev->isScoped();
11356     Diag(Prev->getLocation(), diag::note_previous_declaration);
11357     return true;
11358   }
11359 
11360   if (IsFixed && Prev->isFixed()) {
11361     if (!EnumUnderlyingTy->isDependentType() &&
11362         !Prev->getIntegerType()->isDependentType() &&
11363         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11364                                         Prev->getIntegerType())) {
11365       // TODO: Highlight the underlying type of the redeclaration.
11366       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11367         << EnumUnderlyingTy << Prev->getIntegerType();
11368       Diag(Prev->getLocation(), diag::note_previous_declaration)
11369           << Prev->getIntegerTypeRange();
11370       return true;
11371     }
11372   } else if (IsFixed != Prev->isFixed()) {
11373     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11374       << Prev->isFixed();
11375     Diag(Prev->getLocation(), diag::note_previous_declaration);
11376     return true;
11377   }
11378 
11379   return false;
11380 }
11381 
11382 /// \brief Get diagnostic %select index for tag kind for
11383 /// redeclaration diagnostic message.
11384 /// WARNING: Indexes apply to particular diagnostics only!
11385 ///
11386 /// \returns diagnostic %select index.
11387 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
11388   switch (Tag) {
11389   case TTK_Struct: return 0;
11390   case TTK_Interface: return 1;
11391   case TTK_Class:  return 2;
11392   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11393   }
11394 }
11395 
11396 /// \brief Determine if tag kind is a class-key compatible with
11397 /// class for redeclaration (class, struct, or __interface).
11398 ///
11399 /// \returns true iff the tag kind is compatible.
11400 static bool isClassCompatTagKind(TagTypeKind Tag)
11401 {
11402   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11403 }
11404 
11405 /// \brief Determine whether a tag with a given kind is acceptable
11406 /// as a redeclaration of the given tag declaration.
11407 ///
11408 /// \returns true if the new tag kind is acceptable, false otherwise.
11409 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11410                                         TagTypeKind NewTag, bool isDefinition,
11411                                         SourceLocation NewTagLoc,
11412                                         const IdentifierInfo *Name) {
11413   // C++ [dcl.type.elab]p3:
11414   //   The class-key or enum keyword present in the
11415   //   elaborated-type-specifier shall agree in kind with the
11416   //   declaration to which the name in the elaborated-type-specifier
11417   //   refers. This rule also applies to the form of
11418   //   elaborated-type-specifier that declares a class-name or
11419   //   friend class since it can be construed as referring to the
11420   //   definition of the class. Thus, in any
11421   //   elaborated-type-specifier, the enum keyword shall be used to
11422   //   refer to an enumeration (7.2), the union class-key shall be
11423   //   used to refer to a union (clause 9), and either the class or
11424   //   struct class-key shall be used to refer to a class (clause 9)
11425   //   declared using the class or struct class-key.
11426   TagTypeKind OldTag = Previous->getTagKind();
11427   if (!isDefinition || !isClassCompatTagKind(NewTag))
11428     if (OldTag == NewTag)
11429       return true;
11430 
11431   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11432     // Warn about the struct/class tag mismatch.
11433     bool isTemplate = false;
11434     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11435       isTemplate = Record->getDescribedClassTemplate();
11436 
11437     if (!ActiveTemplateInstantiations.empty()) {
11438       // In a template instantiation, do not offer fix-its for tag mismatches
11439       // since they usually mess up the template instead of fixing the problem.
11440       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11441         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11442         << getRedeclDiagFromTagKind(OldTag);
11443       return true;
11444     }
11445 
11446     if (isDefinition) {
11447       // On definitions, check previous tags and issue a fix-it for each
11448       // one that doesn't match the current tag.
11449       if (Previous->getDefinition()) {
11450         // Don't suggest fix-its for redefinitions.
11451         return true;
11452       }
11453 
11454       bool previousMismatch = false;
11455       for (auto I : Previous->redecls()) {
11456         if (I->getTagKind() != NewTag) {
11457           if (!previousMismatch) {
11458             previousMismatch = true;
11459             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11460               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11461               << getRedeclDiagFromTagKind(I->getTagKind());
11462           }
11463           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11464             << getRedeclDiagFromTagKind(NewTag)
11465             << FixItHint::CreateReplacement(I->getInnerLocStart(),
11466                  TypeWithKeyword::getTagTypeKindName(NewTag));
11467         }
11468       }
11469       return true;
11470     }
11471 
11472     // Check for a previous definition.  If current tag and definition
11473     // are same type, do nothing.  If no definition, but disagree with
11474     // with previous tag type, give a warning, but no fix-it.
11475     const TagDecl *Redecl = Previous->getDefinition() ?
11476                             Previous->getDefinition() : Previous;
11477     if (Redecl->getTagKind() == NewTag) {
11478       return true;
11479     }
11480 
11481     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11482       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11483       << getRedeclDiagFromTagKind(OldTag);
11484     Diag(Redecl->getLocation(), diag::note_previous_use);
11485 
11486     // If there is a previous definition, suggest a fix-it.
11487     if (Previous->getDefinition()) {
11488         Diag(NewTagLoc, diag::note_struct_class_suggestion)
11489           << getRedeclDiagFromTagKind(Redecl->getTagKind())
11490           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11491                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11492     }
11493 
11494     return true;
11495   }
11496   return false;
11497 }
11498 
11499 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11500 /// from an outer enclosing namespace or file scope inside a friend declaration.
11501 /// This should provide the commented out code in the following snippet:
11502 ///   namespace N {
11503 ///     struct X;
11504 ///     namespace M {
11505 ///       struct Y { friend struct /*N::*/ X; };
11506 ///     }
11507 ///   }
11508 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11509                                          SourceLocation NameLoc) {
11510   // While the decl is in a namespace, do repeated lookup of that name and see
11511   // if we get the same namespace back.  If we do not, continue until
11512   // translation unit scope, at which point we have a fully qualified NNS.
11513   SmallVector<IdentifierInfo *, 4> Namespaces;
11514   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11515   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11516     // This tag should be declared in a namespace, which can only be enclosed by
11517     // other namespaces.  Bail if there's an anonymous namespace in the chain.
11518     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11519     if (!Namespace || Namespace->isAnonymousNamespace())
11520       return FixItHint();
11521     IdentifierInfo *II = Namespace->getIdentifier();
11522     Namespaces.push_back(II);
11523     NamedDecl *Lookup = SemaRef.LookupSingleName(
11524         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11525     if (Lookup == Namespace)
11526       break;
11527   }
11528 
11529   // Once we have all the namespaces, reverse them to go outermost first, and
11530   // build an NNS.
11531   SmallString<64> Insertion;
11532   llvm::raw_svector_ostream OS(Insertion);
11533   if (DC->isTranslationUnit())
11534     OS << "::";
11535   std::reverse(Namespaces.begin(), Namespaces.end());
11536   for (auto *II : Namespaces)
11537     OS << II->getName() << "::";
11538   return FixItHint::CreateInsertion(NameLoc, Insertion);
11539 }
11540 
11541 /// \brief Determine whether a tag originally declared in context \p OldDC can
11542 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
11543 /// found a declaration in \p OldDC as a previous decl, perhaps through a
11544 /// using-declaration).
11545 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
11546                                          DeclContext *NewDC) {
11547   OldDC = OldDC->getRedeclContext();
11548   NewDC = NewDC->getRedeclContext();
11549 
11550   if (OldDC->Equals(NewDC))
11551     return true;
11552 
11553   // In MSVC mode, we allow a redeclaration if the contexts are related (either
11554   // encloses the other).
11555   if (S.getLangOpts().MSVCCompat &&
11556       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
11557     return true;
11558 
11559   return false;
11560 }
11561 
11562 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
11563 /// former case, Name will be non-null.  In the later case, Name will be null.
11564 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
11565 /// reference/declaration/definition of a tag.
11566 ///
11567 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
11568 /// trailing-type-specifier) other than one in an alias-declaration.
11569 ///
11570 /// \param SkipBody If non-null, will be set to indicate if the caller should
11571 /// skip the definition of this tag and treat it as if it were a declaration.
11572 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11573                      SourceLocation KWLoc, CXXScopeSpec &SS,
11574                      IdentifierInfo *Name, SourceLocation NameLoc,
11575                      AttributeList *Attr, AccessSpecifier AS,
11576                      SourceLocation ModulePrivateLoc,
11577                      MultiTemplateParamsArg TemplateParameterLists,
11578                      bool &OwnedDecl, bool &IsDependent,
11579                      SourceLocation ScopedEnumKWLoc,
11580                      bool ScopedEnumUsesClassTag,
11581                      TypeResult UnderlyingType,
11582                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
11583   // If this is not a definition, it must have a name.
11584   IdentifierInfo *OrigName = Name;
11585   assert((Name != nullptr || TUK == TUK_Definition) &&
11586          "Nameless record must be a definition!");
11587   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
11588 
11589   OwnedDecl = false;
11590   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11591   bool ScopedEnum = ScopedEnumKWLoc.isValid();
11592 
11593   // FIXME: Check explicit specializations more carefully.
11594   bool isExplicitSpecialization = false;
11595   bool Invalid = false;
11596 
11597   // We only need to do this matching if we have template parameters
11598   // or a scope specifier, which also conveniently avoids this work
11599   // for non-C++ cases.
11600   if (TemplateParameterLists.size() > 0 ||
11601       (SS.isNotEmpty() && TUK != TUK_Reference)) {
11602     if (TemplateParameterList *TemplateParams =
11603             MatchTemplateParametersToScopeSpecifier(
11604                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
11605                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
11606       if (Kind == TTK_Enum) {
11607         Diag(KWLoc, diag::err_enum_template);
11608         return nullptr;
11609       }
11610 
11611       if (TemplateParams->size() > 0) {
11612         // This is a declaration or definition of a class template (which may
11613         // be a member of another template).
11614 
11615         if (Invalid)
11616           return nullptr;
11617 
11618         OwnedDecl = false;
11619         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
11620                                                SS, Name, NameLoc, Attr,
11621                                                TemplateParams, AS,
11622                                                ModulePrivateLoc,
11623                                                /*FriendLoc*/SourceLocation(),
11624                                                TemplateParameterLists.size()-1,
11625                                                TemplateParameterLists.data(),
11626                                                SkipBody);
11627         return Result.get();
11628       } else {
11629         // The "template<>" header is extraneous.
11630         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11631           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11632         isExplicitSpecialization = true;
11633       }
11634     }
11635   }
11636 
11637   // Figure out the underlying type if this a enum declaration. We need to do
11638   // this early, because it's needed to detect if this is an incompatible
11639   // redeclaration.
11640   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11641 
11642   if (Kind == TTK_Enum) {
11643     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11644       // No underlying type explicitly specified, or we failed to parse the
11645       // type, default to int.
11646       EnumUnderlying = Context.IntTy.getTypePtr();
11647     else if (UnderlyingType.get()) {
11648       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11649       // integral type; any cv-qualification is ignored.
11650       TypeSourceInfo *TI = nullptr;
11651       GetTypeFromParser(UnderlyingType.get(), &TI);
11652       EnumUnderlying = TI;
11653 
11654       if (CheckEnumUnderlyingType(TI))
11655         // Recover by falling back to int.
11656         EnumUnderlying = Context.IntTy.getTypePtr();
11657 
11658       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
11659                                           UPPC_FixedUnderlyingType))
11660         EnumUnderlying = Context.IntTy.getTypePtr();
11661 
11662     } else if (getLangOpts().MSVCCompat)
11663       // Microsoft enums are always of int type.
11664       EnumUnderlying = Context.IntTy.getTypePtr();
11665   }
11666 
11667   DeclContext *SearchDC = CurContext;
11668   DeclContext *DC = CurContext;
11669   bool isStdBadAlloc = false;
11670 
11671   RedeclarationKind Redecl = ForRedeclaration;
11672   if (TUK == TUK_Friend || TUK == TUK_Reference)
11673     Redecl = NotForRedeclaration;
11674 
11675   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
11676   if (Name && SS.isNotEmpty()) {
11677     // We have a nested-name tag ('struct foo::bar').
11678 
11679     // Check for invalid 'foo::'.
11680     if (SS.isInvalid()) {
11681       Name = nullptr;
11682       goto CreateNewDecl;
11683     }
11684 
11685     // If this is a friend or a reference to a class in a dependent
11686     // context, don't try to make a decl for it.
11687     if (TUK == TUK_Friend || TUK == TUK_Reference) {
11688       DC = computeDeclContext(SS, false);
11689       if (!DC) {
11690         IsDependent = true;
11691         return nullptr;
11692       }
11693     } else {
11694       DC = computeDeclContext(SS, true);
11695       if (!DC) {
11696         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11697           << SS.getRange();
11698         return nullptr;
11699       }
11700     }
11701 
11702     if (RequireCompleteDeclContext(SS, DC))
11703       return nullptr;
11704 
11705     SearchDC = DC;
11706     // Look-up name inside 'foo::'.
11707     LookupQualifiedName(Previous, DC);
11708 
11709     if (Previous.isAmbiguous())
11710       return nullptr;
11711 
11712     if (Previous.empty()) {
11713       // Name lookup did not find anything. However, if the
11714       // nested-name-specifier refers to the current instantiation,
11715       // and that current instantiation has any dependent base
11716       // classes, we might find something at instantiation time: treat
11717       // this as a dependent elaborated-type-specifier.
11718       // But this only makes any sense for reference-like lookups.
11719       if (Previous.wasNotFoundInCurrentInstantiation() &&
11720           (TUK == TUK_Reference || TUK == TUK_Friend)) {
11721         IsDependent = true;
11722         return nullptr;
11723       }
11724 
11725       // A tag 'foo::bar' must already exist.
11726       Diag(NameLoc, diag::err_not_tag_in_scope)
11727         << Kind << Name << DC << SS.getRange();
11728       Name = nullptr;
11729       Invalid = true;
11730       goto CreateNewDecl;
11731     }
11732   } else if (Name) {
11733     // C++14 [class.mem]p14:
11734     //   If T is the name of a class, then each of the following shall have a
11735     //   name different from T:
11736     //    -- every member of class T that is itself a type
11737     if (TUK != TUK_Reference && TUK != TUK_Friend &&
11738         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
11739       return nullptr;
11740 
11741     // If this is a named struct, check to see if there was a previous forward
11742     // declaration or definition.
11743     // FIXME: We're looking into outer scopes here, even when we
11744     // shouldn't be. Doing so can result in ambiguities that we
11745     // shouldn't be diagnosing.
11746     LookupName(Previous, S);
11747 
11748     // When declaring or defining a tag, ignore ambiguities introduced
11749     // by types using'ed into this scope.
11750     if (Previous.isAmbiguous() &&
11751         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
11752       LookupResult::Filter F = Previous.makeFilter();
11753       while (F.hasNext()) {
11754         NamedDecl *ND = F.next();
11755         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
11756           F.erase();
11757       }
11758       F.done();
11759     }
11760 
11761     // C++11 [namespace.memdef]p3:
11762     //   If the name in a friend declaration is neither qualified nor
11763     //   a template-id and the declaration is a function or an
11764     //   elaborated-type-specifier, the lookup to determine whether
11765     //   the entity has been previously declared shall not consider
11766     //   any scopes outside the innermost enclosing namespace.
11767     //
11768     // MSVC doesn't implement the above rule for types, so a friend tag
11769     // declaration may be a redeclaration of a type declared in an enclosing
11770     // scope.  They do implement this rule for friend functions.
11771     //
11772     // Does it matter that this should be by scope instead of by
11773     // semantic context?
11774     if (!Previous.empty() && TUK == TUK_Friend) {
11775       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
11776       LookupResult::Filter F = Previous.makeFilter();
11777       bool FriendSawTagOutsideEnclosingNamespace = false;
11778       while (F.hasNext()) {
11779         NamedDecl *ND = F.next();
11780         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11781         if (DC->isFileContext() &&
11782             !EnclosingNS->Encloses(ND->getDeclContext())) {
11783           if (getLangOpts().MSVCCompat)
11784             FriendSawTagOutsideEnclosingNamespace = true;
11785           else
11786             F.erase();
11787         }
11788       }
11789       F.done();
11790 
11791       // Diagnose this MSVC extension in the easy case where lookup would have
11792       // unambiguously found something outside the enclosing namespace.
11793       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
11794         NamedDecl *ND = Previous.getFoundDecl();
11795         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
11796             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
11797       }
11798     }
11799 
11800     // Note:  there used to be some attempt at recovery here.
11801     if (Previous.isAmbiguous())
11802       return nullptr;
11803 
11804     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
11805       // FIXME: This makes sure that we ignore the contexts associated
11806       // with C structs, unions, and enums when looking for a matching
11807       // tag declaration or definition. See the similar lookup tweak
11808       // in Sema::LookupName; is there a better way to deal with this?
11809       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
11810         SearchDC = SearchDC->getParent();
11811     }
11812   }
11813 
11814   if (Previous.isSingleResult() &&
11815       Previous.getFoundDecl()->isTemplateParameter()) {
11816     // Maybe we will complain about the shadowed template parameter.
11817     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
11818     // Just pretend that we didn't see the previous declaration.
11819     Previous.clear();
11820   }
11821 
11822   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
11823       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
11824     // This is a declaration of or a reference to "std::bad_alloc".
11825     isStdBadAlloc = true;
11826 
11827     if (Previous.empty() && StdBadAlloc) {
11828       // std::bad_alloc has been implicitly declared (but made invisible to
11829       // name lookup). Fill in this implicit declaration as the previous
11830       // declaration, so that the declarations get chained appropriately.
11831       Previous.addDecl(getStdBadAlloc());
11832     }
11833   }
11834 
11835   // If we didn't find a previous declaration, and this is a reference
11836   // (or friend reference), move to the correct scope.  In C++, we
11837   // also need to do a redeclaration lookup there, just in case
11838   // there's a shadow friend decl.
11839   if (Name && Previous.empty() &&
11840       (TUK == TUK_Reference || TUK == TUK_Friend)) {
11841     if (Invalid) goto CreateNewDecl;
11842     assert(SS.isEmpty());
11843 
11844     if (TUK == TUK_Reference) {
11845       // C++ [basic.scope.pdecl]p5:
11846       //   -- for an elaborated-type-specifier of the form
11847       //
11848       //          class-key identifier
11849       //
11850       //      if the elaborated-type-specifier is used in the
11851       //      decl-specifier-seq or parameter-declaration-clause of a
11852       //      function defined in namespace scope, the identifier is
11853       //      declared as a class-name in the namespace that contains
11854       //      the declaration; otherwise, except as a friend
11855       //      declaration, the identifier is declared in the smallest
11856       //      non-class, non-function-prototype scope that contains the
11857       //      declaration.
11858       //
11859       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
11860       // C structs and unions.
11861       //
11862       // It is an error in C++ to declare (rather than define) an enum
11863       // type, including via an elaborated type specifier.  We'll
11864       // diagnose that later; for now, declare the enum in the same
11865       // scope as we would have picked for any other tag type.
11866       //
11867       // GNU C also supports this behavior as part of its incomplete
11868       // enum types extension, while GNU C++ does not.
11869       //
11870       // Find the context where we'll be declaring the tag.
11871       // FIXME: We would like to maintain the current DeclContext as the
11872       // lexical context,
11873       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
11874         SearchDC = SearchDC->getParent();
11875 
11876       // Find the scope where we'll be declaring the tag.
11877       while (S->isClassScope() ||
11878              (getLangOpts().CPlusPlus &&
11879               S->isFunctionPrototypeScope()) ||
11880              ((S->getFlags() & Scope::DeclScope) == 0) ||
11881              (S->getEntity() && S->getEntity()->isTransparentContext()))
11882         S = S->getParent();
11883     } else {
11884       assert(TUK == TUK_Friend);
11885       // C++ [namespace.memdef]p3:
11886       //   If a friend declaration in a non-local class first declares a
11887       //   class or function, the friend class or function is a member of
11888       //   the innermost enclosing namespace.
11889       SearchDC = SearchDC->getEnclosingNamespaceContext();
11890     }
11891 
11892     // In C++, we need to do a redeclaration lookup to properly
11893     // diagnose some problems.
11894     if (getLangOpts().CPlusPlus) {
11895       Previous.setRedeclarationKind(ForRedeclaration);
11896       LookupQualifiedName(Previous, SearchDC);
11897     }
11898   }
11899 
11900   // If we have a known previous declaration to use, then use it.
11901   if (Previous.empty() && SkipBody && SkipBody->Previous)
11902     Previous.addDecl(SkipBody->Previous);
11903 
11904   if (!Previous.empty()) {
11905     NamedDecl *PrevDecl = Previous.getFoundDecl();
11906     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
11907 
11908     // It's okay to have a tag decl in the same scope as a typedef
11909     // which hides a tag decl in the same scope.  Finding this
11910     // insanity with a redeclaration lookup can only actually happen
11911     // in C++.
11912     //
11913     // This is also okay for elaborated-type-specifiers, which is
11914     // technically forbidden by the current standard but which is
11915     // okay according to the likely resolution of an open issue;
11916     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
11917     if (getLangOpts().CPlusPlus) {
11918       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11919         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
11920           TagDecl *Tag = TT->getDecl();
11921           if (Tag->getDeclName() == Name &&
11922               Tag->getDeclContext()->getRedeclContext()
11923                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
11924             PrevDecl = Tag;
11925             Previous.clear();
11926             Previous.addDecl(Tag);
11927             Previous.resolveKind();
11928           }
11929         }
11930       }
11931     }
11932 
11933     // If this is a redeclaration of a using shadow declaration, it must
11934     // declare a tag in the same context. In MSVC mode, we allow a
11935     // redefinition if either context is within the other.
11936     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
11937       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
11938       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
11939           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
11940           !(OldTag && isAcceptableTagRedeclContext(
11941                           *this, OldTag->getDeclContext(), SearchDC))) {
11942         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
11943         Diag(Shadow->getTargetDecl()->getLocation(),
11944              diag::note_using_decl_target);
11945         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
11946             << 0;
11947         // Recover by ignoring the old declaration.
11948         Previous.clear();
11949         goto CreateNewDecl;
11950       }
11951     }
11952 
11953     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
11954       // If this is a use of a previous tag, or if the tag is already declared
11955       // in the same scope (so that the definition/declaration completes or
11956       // rementions the tag), reuse the decl.
11957       if (TUK == TUK_Reference || TUK == TUK_Friend ||
11958           isDeclInScope(DirectPrevDecl, SearchDC, S,
11959                         SS.isNotEmpty() || isExplicitSpecialization)) {
11960         // Make sure that this wasn't declared as an enum and now used as a
11961         // struct or something similar.
11962         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
11963                                           TUK == TUK_Definition, KWLoc,
11964                                           Name)) {
11965           bool SafeToContinue
11966             = (PrevTagDecl->getTagKind() != TTK_Enum &&
11967                Kind != TTK_Enum);
11968           if (SafeToContinue)
11969             Diag(KWLoc, diag::err_use_with_wrong_tag)
11970               << Name
11971               << FixItHint::CreateReplacement(SourceRange(KWLoc),
11972                                               PrevTagDecl->getKindName());
11973           else
11974             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
11975           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
11976 
11977           if (SafeToContinue)
11978             Kind = PrevTagDecl->getTagKind();
11979           else {
11980             // Recover by making this an anonymous redefinition.
11981             Name = nullptr;
11982             Previous.clear();
11983             Invalid = true;
11984           }
11985         }
11986 
11987         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
11988           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
11989 
11990           // If this is an elaborated-type-specifier for a scoped enumeration,
11991           // the 'class' keyword is not necessary and not permitted.
11992           if (TUK == TUK_Reference || TUK == TUK_Friend) {
11993             if (ScopedEnum)
11994               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
11995                 << PrevEnum->isScoped()
11996                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
11997             return PrevTagDecl;
11998           }
11999 
12000           QualType EnumUnderlyingTy;
12001           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12002             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12003           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12004             EnumUnderlyingTy = QualType(T, 0);
12005 
12006           // All conflicts with previous declarations are recovered by
12007           // returning the previous declaration, unless this is a definition,
12008           // in which case we want the caller to bail out.
12009           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12010                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
12011             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12012         }
12013 
12014         // C++11 [class.mem]p1:
12015         //   A member shall not be declared twice in the member-specification,
12016         //   except that a nested class or member class template can be declared
12017         //   and then later defined.
12018         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12019             S->isDeclScope(PrevDecl)) {
12020           Diag(NameLoc, diag::ext_member_redeclared);
12021           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12022         }
12023 
12024         if (!Invalid) {
12025           // If this is a use, just return the declaration we found, unless
12026           // we have attributes.
12027 
12028           // FIXME: In the future, return a variant or some other clue
12029           // for the consumer of this Decl to know it doesn't own it.
12030           // For our current ASTs this shouldn't be a problem, but will
12031           // need to be changed with DeclGroups.
12032           if (!Attr &&
12033               ((TUK == TUK_Reference &&
12034                 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
12035                || TUK == TUK_Friend))
12036             return PrevTagDecl;
12037 
12038           // Diagnose attempts to redefine a tag.
12039           if (TUK == TUK_Definition) {
12040             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12041               // If we're defining a specialization and the previous definition
12042               // is from an implicit instantiation, don't emit an error
12043               // here; we'll catch this in the general case below.
12044               bool IsExplicitSpecializationAfterInstantiation = false;
12045               if (isExplicitSpecialization) {
12046                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12047                   IsExplicitSpecializationAfterInstantiation =
12048                     RD->getTemplateSpecializationKind() !=
12049                     TSK_ExplicitSpecialization;
12050                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12051                   IsExplicitSpecializationAfterInstantiation =
12052                     ED->getTemplateSpecializationKind() !=
12053                     TSK_ExplicitSpecialization;
12054               }
12055 
12056               NamedDecl *Hidden = nullptr;
12057               if (SkipBody && getLangOpts().CPlusPlus &&
12058                   !hasVisibleDefinition(Def, &Hidden)) {
12059                 // There is a definition of this tag, but it is not visible. We
12060                 // explicitly make use of C++'s one definition rule here, and
12061                 // assume that this definition is identical to the hidden one
12062                 // we already have. Make the existing definition visible and
12063                 // use it in place of this one.
12064                 SkipBody->ShouldSkip = true;
12065                 makeMergedDefinitionVisible(Hidden, KWLoc);
12066                 return Def;
12067               } else if (!IsExplicitSpecializationAfterInstantiation) {
12068                 // A redeclaration in function prototype scope in C isn't
12069                 // visible elsewhere, so merely issue a warning.
12070                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12071                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12072                 else
12073                   Diag(NameLoc, diag::err_redefinition) << Name;
12074                 Diag(Def->getLocation(), diag::note_previous_definition);
12075                 // If this is a redefinition, recover by making this
12076                 // struct be anonymous, which will make any later
12077                 // references get the previous definition.
12078                 Name = nullptr;
12079                 Previous.clear();
12080                 Invalid = true;
12081               }
12082             } else {
12083               // If the type is currently being defined, complain
12084               // about a nested redefinition.
12085               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12086               if (TD->isBeingDefined()) {
12087                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12088                 Diag(PrevTagDecl->getLocation(),
12089                      diag::note_previous_definition);
12090                 Name = nullptr;
12091                 Previous.clear();
12092                 Invalid = true;
12093               }
12094             }
12095 
12096             // Okay, this is definition of a previously declared or referenced
12097             // tag. We're going to create a new Decl for it.
12098           }
12099 
12100           // Okay, we're going to make a redeclaration.  If this is some kind
12101           // of reference, make sure we build the redeclaration in the same DC
12102           // as the original, and ignore the current access specifier.
12103           if (TUK == TUK_Friend || TUK == TUK_Reference) {
12104             SearchDC = PrevTagDecl->getDeclContext();
12105             AS = AS_none;
12106           }
12107         }
12108         // If we get here we have (another) forward declaration or we
12109         // have a definition.  Just create a new decl.
12110 
12111       } else {
12112         // If we get here, this is a definition of a new tag type in a nested
12113         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12114         // new decl/type.  We set PrevDecl to NULL so that the entities
12115         // have distinct types.
12116         Previous.clear();
12117       }
12118       // If we get here, we're going to create a new Decl. If PrevDecl
12119       // is non-NULL, it's a definition of the tag declared by
12120       // PrevDecl. If it's NULL, we have a new definition.
12121 
12122 
12123     // Otherwise, PrevDecl is not a tag, but was found with tag
12124     // lookup.  This is only actually possible in C++, where a few
12125     // things like templates still live in the tag namespace.
12126     } else {
12127       // Use a better diagnostic if an elaborated-type-specifier
12128       // found the wrong kind of type on the first
12129       // (non-redeclaration) lookup.
12130       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12131           !Previous.isForRedeclaration()) {
12132         unsigned Kind = 0;
12133         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12134         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12135         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12136         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12137         Diag(PrevDecl->getLocation(), diag::note_declared_at);
12138         Invalid = true;
12139 
12140       // Otherwise, only diagnose if the declaration is in scope.
12141       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12142                                 SS.isNotEmpty() || isExplicitSpecialization)) {
12143         // do nothing
12144 
12145       // Diagnose implicit declarations introduced by elaborated types.
12146       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12147         unsigned Kind = 0;
12148         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12149         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12150         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12151         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12152         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12153         Invalid = true;
12154 
12155       // Otherwise it's a declaration.  Call out a particularly common
12156       // case here.
12157       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12158         unsigned Kind = 0;
12159         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12160         Diag(NameLoc, diag::err_tag_definition_of_typedef)
12161           << Name << Kind << TND->getUnderlyingType();
12162         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12163         Invalid = true;
12164 
12165       // Otherwise, diagnose.
12166       } else {
12167         // The tag name clashes with something else in the target scope,
12168         // issue an error and recover by making this tag be anonymous.
12169         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12170         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12171         Name = nullptr;
12172         Invalid = true;
12173       }
12174 
12175       // The existing declaration isn't relevant to us; we're in a
12176       // new scope, so clear out the previous declaration.
12177       Previous.clear();
12178     }
12179   }
12180 
12181 CreateNewDecl:
12182 
12183   TagDecl *PrevDecl = nullptr;
12184   if (Previous.isSingleResult())
12185     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12186 
12187   // If there is an identifier, use the location of the identifier as the
12188   // location of the decl, otherwise use the location of the struct/union
12189   // keyword.
12190   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12191 
12192   // Otherwise, create a new declaration. If there is a previous
12193   // declaration of the same entity, the two will be linked via
12194   // PrevDecl.
12195   TagDecl *New;
12196 
12197   bool IsForwardReference = false;
12198   if (Kind == TTK_Enum) {
12199     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12200     // enum X { A, B, C } D;    D should chain to X.
12201     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12202                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12203                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12204     // If this is an undefined enum, warn.
12205     if (TUK != TUK_Definition && !Invalid) {
12206       TagDecl *Def;
12207       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12208           cast<EnumDecl>(New)->isFixed()) {
12209         // C++0x: 7.2p2: opaque-enum-declaration.
12210         // Conflicts are diagnosed above. Do nothing.
12211       }
12212       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12213         Diag(Loc, diag::ext_forward_ref_enum_def)
12214           << New;
12215         Diag(Def->getLocation(), diag::note_previous_definition);
12216       } else {
12217         unsigned DiagID = diag::ext_forward_ref_enum;
12218         if (getLangOpts().MSVCCompat)
12219           DiagID = diag::ext_ms_forward_ref_enum;
12220         else if (getLangOpts().CPlusPlus)
12221           DiagID = diag::err_forward_ref_enum;
12222         Diag(Loc, DiagID);
12223 
12224         // If this is a forward-declared reference to an enumeration, make a
12225         // note of it; we won't actually be introducing the declaration into
12226         // the declaration context.
12227         if (TUK == TUK_Reference)
12228           IsForwardReference = true;
12229       }
12230     }
12231 
12232     if (EnumUnderlying) {
12233       EnumDecl *ED = cast<EnumDecl>(New);
12234       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12235         ED->setIntegerTypeSourceInfo(TI);
12236       else
12237         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12238       ED->setPromotionType(ED->getIntegerType());
12239     }
12240 
12241   } else {
12242     // struct/union/class
12243 
12244     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12245     // struct X { int A; } D;    D should chain to X.
12246     if (getLangOpts().CPlusPlus) {
12247       // FIXME: Look for a way to use RecordDecl for simple structs.
12248       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12249                                   cast_or_null<CXXRecordDecl>(PrevDecl));
12250 
12251       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12252         StdBadAlloc = cast<CXXRecordDecl>(New);
12253     } else
12254       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12255                                cast_or_null<RecordDecl>(PrevDecl));
12256   }
12257 
12258   // C++11 [dcl.type]p3:
12259   //   A type-specifier-seq shall not define a class or enumeration [...].
12260   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12261     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12262       << Context.getTagDeclType(New);
12263     Invalid = true;
12264   }
12265 
12266   // Maybe add qualifier info.
12267   if (SS.isNotEmpty()) {
12268     if (SS.isSet()) {
12269       // If this is either a declaration or a definition, check the
12270       // nested-name-specifier against the current context. We don't do this
12271       // for explicit specializations, because they have similar checking
12272       // (with more specific diagnostics) in the call to
12273       // CheckMemberSpecialization, below.
12274       if (!isExplicitSpecialization &&
12275           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12276           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12277         Invalid = true;
12278 
12279       New->setQualifierInfo(SS.getWithLocInContext(Context));
12280       if (TemplateParameterLists.size() > 0) {
12281         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12282       }
12283     }
12284     else
12285       Invalid = true;
12286   }
12287 
12288   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12289     // Add alignment attributes if necessary; these attributes are checked when
12290     // the ASTContext lays out the structure.
12291     //
12292     // It is important for implementing the correct semantics that this
12293     // happen here (in act on tag decl). The #pragma pack stack is
12294     // maintained as a result of parser callbacks which can occur at
12295     // many points during the parsing of a struct declaration (because
12296     // the #pragma tokens are effectively skipped over during the
12297     // parsing of the struct).
12298     if (TUK == TUK_Definition) {
12299       AddAlignmentAttributesForRecord(RD);
12300       AddMsStructLayoutForRecord(RD);
12301     }
12302   }
12303 
12304   if (ModulePrivateLoc.isValid()) {
12305     if (isExplicitSpecialization)
12306       Diag(New->getLocation(), diag::err_module_private_specialization)
12307         << 2
12308         << FixItHint::CreateRemoval(ModulePrivateLoc);
12309     // __module_private__ does not apply to local classes. However, we only
12310     // diagnose this as an error when the declaration specifiers are
12311     // freestanding. Here, we just ignore the __module_private__.
12312     else if (!SearchDC->isFunctionOrMethod())
12313       New->setModulePrivate();
12314   }
12315 
12316   // If this is a specialization of a member class (of a class template),
12317   // check the specialization.
12318   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12319     Invalid = true;
12320 
12321   // If we're declaring or defining a tag in function prototype scope in C,
12322   // note that this type can only be used within the function and add it to
12323   // the list of decls to inject into the function definition scope.
12324   if ((Name || Kind == TTK_Enum) &&
12325       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12326     if (getLangOpts().CPlusPlus) {
12327       // C++ [dcl.fct]p6:
12328       //   Types shall not be defined in return or parameter types.
12329       if (TUK == TUK_Definition && !IsTypeSpecifier) {
12330         Diag(Loc, diag::err_type_defined_in_param_type)
12331             << Name;
12332         Invalid = true;
12333       }
12334     } else {
12335       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
12336     }
12337     DeclsInPrototypeScope.push_back(New);
12338   }
12339 
12340   if (Invalid)
12341     New->setInvalidDecl();
12342 
12343   if (Attr)
12344     ProcessDeclAttributeList(S, New, Attr);
12345 
12346   // Set the lexical context. If the tag has a C++ scope specifier, the
12347   // lexical context will be different from the semantic context.
12348   New->setLexicalDeclContext(CurContext);
12349 
12350   // Mark this as a friend decl if applicable.
12351   // In Microsoft mode, a friend declaration also acts as a forward
12352   // declaration so we always pass true to setObjectOfFriendDecl to make
12353   // the tag name visible.
12354   if (TUK == TUK_Friend)
12355     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
12356 
12357   // Set the access specifier.
12358   if (!Invalid && SearchDC->isRecord())
12359     SetMemberAccessSpecifier(New, PrevDecl, AS);
12360 
12361   if (TUK == TUK_Definition)
12362     New->startDefinition();
12363 
12364   // If this has an identifier, add it to the scope stack.
12365   if (TUK == TUK_Friend) {
12366     // We might be replacing an existing declaration in the lookup tables;
12367     // if so, borrow its access specifier.
12368     if (PrevDecl)
12369       New->setAccess(PrevDecl->getAccess());
12370 
12371     DeclContext *DC = New->getDeclContext()->getRedeclContext();
12372     DC->makeDeclVisibleInContext(New);
12373     if (Name) // can be null along some error paths
12374       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12375         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
12376   } else if (Name) {
12377     S = getNonFieldDeclScope(S);
12378     PushOnScopeChains(New, S, !IsForwardReference);
12379     if (IsForwardReference)
12380       SearchDC->makeDeclVisibleInContext(New);
12381 
12382   } else {
12383     CurContext->addDecl(New);
12384   }
12385 
12386   // If this is the C FILE type, notify the AST context.
12387   if (IdentifierInfo *II = New->getIdentifier())
12388     if (!New->isInvalidDecl() &&
12389         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
12390         II->isStr("FILE"))
12391       Context.setFILEDecl(New);
12392 
12393   if (PrevDecl)
12394     mergeDeclAttributes(New, PrevDecl);
12395 
12396   // If there's a #pragma GCC visibility in scope, set the visibility of this
12397   // record.
12398   AddPushedVisibilityAttribute(New);
12399 
12400   OwnedDecl = true;
12401   // In C++, don't return an invalid declaration. We can't recover well from
12402   // the cases where we make the type anonymous.
12403   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
12404 }
12405 
12406 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
12407   AdjustDeclIfTemplate(TagD);
12408   TagDecl *Tag = cast<TagDecl>(TagD);
12409 
12410   // Enter the tag context.
12411   PushDeclContext(S, Tag);
12412 
12413   ActOnDocumentableDecl(TagD);
12414 
12415   // If there's a #pragma GCC visibility in scope, set the visibility of this
12416   // record.
12417   AddPushedVisibilityAttribute(Tag);
12418 }
12419 
12420 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
12421   assert(isa<ObjCContainerDecl>(IDecl) &&
12422          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
12423   DeclContext *OCD = cast<DeclContext>(IDecl);
12424   assert(getContainingDC(OCD) == CurContext &&
12425       "The next DeclContext should be lexically contained in the current one.");
12426   CurContext = OCD;
12427   return IDecl;
12428 }
12429 
12430 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
12431                                            SourceLocation FinalLoc,
12432                                            bool IsFinalSpelledSealed,
12433                                            SourceLocation LBraceLoc) {
12434   AdjustDeclIfTemplate(TagD);
12435   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
12436 
12437   FieldCollector->StartClass();
12438 
12439   if (!Record->getIdentifier())
12440     return;
12441 
12442   if (FinalLoc.isValid())
12443     Record->addAttr(new (Context)
12444                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
12445 
12446   // C++ [class]p2:
12447   //   [...] The class-name is also inserted into the scope of the
12448   //   class itself; this is known as the injected-class-name. For
12449   //   purposes of access checking, the injected-class-name is treated
12450   //   as if it were a public member name.
12451   CXXRecordDecl *InjectedClassName
12452     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
12453                             Record->getLocStart(), Record->getLocation(),
12454                             Record->getIdentifier(),
12455                             /*PrevDecl=*/nullptr,
12456                             /*DelayTypeCreation=*/true);
12457   Context.getTypeDeclType(InjectedClassName, Record);
12458   InjectedClassName->setImplicit();
12459   InjectedClassName->setAccess(AS_public);
12460   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
12461       InjectedClassName->setDescribedClassTemplate(Template);
12462   PushOnScopeChains(InjectedClassName, S);
12463   assert(InjectedClassName->isInjectedClassName() &&
12464          "Broken injected-class-name");
12465 }
12466 
12467 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
12468                                     SourceLocation RBraceLoc) {
12469   AdjustDeclIfTemplate(TagD);
12470   TagDecl *Tag = cast<TagDecl>(TagD);
12471   Tag->setRBraceLoc(RBraceLoc);
12472 
12473   // Make sure we "complete" the definition even it is invalid.
12474   if (Tag->isBeingDefined()) {
12475     assert(Tag->isInvalidDecl() && "We should already have completed it");
12476     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12477       RD->completeDefinition();
12478   }
12479 
12480   if (isa<CXXRecordDecl>(Tag))
12481     FieldCollector->FinishClass();
12482 
12483   // Exit this scope of this tag's definition.
12484   PopDeclContext();
12485 
12486   if (getCurLexicalContext()->isObjCContainer() &&
12487       Tag->getDeclContext()->isFileContext())
12488     Tag->setTopLevelDeclInObjCContainer();
12489 
12490   // Notify the consumer that we've defined a tag.
12491   if (!Tag->isInvalidDecl())
12492     Consumer.HandleTagDeclDefinition(Tag);
12493 }
12494 
12495 void Sema::ActOnObjCContainerFinishDefinition() {
12496   // Exit this scope of this interface definition.
12497   PopDeclContext();
12498 }
12499 
12500 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
12501   assert(DC == CurContext && "Mismatch of container contexts");
12502   OriginalLexicalContext = DC;
12503   ActOnObjCContainerFinishDefinition();
12504 }
12505 
12506 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
12507   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
12508   OriginalLexicalContext = nullptr;
12509 }
12510 
12511 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
12512   AdjustDeclIfTemplate(TagD);
12513   TagDecl *Tag = cast<TagDecl>(TagD);
12514   Tag->setInvalidDecl();
12515 
12516   // Make sure we "complete" the definition even it is invalid.
12517   if (Tag->isBeingDefined()) {
12518     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12519       RD->completeDefinition();
12520   }
12521 
12522   // We're undoing ActOnTagStartDefinition here, not
12523   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
12524   // the FieldCollector.
12525 
12526   PopDeclContext();
12527 }
12528 
12529 // Note that FieldName may be null for anonymous bitfields.
12530 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
12531                                 IdentifierInfo *FieldName,
12532                                 QualType FieldTy, bool IsMsStruct,
12533                                 Expr *BitWidth, bool *ZeroWidth) {
12534   // Default to true; that shouldn't confuse checks for emptiness
12535   if (ZeroWidth)
12536     *ZeroWidth = true;
12537 
12538   // C99 6.7.2.1p4 - verify the field type.
12539   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
12540   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
12541     // Handle incomplete types with specific error.
12542     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
12543       return ExprError();
12544     if (FieldName)
12545       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12546         << FieldName << FieldTy << BitWidth->getSourceRange();
12547     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12548       << FieldTy << BitWidth->getSourceRange();
12549   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12550                                              UPPC_BitFieldWidth))
12551     return ExprError();
12552 
12553   // If the bit-width is type- or value-dependent, don't try to check
12554   // it now.
12555   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
12556     return BitWidth;
12557 
12558   llvm::APSInt Value;
12559   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
12560   if (ICE.isInvalid())
12561     return ICE;
12562   BitWidth = ICE.get();
12563 
12564   if (Value != 0 && ZeroWidth)
12565     *ZeroWidth = false;
12566 
12567   // Zero-width bitfield is ok for anonymous field.
12568   if (Value == 0 && FieldName)
12569     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
12570 
12571   if (Value.isSigned() && Value.isNegative()) {
12572     if (FieldName)
12573       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
12574                << FieldName << Value.toString(10);
12575     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
12576       << Value.toString(10);
12577   }
12578 
12579   if (!FieldTy->isDependentType()) {
12580     uint64_t TypeSize = Context.getTypeSize(FieldTy);
12581     if (Value.getZExtValue() > TypeSize) {
12582       if (!getLangOpts().CPlusPlus || IsMsStruct ||
12583           Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12584         if (FieldName)
12585           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
12586             << FieldName << (unsigned)Value.getZExtValue()
12587             << (unsigned)TypeSize;
12588 
12589         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
12590           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12591       }
12592 
12593       if (FieldName)
12594         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
12595           << FieldName << (unsigned)Value.getZExtValue()
12596           << (unsigned)TypeSize;
12597       else
12598         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
12599           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12600     }
12601   }
12602 
12603   return BitWidth;
12604 }
12605 
12606 /// ActOnField - Each field of a C struct/union is passed into this in order
12607 /// to create a FieldDecl object for it.
12608 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
12609                        Declarator &D, Expr *BitfieldWidth) {
12610   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
12611                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
12612                                /*InitStyle=*/ICIS_NoInit, AS_public);
12613   return Res;
12614 }
12615 
12616 /// HandleField - Analyze a field of a C struct or a C++ data member.
12617 ///
12618 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
12619                              SourceLocation DeclStart,
12620                              Declarator &D, Expr *BitWidth,
12621                              InClassInitStyle InitStyle,
12622                              AccessSpecifier AS) {
12623   IdentifierInfo *II = D.getIdentifier();
12624   SourceLocation Loc = DeclStart;
12625   if (II) Loc = D.getIdentifierLoc();
12626 
12627   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12628   QualType T = TInfo->getType();
12629   if (getLangOpts().CPlusPlus) {
12630     CheckExtraCXXDefaultArguments(D);
12631 
12632     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12633                                         UPPC_DataMemberType)) {
12634       D.setInvalidType();
12635       T = Context.IntTy;
12636       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12637     }
12638   }
12639 
12640   // TR 18037 does not allow fields to be declared with address spaces.
12641   if (T.getQualifiers().hasAddressSpace()) {
12642     Diag(Loc, diag::err_field_with_address_space);
12643     D.setInvalidType();
12644   }
12645 
12646   // OpenCL 1.2 spec, s6.9 r:
12647   // The event type cannot be used to declare a structure or union field.
12648   if (LangOpts.OpenCL && T->isEventT()) {
12649     Diag(Loc, diag::err_event_t_struct_field);
12650     D.setInvalidType();
12651   }
12652 
12653   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12654 
12655   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12656     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12657          diag::err_invalid_thread)
12658       << DeclSpec::getSpecifierName(TSCS);
12659 
12660   // Check to see if this name was declared as a member previously
12661   NamedDecl *PrevDecl = nullptr;
12662   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12663   LookupName(Previous, S);
12664   switch (Previous.getResultKind()) {
12665     case LookupResult::Found:
12666     case LookupResult::FoundUnresolvedValue:
12667       PrevDecl = Previous.getAsSingle<NamedDecl>();
12668       break;
12669 
12670     case LookupResult::FoundOverloaded:
12671       PrevDecl = Previous.getRepresentativeDecl();
12672       break;
12673 
12674     case LookupResult::NotFound:
12675     case LookupResult::NotFoundInCurrentInstantiation:
12676     case LookupResult::Ambiguous:
12677       break;
12678   }
12679   Previous.suppressDiagnostics();
12680 
12681   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12682     // Maybe we will complain about the shadowed template parameter.
12683     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12684     // Just pretend that we didn't see the previous declaration.
12685     PrevDecl = nullptr;
12686   }
12687 
12688   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12689     PrevDecl = nullptr;
12690 
12691   bool Mutable
12692     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
12693   SourceLocation TSSL = D.getLocStart();
12694   FieldDecl *NewFD
12695     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
12696                      TSSL, AS, PrevDecl, &D);
12697 
12698   if (NewFD->isInvalidDecl())
12699     Record->setInvalidDecl();
12700 
12701   if (D.getDeclSpec().isModulePrivateSpecified())
12702     NewFD->setModulePrivate();
12703 
12704   if (NewFD->isInvalidDecl() && PrevDecl) {
12705     // Don't introduce NewFD into scope; there's already something
12706     // with the same name in the same scope.
12707   } else if (II) {
12708     PushOnScopeChains(NewFD, S);
12709   } else
12710     Record->addDecl(NewFD);
12711 
12712   return NewFD;
12713 }
12714 
12715 /// \brief Build a new FieldDecl and check its well-formedness.
12716 ///
12717 /// This routine builds a new FieldDecl given the fields name, type,
12718 /// record, etc. \p PrevDecl should refer to any previous declaration
12719 /// with the same name and in the same scope as the field to be
12720 /// created.
12721 ///
12722 /// \returns a new FieldDecl.
12723 ///
12724 /// \todo The Declarator argument is a hack. It will be removed once
12725 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
12726                                 TypeSourceInfo *TInfo,
12727                                 RecordDecl *Record, SourceLocation Loc,
12728                                 bool Mutable, Expr *BitWidth,
12729                                 InClassInitStyle InitStyle,
12730                                 SourceLocation TSSL,
12731                                 AccessSpecifier AS, NamedDecl *PrevDecl,
12732                                 Declarator *D) {
12733   IdentifierInfo *II = Name.getAsIdentifierInfo();
12734   bool InvalidDecl = false;
12735   if (D) InvalidDecl = D->isInvalidType();
12736 
12737   // If we receive a broken type, recover by assuming 'int' and
12738   // marking this declaration as invalid.
12739   if (T.isNull()) {
12740     InvalidDecl = true;
12741     T = Context.IntTy;
12742   }
12743 
12744   QualType EltTy = Context.getBaseElementType(T);
12745   if (!EltTy->isDependentType()) {
12746     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
12747       // Fields of incomplete type force their record to be invalid.
12748       Record->setInvalidDecl();
12749       InvalidDecl = true;
12750     } else {
12751       NamedDecl *Def;
12752       EltTy->isIncompleteType(&Def);
12753       if (Def && Def->isInvalidDecl()) {
12754         Record->setInvalidDecl();
12755         InvalidDecl = true;
12756       }
12757     }
12758   }
12759 
12760   // OpenCL v1.2 s6.9.c: bitfields are not supported.
12761   if (BitWidth && getLangOpts().OpenCL) {
12762     Diag(Loc, diag::err_opencl_bitfields);
12763     InvalidDecl = true;
12764   }
12765 
12766   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12767   // than a variably modified type.
12768   if (!InvalidDecl && T->isVariablyModifiedType()) {
12769     bool SizeIsNegative;
12770     llvm::APSInt Oversized;
12771 
12772     TypeSourceInfo *FixedTInfo =
12773       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
12774                                                     SizeIsNegative,
12775                                                     Oversized);
12776     if (FixedTInfo) {
12777       Diag(Loc, diag::warn_illegal_constant_array_size);
12778       TInfo = FixedTInfo;
12779       T = FixedTInfo->getType();
12780     } else {
12781       if (SizeIsNegative)
12782         Diag(Loc, diag::err_typecheck_negative_array_size);
12783       else if (Oversized.getBoolValue())
12784         Diag(Loc, diag::err_array_too_large)
12785           << Oversized.toString(10);
12786       else
12787         Diag(Loc, diag::err_typecheck_field_variable_size);
12788       InvalidDecl = true;
12789     }
12790   }
12791 
12792   // Fields can not have abstract class types
12793   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
12794                                              diag::err_abstract_type_in_decl,
12795                                              AbstractFieldType))
12796     InvalidDecl = true;
12797 
12798   bool ZeroWidth = false;
12799   if (InvalidDecl)
12800     BitWidth = nullptr;
12801   // If this is declared as a bit-field, check the bit-field.
12802   if (BitWidth) {
12803     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
12804                               &ZeroWidth).get();
12805     if (!BitWidth) {
12806       InvalidDecl = true;
12807       BitWidth = nullptr;
12808       ZeroWidth = false;
12809     }
12810   }
12811 
12812   // Check that 'mutable' is consistent with the type of the declaration.
12813   if (!InvalidDecl && Mutable) {
12814     unsigned DiagID = 0;
12815     if (T->isReferenceType())
12816       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
12817                                         : diag::err_mutable_reference;
12818     else if (T.isConstQualified())
12819       DiagID = diag::err_mutable_const;
12820 
12821     if (DiagID) {
12822       SourceLocation ErrLoc = Loc;
12823       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
12824         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
12825       Diag(ErrLoc, DiagID);
12826       if (DiagID != diag::ext_mutable_reference) {
12827         Mutable = false;
12828         InvalidDecl = true;
12829       }
12830     }
12831   }
12832 
12833   // C++11 [class.union]p8 (DR1460):
12834   //   At most one variant member of a union may have a
12835   //   brace-or-equal-initializer.
12836   if (InitStyle != ICIS_NoInit)
12837     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
12838 
12839   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
12840                                        BitWidth, Mutable, InitStyle);
12841   if (InvalidDecl)
12842     NewFD->setInvalidDecl();
12843 
12844   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
12845     Diag(Loc, diag::err_duplicate_member) << II;
12846     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12847     NewFD->setInvalidDecl();
12848   }
12849 
12850   if (!InvalidDecl && getLangOpts().CPlusPlus) {
12851     if (Record->isUnion()) {
12852       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12853         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
12854         if (RDecl->getDefinition()) {
12855           // C++ [class.union]p1: An object of a class with a non-trivial
12856           // constructor, a non-trivial copy constructor, a non-trivial
12857           // destructor, or a non-trivial copy assignment operator
12858           // cannot be a member of a union, nor can an array of such
12859           // objects.
12860           if (CheckNontrivialField(NewFD))
12861             NewFD->setInvalidDecl();
12862         }
12863       }
12864 
12865       // C++ [class.union]p1: If a union contains a member of reference type,
12866       // the program is ill-formed, except when compiling with MSVC extensions
12867       // enabled.
12868       if (EltTy->isReferenceType()) {
12869         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
12870                                     diag::ext_union_member_of_reference_type :
12871                                     diag::err_union_member_of_reference_type)
12872           << NewFD->getDeclName() << EltTy;
12873         if (!getLangOpts().MicrosoftExt)
12874           NewFD->setInvalidDecl();
12875       }
12876     }
12877   }
12878 
12879   // FIXME: We need to pass in the attributes given an AST
12880   // representation, not a parser representation.
12881   if (D) {
12882     // FIXME: The current scope is almost... but not entirely... correct here.
12883     ProcessDeclAttributes(getCurScope(), NewFD, *D);
12884 
12885     if (NewFD->hasAttrs())
12886       CheckAlignasUnderalignment(NewFD);
12887   }
12888 
12889   // In auto-retain/release, infer strong retension for fields of
12890   // retainable type.
12891   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
12892     NewFD->setInvalidDecl();
12893 
12894   if (T.isObjCGCWeak())
12895     Diag(Loc, diag::warn_attribute_weak_on_field);
12896 
12897   NewFD->setAccess(AS);
12898   return NewFD;
12899 }
12900 
12901 bool Sema::CheckNontrivialField(FieldDecl *FD) {
12902   assert(FD);
12903   assert(getLangOpts().CPlusPlus && "valid check only for C++");
12904 
12905   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
12906     return false;
12907 
12908   QualType EltTy = Context.getBaseElementType(FD->getType());
12909   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12910     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
12911     if (RDecl->getDefinition()) {
12912       // We check for copy constructors before constructors
12913       // because otherwise we'll never get complaints about
12914       // copy constructors.
12915 
12916       CXXSpecialMember member = CXXInvalid;
12917       // We're required to check for any non-trivial constructors. Since the
12918       // implicit default constructor is suppressed if there are any
12919       // user-declared constructors, we just need to check that there is a
12920       // trivial default constructor and a trivial copy constructor. (We don't
12921       // worry about move constructors here, since this is a C++98 check.)
12922       if (RDecl->hasNonTrivialCopyConstructor())
12923         member = CXXCopyConstructor;
12924       else if (!RDecl->hasTrivialDefaultConstructor())
12925         member = CXXDefaultConstructor;
12926       else if (RDecl->hasNonTrivialCopyAssignment())
12927         member = CXXCopyAssignment;
12928       else if (RDecl->hasNonTrivialDestructor())
12929         member = CXXDestructor;
12930 
12931       if (member != CXXInvalid) {
12932         if (!getLangOpts().CPlusPlus11 &&
12933             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
12934           // Objective-C++ ARC: it is an error to have a non-trivial field of
12935           // a union. However, system headers in Objective-C programs
12936           // occasionally have Objective-C lifetime objects within unions,
12937           // and rather than cause the program to fail, we make those
12938           // members unavailable.
12939           SourceLocation Loc = FD->getLocation();
12940           if (getSourceManager().isInSystemHeader(Loc)) {
12941             if (!FD->hasAttr<UnavailableAttr>())
12942               FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12943                                   "this system field has retaining ownership",
12944                                   Loc));
12945             return false;
12946           }
12947         }
12948 
12949         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
12950                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
12951                diag::err_illegal_union_or_anon_struct_member)
12952           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
12953         DiagnoseNontrivial(RDecl, member);
12954         return !getLangOpts().CPlusPlus11;
12955       }
12956     }
12957   }
12958 
12959   return false;
12960 }
12961 
12962 /// TranslateIvarVisibility - Translate visibility from a token ID to an
12963 ///  AST enum value.
12964 static ObjCIvarDecl::AccessControl
12965 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
12966   switch (ivarVisibility) {
12967   default: llvm_unreachable("Unknown visitibility kind");
12968   case tok::objc_private: return ObjCIvarDecl::Private;
12969   case tok::objc_public: return ObjCIvarDecl::Public;
12970   case tok::objc_protected: return ObjCIvarDecl::Protected;
12971   case tok::objc_package: return ObjCIvarDecl::Package;
12972   }
12973 }
12974 
12975 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
12976 /// in order to create an IvarDecl object for it.
12977 Decl *Sema::ActOnIvar(Scope *S,
12978                                 SourceLocation DeclStart,
12979                                 Declarator &D, Expr *BitfieldWidth,
12980                                 tok::ObjCKeywordKind Visibility) {
12981 
12982   IdentifierInfo *II = D.getIdentifier();
12983   Expr *BitWidth = (Expr*)BitfieldWidth;
12984   SourceLocation Loc = DeclStart;
12985   if (II) Loc = D.getIdentifierLoc();
12986 
12987   // FIXME: Unnamed fields can be handled in various different ways, for
12988   // example, unnamed unions inject all members into the struct namespace!
12989 
12990   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12991   QualType T = TInfo->getType();
12992 
12993   if (BitWidth) {
12994     // 6.7.2.1p3, 6.7.2.1p4
12995     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
12996     if (!BitWidth)
12997       D.setInvalidType();
12998   } else {
12999     // Not a bitfield.
13000 
13001     // validate II.
13002 
13003   }
13004   if (T->isReferenceType()) {
13005     Diag(Loc, diag::err_ivar_reference_type);
13006     D.setInvalidType();
13007   }
13008   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13009   // than a variably modified type.
13010   else if (T->isVariablyModifiedType()) {
13011     Diag(Loc, diag::err_typecheck_ivar_variable_size);
13012     D.setInvalidType();
13013   }
13014 
13015   // Get the visibility (access control) for this ivar.
13016   ObjCIvarDecl::AccessControl ac =
13017     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13018                                         : ObjCIvarDecl::None;
13019   // Must set ivar's DeclContext to its enclosing interface.
13020   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13021   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13022     return nullptr;
13023   ObjCContainerDecl *EnclosingContext;
13024   if (ObjCImplementationDecl *IMPDecl =
13025       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13026     if (LangOpts.ObjCRuntime.isFragile()) {
13027     // Case of ivar declared in an implementation. Context is that of its class.
13028       EnclosingContext = IMPDecl->getClassInterface();
13029       assert(EnclosingContext && "Implementation has no class interface!");
13030     }
13031     else
13032       EnclosingContext = EnclosingDecl;
13033   } else {
13034     if (ObjCCategoryDecl *CDecl =
13035         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13036       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13037         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13038         return nullptr;
13039       }
13040     }
13041     EnclosingContext = EnclosingDecl;
13042   }
13043 
13044   // Construct the decl.
13045   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13046                                              DeclStart, Loc, II, T,
13047                                              TInfo, ac, (Expr *)BitfieldWidth);
13048 
13049   if (II) {
13050     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13051                                            ForRedeclaration);
13052     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13053         && !isa<TagDecl>(PrevDecl)) {
13054       Diag(Loc, diag::err_duplicate_member) << II;
13055       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13056       NewID->setInvalidDecl();
13057     }
13058   }
13059 
13060   // Process attributes attached to the ivar.
13061   ProcessDeclAttributes(S, NewID, D);
13062 
13063   if (D.isInvalidType())
13064     NewID->setInvalidDecl();
13065 
13066   // In ARC, infer 'retaining' for ivars of retainable type.
13067   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13068     NewID->setInvalidDecl();
13069 
13070   if (D.getDeclSpec().isModulePrivateSpecified())
13071     NewID->setModulePrivate();
13072 
13073   if (II) {
13074     // FIXME: When interfaces are DeclContexts, we'll need to add
13075     // these to the interface.
13076     S->AddDecl(NewID);
13077     IdResolver.AddDecl(NewID);
13078   }
13079 
13080   if (LangOpts.ObjCRuntime.isNonFragile() &&
13081       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13082     Diag(Loc, diag::warn_ivars_in_interface);
13083 
13084   return NewID;
13085 }
13086 
13087 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13088 /// class and class extensions. For every class \@interface and class
13089 /// extension \@interface, if the last ivar is a bitfield of any type,
13090 /// then add an implicit `char :0` ivar to the end of that interface.
13091 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13092                              SmallVectorImpl<Decl *> &AllIvarDecls) {
13093   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13094     return;
13095 
13096   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13097   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13098 
13099   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13100     return;
13101   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13102   if (!ID) {
13103     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13104       if (!CD->IsClassExtension())
13105         return;
13106     }
13107     // No need to add this to end of @implementation.
13108     else
13109       return;
13110   }
13111   // All conditions are met. Add a new bitfield to the tail end of ivars.
13112   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13113   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13114 
13115   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13116                               DeclLoc, DeclLoc, nullptr,
13117                               Context.CharTy,
13118                               Context.getTrivialTypeSourceInfo(Context.CharTy,
13119                                                                DeclLoc),
13120                               ObjCIvarDecl::Private, BW,
13121                               true);
13122   AllIvarDecls.push_back(Ivar);
13123 }
13124 
13125 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13126                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
13127                        SourceLocation RBrac, AttributeList *Attr) {
13128   assert(EnclosingDecl && "missing record or interface decl");
13129 
13130   // If this is an Objective-C @implementation or category and we have
13131   // new fields here we should reset the layout of the interface since
13132   // it will now change.
13133   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13134     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13135     switch (DC->getKind()) {
13136     default: break;
13137     case Decl::ObjCCategory:
13138       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13139       break;
13140     case Decl::ObjCImplementation:
13141       Context.
13142         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13143       break;
13144     }
13145   }
13146 
13147   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13148 
13149   // Start counting up the number of named members; make sure to include
13150   // members of anonymous structs and unions in the total.
13151   unsigned NumNamedMembers = 0;
13152   if (Record) {
13153     for (const auto *I : Record->decls()) {
13154       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13155         if (IFD->getDeclName())
13156           ++NumNamedMembers;
13157     }
13158   }
13159 
13160   // Verify that all the fields are okay.
13161   SmallVector<FieldDecl*, 32> RecFields;
13162 
13163   bool ARCErrReported = false;
13164   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13165        i != end; ++i) {
13166     FieldDecl *FD = cast<FieldDecl>(*i);
13167 
13168     // Get the type for the field.
13169     const Type *FDTy = FD->getType().getTypePtr();
13170 
13171     if (!FD->isAnonymousStructOrUnion()) {
13172       // Remember all fields written by the user.
13173       RecFields.push_back(FD);
13174     }
13175 
13176     // If the field is already invalid for some reason, don't emit more
13177     // diagnostics about it.
13178     if (FD->isInvalidDecl()) {
13179       EnclosingDecl->setInvalidDecl();
13180       continue;
13181     }
13182 
13183     // C99 6.7.2.1p2:
13184     //   A structure or union shall not contain a member with
13185     //   incomplete or function type (hence, a structure shall not
13186     //   contain an instance of itself, but may contain a pointer to
13187     //   an instance of itself), except that the last member of a
13188     //   structure with more than one named member may have incomplete
13189     //   array type; such a structure (and any union containing,
13190     //   possibly recursively, a member that is such a structure)
13191     //   shall not be a member of a structure or an element of an
13192     //   array.
13193     if (FDTy->isFunctionType()) {
13194       // Field declared as a function.
13195       Diag(FD->getLocation(), diag::err_field_declared_as_function)
13196         << FD->getDeclName();
13197       FD->setInvalidDecl();
13198       EnclosingDecl->setInvalidDecl();
13199       continue;
13200     } else if (FDTy->isIncompleteArrayType() && Record &&
13201                ((i + 1 == Fields.end() && !Record->isUnion()) ||
13202                 ((getLangOpts().MicrosoftExt ||
13203                   getLangOpts().CPlusPlus) &&
13204                  (i + 1 == Fields.end() || Record->isUnion())))) {
13205       // Flexible array member.
13206       // Microsoft and g++ is more permissive regarding flexible array.
13207       // It will accept flexible array in union and also
13208       // as the sole element of a struct/class.
13209       unsigned DiagID = 0;
13210       if (Record->isUnion())
13211         DiagID = getLangOpts().MicrosoftExt
13212                      ? diag::ext_flexible_array_union_ms
13213                      : getLangOpts().CPlusPlus
13214                            ? diag::ext_flexible_array_union_gnu
13215                            : diag::err_flexible_array_union;
13216       else if (Fields.size() == 1)
13217         DiagID = getLangOpts().MicrosoftExt
13218                      ? diag::ext_flexible_array_empty_aggregate_ms
13219                      : getLangOpts().CPlusPlus
13220                            ? diag::ext_flexible_array_empty_aggregate_gnu
13221                            : NumNamedMembers < 1
13222                                  ? diag::err_flexible_array_empty_aggregate
13223                                  : 0;
13224 
13225       if (DiagID)
13226         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13227                                         << Record->getTagKind();
13228       // While the layout of types that contain virtual bases is not specified
13229       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13230       // virtual bases after the derived members.  This would make a flexible
13231       // array member declared at the end of an object not adjacent to the end
13232       // of the type.
13233       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13234         if (RD->getNumVBases() != 0)
13235           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13236             << FD->getDeclName() << Record->getTagKind();
13237       if (!getLangOpts().C99)
13238         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13239           << FD->getDeclName() << Record->getTagKind();
13240 
13241       // If the element type has a non-trivial destructor, we would not
13242       // implicitly destroy the elements, so disallow it for now.
13243       //
13244       // FIXME: GCC allows this. We should probably either implicitly delete
13245       // the destructor of the containing class, or just allow this.
13246       QualType BaseElem = Context.getBaseElementType(FD->getType());
13247       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13248         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13249           << FD->getDeclName() << FD->getType();
13250         FD->setInvalidDecl();
13251         EnclosingDecl->setInvalidDecl();
13252         continue;
13253       }
13254       // Okay, we have a legal flexible array member at the end of the struct.
13255       Record->setHasFlexibleArrayMember(true);
13256     } else if (!FDTy->isDependentType() &&
13257                RequireCompleteType(FD->getLocation(), FD->getType(),
13258                                    diag::err_field_incomplete)) {
13259       // Incomplete type
13260       FD->setInvalidDecl();
13261       EnclosingDecl->setInvalidDecl();
13262       continue;
13263     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13264       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13265         // A type which contains a flexible array member is considered to be a
13266         // flexible array member.
13267         Record->setHasFlexibleArrayMember(true);
13268         if (!Record->isUnion()) {
13269           // If this is a struct/class and this is not the last element, reject
13270           // it.  Note that GCC supports variable sized arrays in the middle of
13271           // structures.
13272           if (i + 1 != Fields.end())
13273             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13274               << FD->getDeclName() << FD->getType();
13275           else {
13276             // We support flexible arrays at the end of structs in
13277             // other structs as an extension.
13278             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13279               << FD->getDeclName();
13280           }
13281         }
13282       }
13283       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13284           RequireNonAbstractType(FD->getLocation(), FD->getType(),
13285                                  diag::err_abstract_type_in_decl,
13286                                  AbstractIvarType)) {
13287         // Ivars can not have abstract class types
13288         FD->setInvalidDecl();
13289       }
13290       if (Record && FDTTy->getDecl()->hasObjectMember())
13291         Record->setHasObjectMember(true);
13292       if (Record && FDTTy->getDecl()->hasVolatileMember())
13293         Record->setHasVolatileMember(true);
13294     } else if (FDTy->isObjCObjectType()) {
13295       /// A field cannot be an Objective-c object
13296       Diag(FD->getLocation(), diag::err_statically_allocated_object)
13297         << FixItHint::CreateInsertion(FD->getLocation(), "*");
13298       QualType T = Context.getObjCObjectPointerType(FD->getType());
13299       FD->setType(T);
13300     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13301                (!getLangOpts().CPlusPlus || Record->isUnion())) {
13302       // It's an error in ARC if a field has lifetime.
13303       // We don't want to report this in a system header, though,
13304       // so we just make the field unavailable.
13305       // FIXME: that's really not sufficient; we need to make the type
13306       // itself invalid to, say, initialize or copy.
13307       QualType T = FD->getType();
13308       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
13309       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13310         SourceLocation loc = FD->getLocation();
13311         if (getSourceManager().isInSystemHeader(loc)) {
13312           if (!FD->hasAttr<UnavailableAttr>()) {
13313             FD->addAttr(UnavailableAttr::CreateImplicit(Context,
13314                               "this system field has retaining ownership",
13315                               loc));
13316           }
13317         } else {
13318           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
13319             << T->isBlockPointerType() << Record->getTagKind();
13320         }
13321         ARCErrReported = true;
13322       }
13323     } else if (getLangOpts().ObjC1 &&
13324                getLangOpts().getGC() != LangOptions::NonGC &&
13325                Record && !Record->hasObjectMember()) {
13326       if (FD->getType()->isObjCObjectPointerType() ||
13327           FD->getType().isObjCGCStrong())
13328         Record->setHasObjectMember(true);
13329       else if (Context.getAsArrayType(FD->getType())) {
13330         QualType BaseType = Context.getBaseElementType(FD->getType());
13331         if (BaseType->isRecordType() &&
13332             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
13333           Record->setHasObjectMember(true);
13334         else if (BaseType->isObjCObjectPointerType() ||
13335                  BaseType.isObjCGCStrong())
13336                Record->setHasObjectMember(true);
13337       }
13338     }
13339     if (Record && FD->getType().isVolatileQualified())
13340       Record->setHasVolatileMember(true);
13341     // Keep track of the number of named members.
13342     if (FD->getIdentifier())
13343       ++NumNamedMembers;
13344   }
13345 
13346   // Okay, we successfully defined 'Record'.
13347   if (Record) {
13348     bool Completed = false;
13349     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
13350       if (!CXXRecord->isInvalidDecl()) {
13351         // Set access bits correctly on the directly-declared conversions.
13352         for (CXXRecordDecl::conversion_iterator
13353                I = CXXRecord->conversion_begin(),
13354                E = CXXRecord->conversion_end(); I != E; ++I)
13355           I.setAccess((*I)->getAccess());
13356 
13357         if (!CXXRecord->isDependentType()) {
13358           if (CXXRecord->hasUserDeclaredDestructor()) {
13359             // Adjust user-defined destructor exception spec.
13360             if (getLangOpts().CPlusPlus11)
13361               AdjustDestructorExceptionSpec(CXXRecord,
13362                                             CXXRecord->getDestructor());
13363           }
13364 
13365           // Add any implicitly-declared members to this class.
13366           AddImplicitlyDeclaredMembersToClass(CXXRecord);
13367 
13368           // If we have virtual base classes, we may end up finding multiple
13369           // final overriders for a given virtual function. Check for this
13370           // problem now.
13371           if (CXXRecord->getNumVBases()) {
13372             CXXFinalOverriderMap FinalOverriders;
13373             CXXRecord->getFinalOverriders(FinalOverriders);
13374 
13375             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
13376                                              MEnd = FinalOverriders.end();
13377                  M != MEnd; ++M) {
13378               for (OverridingMethods::iterator SO = M->second.begin(),
13379                                             SOEnd = M->second.end();
13380                    SO != SOEnd; ++SO) {
13381                 assert(SO->second.size() > 0 &&
13382                        "Virtual function without overridding functions?");
13383                 if (SO->second.size() == 1)
13384                   continue;
13385 
13386                 // C++ [class.virtual]p2:
13387                 //   In a derived class, if a virtual member function of a base
13388                 //   class subobject has more than one final overrider the
13389                 //   program is ill-formed.
13390                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
13391                   << (const NamedDecl *)M->first << Record;
13392                 Diag(M->first->getLocation(),
13393                      diag::note_overridden_virtual_function);
13394                 for (OverridingMethods::overriding_iterator
13395                           OM = SO->second.begin(),
13396                        OMEnd = SO->second.end();
13397                      OM != OMEnd; ++OM)
13398                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
13399                     << (const NamedDecl *)M->first << OM->Method->getParent();
13400 
13401                 Record->setInvalidDecl();
13402               }
13403             }
13404             CXXRecord->completeDefinition(&FinalOverriders);
13405             Completed = true;
13406           }
13407         }
13408       }
13409     }
13410 
13411     if (!Completed)
13412       Record->completeDefinition();
13413 
13414     if (Record->hasAttrs()) {
13415       CheckAlignasUnderalignment(Record);
13416 
13417       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
13418         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
13419                                            IA->getRange(), IA->getBestCase(),
13420                                            IA->getSemanticSpelling());
13421     }
13422 
13423     // Check if the structure/union declaration is a type that can have zero
13424     // size in C. For C this is a language extension, for C++ it may cause
13425     // compatibility problems.
13426     bool CheckForZeroSize;
13427     if (!getLangOpts().CPlusPlus) {
13428       CheckForZeroSize = true;
13429     } else {
13430       // For C++ filter out types that cannot be referenced in C code.
13431       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
13432       CheckForZeroSize =
13433           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
13434           !CXXRecord->isDependentType() &&
13435           CXXRecord->isCLike();
13436     }
13437     if (CheckForZeroSize) {
13438       bool ZeroSize = true;
13439       bool IsEmpty = true;
13440       unsigned NonBitFields = 0;
13441       for (RecordDecl::field_iterator I = Record->field_begin(),
13442                                       E = Record->field_end();
13443            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
13444         IsEmpty = false;
13445         if (I->isUnnamedBitfield()) {
13446           if (I->getBitWidthValue(Context) > 0)
13447             ZeroSize = false;
13448         } else {
13449           ++NonBitFields;
13450           QualType FieldType = I->getType();
13451           if (FieldType->isIncompleteType() ||
13452               !Context.getTypeSizeInChars(FieldType).isZero())
13453             ZeroSize = false;
13454         }
13455       }
13456 
13457       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
13458       // allowed in C++, but warn if its declaration is inside
13459       // extern "C" block.
13460       if (ZeroSize) {
13461         Diag(RecLoc, getLangOpts().CPlusPlus ?
13462                          diag::warn_zero_size_struct_union_in_extern_c :
13463                          diag::warn_zero_size_struct_union_compat)
13464           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
13465       }
13466 
13467       // Structs without named members are extension in C (C99 6.7.2.1p7),
13468       // but are accepted by GCC.
13469       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
13470         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
13471                                diag::ext_no_named_members_in_struct_union)
13472           << Record->isUnion();
13473       }
13474     }
13475   } else {
13476     ObjCIvarDecl **ClsFields =
13477       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
13478     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
13479       ID->setEndOfDefinitionLoc(RBrac);
13480       // Add ivar's to class's DeclContext.
13481       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13482         ClsFields[i]->setLexicalDeclContext(ID);
13483         ID->addDecl(ClsFields[i]);
13484       }
13485       // Must enforce the rule that ivars in the base classes may not be
13486       // duplicates.
13487       if (ID->getSuperClass())
13488         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
13489     } else if (ObjCImplementationDecl *IMPDecl =
13490                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13491       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
13492       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
13493         // Ivar declared in @implementation never belongs to the implementation.
13494         // Only it is in implementation's lexical context.
13495         ClsFields[I]->setLexicalDeclContext(IMPDecl);
13496       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
13497       IMPDecl->setIvarLBraceLoc(LBrac);
13498       IMPDecl->setIvarRBraceLoc(RBrac);
13499     } else if (ObjCCategoryDecl *CDecl =
13500                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13501       // case of ivars in class extension; all other cases have been
13502       // reported as errors elsewhere.
13503       // FIXME. Class extension does not have a LocEnd field.
13504       // CDecl->setLocEnd(RBrac);
13505       // Add ivar's to class extension's DeclContext.
13506       // Diagnose redeclaration of private ivars.
13507       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
13508       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13509         if (IDecl) {
13510           if (const ObjCIvarDecl *ClsIvar =
13511               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
13512             Diag(ClsFields[i]->getLocation(),
13513                  diag::err_duplicate_ivar_declaration);
13514             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
13515             continue;
13516           }
13517           for (const auto *Ext : IDecl->known_extensions()) {
13518             if (const ObjCIvarDecl *ClsExtIvar
13519                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
13520               Diag(ClsFields[i]->getLocation(),
13521                    diag::err_duplicate_ivar_declaration);
13522               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
13523               continue;
13524             }
13525           }
13526         }
13527         ClsFields[i]->setLexicalDeclContext(CDecl);
13528         CDecl->addDecl(ClsFields[i]);
13529       }
13530       CDecl->setIvarLBraceLoc(LBrac);
13531       CDecl->setIvarRBraceLoc(RBrac);
13532     }
13533   }
13534 
13535   if (Attr)
13536     ProcessDeclAttributeList(S, Record, Attr);
13537 }
13538 
13539 /// \brief Determine whether the given integral value is representable within
13540 /// the given type T.
13541 static bool isRepresentableIntegerValue(ASTContext &Context,
13542                                         llvm::APSInt &Value,
13543                                         QualType T) {
13544   assert(T->isIntegralType(Context) && "Integral type required!");
13545   unsigned BitWidth = Context.getIntWidth(T);
13546 
13547   if (Value.isUnsigned() || Value.isNonNegative()) {
13548     if (T->isSignedIntegerOrEnumerationType())
13549       --BitWidth;
13550     return Value.getActiveBits() <= BitWidth;
13551   }
13552   return Value.getMinSignedBits() <= BitWidth;
13553 }
13554 
13555 // \brief Given an integral type, return the next larger integral type
13556 // (or a NULL type of no such type exists).
13557 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
13558   // FIXME: Int128/UInt128 support, which also needs to be introduced into
13559   // enum checking below.
13560   assert(T->isIntegralType(Context) && "Integral type required!");
13561   const unsigned NumTypes = 4;
13562   QualType SignedIntegralTypes[NumTypes] = {
13563     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
13564   };
13565   QualType UnsignedIntegralTypes[NumTypes] = {
13566     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
13567     Context.UnsignedLongLongTy
13568   };
13569 
13570   unsigned BitWidth = Context.getTypeSize(T);
13571   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
13572                                                         : UnsignedIntegralTypes;
13573   for (unsigned I = 0; I != NumTypes; ++I)
13574     if (Context.getTypeSize(Types[I]) > BitWidth)
13575       return Types[I];
13576 
13577   return QualType();
13578 }
13579 
13580 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
13581                                           EnumConstantDecl *LastEnumConst,
13582                                           SourceLocation IdLoc,
13583                                           IdentifierInfo *Id,
13584                                           Expr *Val) {
13585   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13586   llvm::APSInt EnumVal(IntWidth);
13587   QualType EltTy;
13588 
13589   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
13590     Val = nullptr;
13591 
13592   if (Val)
13593     Val = DefaultLvalueConversion(Val).get();
13594 
13595   if (Val) {
13596     if (Enum->isDependentType() || Val->isTypeDependent())
13597       EltTy = Context.DependentTy;
13598     else {
13599       SourceLocation ExpLoc;
13600       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
13601           !getLangOpts().MSVCCompat) {
13602         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
13603         // constant-expression in the enumerator-definition shall be a converted
13604         // constant expression of the underlying type.
13605         EltTy = Enum->getIntegerType();
13606         ExprResult Converted =
13607           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
13608                                            CCEK_Enumerator);
13609         if (Converted.isInvalid())
13610           Val = nullptr;
13611         else
13612           Val = Converted.get();
13613       } else if (!Val->isValueDependent() &&
13614                  !(Val = VerifyIntegerConstantExpression(Val,
13615                                                          &EnumVal).get())) {
13616         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
13617       } else {
13618         if (Enum->isFixed()) {
13619           EltTy = Enum->getIntegerType();
13620 
13621           // In Obj-C and Microsoft mode, require the enumeration value to be
13622           // representable in the underlying type of the enumeration. In C++11,
13623           // we perform a non-narrowing conversion as part of converted constant
13624           // expression checking.
13625           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13626             if (getLangOpts().MSVCCompat) {
13627               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
13628               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13629             } else
13630               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
13631           } else
13632             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13633         } else if (getLangOpts().CPlusPlus) {
13634           // C++11 [dcl.enum]p5:
13635           //   If the underlying type is not fixed, the type of each enumerator
13636           //   is the type of its initializing value:
13637           //     - If an initializer is specified for an enumerator, the
13638           //       initializing value has the same type as the expression.
13639           EltTy = Val->getType();
13640         } else {
13641           // C99 6.7.2.2p2:
13642           //   The expression that defines the value of an enumeration constant
13643           //   shall be an integer constant expression that has a value
13644           //   representable as an int.
13645 
13646           // Complain if the value is not representable in an int.
13647           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
13648             Diag(IdLoc, diag::ext_enum_value_not_int)
13649               << EnumVal.toString(10) << Val->getSourceRange()
13650               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13651           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13652             // Force the type of the expression to 'int'.
13653             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
13654           }
13655           EltTy = Val->getType();
13656         }
13657       }
13658     }
13659   }
13660 
13661   if (!Val) {
13662     if (Enum->isDependentType())
13663       EltTy = Context.DependentTy;
13664     else if (!LastEnumConst) {
13665       // C++0x [dcl.enum]p5:
13666       //   If the underlying type is not fixed, the type of each enumerator
13667       //   is the type of its initializing value:
13668       //     - If no initializer is specified for the first enumerator, the
13669       //       initializing value has an unspecified integral type.
13670       //
13671       // GCC uses 'int' for its unspecified integral type, as does
13672       // C99 6.7.2.2p3.
13673       if (Enum->isFixed()) {
13674         EltTy = Enum->getIntegerType();
13675       }
13676       else {
13677         EltTy = Context.IntTy;
13678       }
13679     } else {
13680       // Assign the last value + 1.
13681       EnumVal = LastEnumConst->getInitVal();
13682       ++EnumVal;
13683       EltTy = LastEnumConst->getType();
13684 
13685       // Check for overflow on increment.
13686       if (EnumVal < LastEnumConst->getInitVal()) {
13687         // C++0x [dcl.enum]p5:
13688         //   If the underlying type is not fixed, the type of each enumerator
13689         //   is the type of its initializing value:
13690         //
13691         //     - Otherwise the type of the initializing value is the same as
13692         //       the type of the initializing value of the preceding enumerator
13693         //       unless the incremented value is not representable in that type,
13694         //       in which case the type is an unspecified integral type
13695         //       sufficient to contain the incremented value. If no such type
13696         //       exists, the program is ill-formed.
13697         QualType T = getNextLargerIntegralType(Context, EltTy);
13698         if (T.isNull() || Enum->isFixed()) {
13699           // There is no integral type larger enough to represent this
13700           // value. Complain, then allow the value to wrap around.
13701           EnumVal = LastEnumConst->getInitVal();
13702           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
13703           ++EnumVal;
13704           if (Enum->isFixed())
13705             // When the underlying type is fixed, this is ill-formed.
13706             Diag(IdLoc, diag::err_enumerator_wrapped)
13707               << EnumVal.toString(10)
13708               << EltTy;
13709           else
13710             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
13711               << EnumVal.toString(10);
13712         } else {
13713           EltTy = T;
13714         }
13715 
13716         // Retrieve the last enumerator's value, extent that type to the
13717         // type that is supposed to be large enough to represent the incremented
13718         // value, then increment.
13719         EnumVal = LastEnumConst->getInitVal();
13720         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13721         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
13722         ++EnumVal;
13723 
13724         // If we're not in C++, diagnose the overflow of enumerator values,
13725         // which in C99 means that the enumerator value is not representable in
13726         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
13727         // permits enumerator values that are representable in some larger
13728         // integral type.
13729         if (!getLangOpts().CPlusPlus && !T.isNull())
13730           Diag(IdLoc, diag::warn_enum_value_overflow);
13731       } else if (!getLangOpts().CPlusPlus &&
13732                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13733         // Enforce C99 6.7.2.2p2 even when we compute the next value.
13734         Diag(IdLoc, diag::ext_enum_value_not_int)
13735           << EnumVal.toString(10) << 1;
13736       }
13737     }
13738   }
13739 
13740   if (!EltTy->isDependentType()) {
13741     // Make the enumerator value match the signedness and size of the
13742     // enumerator's type.
13743     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
13744     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13745   }
13746 
13747   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
13748                                   Val, EnumVal);
13749 }
13750 
13751 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
13752                                                 SourceLocation IILoc) {
13753   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
13754       !getLangOpts().CPlusPlus)
13755     return SkipBodyInfo();
13756 
13757   // We have an anonymous enum definition. Look up the first enumerator to
13758   // determine if we should merge the definition with an existing one and
13759   // skip the body.
13760   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
13761                                          ForRedeclaration);
13762   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
13763   NamedDecl *Hidden;
13764   if (PrevECD &&
13765       !hasVisibleDefinition(cast<NamedDecl>(PrevECD->getDeclContext()),
13766                             &Hidden)) {
13767     SkipBodyInfo Skip;
13768     Skip.Previous = Hidden;
13769     return Skip;
13770   }
13771 
13772   return SkipBodyInfo();
13773 }
13774 
13775 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
13776                               SourceLocation IdLoc, IdentifierInfo *Id,
13777                               AttributeList *Attr,
13778                               SourceLocation EqualLoc, Expr *Val) {
13779   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
13780   EnumConstantDecl *LastEnumConst =
13781     cast_or_null<EnumConstantDecl>(lastEnumConst);
13782 
13783   // The scope passed in may not be a decl scope.  Zip up the scope tree until
13784   // we find one that is.
13785   S = getNonFieldDeclScope(S);
13786 
13787   // Verify that there isn't already something declared with this name in this
13788   // scope.
13789   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
13790                                          ForRedeclaration);
13791   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13792     // Maybe we will complain about the shadowed template parameter.
13793     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
13794     // Just pretend that we didn't see the previous declaration.
13795     PrevDecl = nullptr;
13796   }
13797 
13798   if (PrevDecl) {
13799     // When in C++, we may get a TagDecl with the same name; in this case the
13800     // enum constant will 'hide' the tag.
13801     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
13802            "Received TagDecl when not in C++!");
13803     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
13804       if (isa<EnumConstantDecl>(PrevDecl))
13805         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
13806       else
13807         Diag(IdLoc, diag::err_redefinition) << Id;
13808       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13809       return nullptr;
13810     }
13811   }
13812 
13813   // C++ [class.mem]p15:
13814   // If T is the name of a class, then each of the following shall have a name
13815   // different from T:
13816   // - every enumerator of every member of class T that is an unscoped
13817   // enumerated type
13818   if (!TheEnumDecl->isScoped())
13819     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
13820                             DeclarationNameInfo(Id, IdLoc));
13821 
13822   EnumConstantDecl *New =
13823     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
13824 
13825   if (New) {
13826     // Process attributes.
13827     if (Attr) ProcessDeclAttributeList(S, New, Attr);
13828 
13829     // Register this decl in the current scope stack.
13830     New->setAccess(TheEnumDecl->getAccess());
13831     PushOnScopeChains(New, S);
13832   }
13833 
13834   ActOnDocumentableDecl(New);
13835 
13836   return New;
13837 }
13838 
13839 // Returns true when the enum initial expression does not trigger the
13840 // duplicate enum warning.  A few common cases are exempted as follows:
13841 // Element2 = Element1
13842 // Element2 = Element1 + 1
13843 // Element2 = Element1 - 1
13844 // Where Element2 and Element1 are from the same enum.
13845 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
13846   Expr *InitExpr = ECD->getInitExpr();
13847   if (!InitExpr)
13848     return true;
13849   InitExpr = InitExpr->IgnoreImpCasts();
13850 
13851   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
13852     if (!BO->isAdditiveOp())
13853       return true;
13854     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
13855     if (!IL)
13856       return true;
13857     if (IL->getValue() != 1)
13858       return true;
13859 
13860     InitExpr = BO->getLHS();
13861   }
13862 
13863   // This checks if the elements are from the same enum.
13864   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
13865   if (!DRE)
13866     return true;
13867 
13868   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
13869   if (!EnumConstant)
13870     return true;
13871 
13872   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
13873       Enum)
13874     return true;
13875 
13876   return false;
13877 }
13878 
13879 struct DupKey {
13880   int64_t val;
13881   bool isTombstoneOrEmptyKey;
13882   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
13883     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
13884 };
13885 
13886 static DupKey GetDupKey(const llvm::APSInt& Val) {
13887   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
13888                 false);
13889 }
13890 
13891 struct DenseMapInfoDupKey {
13892   static DupKey getEmptyKey() { return DupKey(0, true); }
13893   static DupKey getTombstoneKey() { return DupKey(1, true); }
13894   static unsigned getHashValue(const DupKey Key) {
13895     return (unsigned)(Key.val * 37);
13896   }
13897   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
13898     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
13899            LHS.val == RHS.val;
13900   }
13901 };
13902 
13903 // Emits a warning when an element is implicitly set a value that
13904 // a previous element has already been set to.
13905 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
13906                                         EnumDecl *Enum,
13907                                         QualType EnumType) {
13908   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
13909     return;
13910   // Avoid anonymous enums
13911   if (!Enum->getIdentifier())
13912     return;
13913 
13914   // Only check for small enums.
13915   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
13916     return;
13917 
13918   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
13919   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
13920 
13921   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
13922   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
13923           ValueToVectorMap;
13924 
13925   DuplicatesVector DupVector;
13926   ValueToVectorMap EnumMap;
13927 
13928   // Populate the EnumMap with all values represented by enum constants without
13929   // an initialier.
13930   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13931     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
13932 
13933     // Null EnumConstantDecl means a previous diagnostic has been emitted for
13934     // this constant.  Skip this enum since it may be ill-formed.
13935     if (!ECD) {
13936       return;
13937     }
13938 
13939     if (ECD->getInitExpr())
13940       continue;
13941 
13942     DupKey Key = GetDupKey(ECD->getInitVal());
13943     DeclOrVector &Entry = EnumMap[Key];
13944 
13945     // First time encountering this value.
13946     if (Entry.isNull())
13947       Entry = ECD;
13948   }
13949 
13950   // Create vectors for any values that has duplicates.
13951   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13952     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
13953     if (!ValidDuplicateEnum(ECD, Enum))
13954       continue;
13955 
13956     DupKey Key = GetDupKey(ECD->getInitVal());
13957 
13958     DeclOrVector& Entry = EnumMap[Key];
13959     if (Entry.isNull())
13960       continue;
13961 
13962     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
13963       // Ensure constants are different.
13964       if (D == ECD)
13965         continue;
13966 
13967       // Create new vector and push values onto it.
13968       ECDVector *Vec = new ECDVector();
13969       Vec->push_back(D);
13970       Vec->push_back(ECD);
13971 
13972       // Update entry to point to the duplicates vector.
13973       Entry = Vec;
13974 
13975       // Store the vector somewhere we can consult later for quick emission of
13976       // diagnostics.
13977       DupVector.push_back(Vec);
13978       continue;
13979     }
13980 
13981     ECDVector *Vec = Entry.get<ECDVector*>();
13982     // Make sure constants are not added more than once.
13983     if (*Vec->begin() == ECD)
13984       continue;
13985 
13986     Vec->push_back(ECD);
13987   }
13988 
13989   // Emit diagnostics.
13990   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
13991                                   DupVectorEnd = DupVector.end();
13992        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
13993     ECDVector *Vec = *DupVectorIter;
13994     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
13995 
13996     // Emit warning for one enum constant.
13997     ECDVector::iterator I = Vec->begin();
13998     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
13999       << (*I)->getName() << (*I)->getInitVal().toString(10)
14000       << (*I)->getSourceRange();
14001     ++I;
14002 
14003     // Emit one note for each of the remaining enum constants with
14004     // the same value.
14005     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14006       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14007         << (*I)->getName() << (*I)->getInitVal().toString(10)
14008         << (*I)->getSourceRange();
14009     delete Vec;
14010   }
14011 }
14012 
14013 bool
14014 Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14015                         bool AllowMask) const {
14016   FlagEnumAttr *FEAttr = ED->getAttr<FlagEnumAttr>();
14017   assert(FEAttr && "looking for value in non-flag enum");
14018 
14019   llvm::APInt FlagMask = ~FEAttr->getFlagBits();
14020   unsigned Width = FlagMask.getBitWidth();
14021 
14022   // We will try a zero-extended value for the regular check first.
14023   llvm::APInt ExtVal = Val.zextOrSelf(Width);
14024 
14025   // A value is in a flag enum if either its bits are a subset of the enum's
14026   // flag bits (the first condition) or we are allowing masks and the same is
14027   // true of its complement (the second condition). When masks are allowed, we
14028   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14029   //
14030   // While it's true that any value could be used as a mask, the assumption is
14031   // that a mask will have all of the insignificant bits set. Anything else is
14032   // likely a logic error.
14033   if (!(FlagMask & ExtVal))
14034     return true;
14035 
14036   if (AllowMask) {
14037     // Try a one-extended value instead. This can happen if the enum is wider
14038     // than the constant used, in C with extensions to allow for wider enums.
14039     // The mask will still have the correct behaviour, so we give the user the
14040     // benefit of the doubt.
14041     //
14042     // FIXME: This heuristic can cause weird results if the enum was extended
14043     // to a larger type and is signed, because then bit-masks of smaller types
14044     // that get extended will fall out of range (e.g. ~0x1u). We currently don't
14045     // detect that case and will get a false positive for it. In most cases,
14046     // though, it can be fixed by making it a signed type (e.g. ~0x1), so it may
14047     // be fine just to accept this as a warning.
14048     ExtVal |= llvm::APInt::getHighBitsSet(Width, Width - Val.getBitWidth());
14049     if (!(FlagMask & ~ExtVal))
14050       return true;
14051   }
14052 
14053   return false;
14054 }
14055 
14056 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14057                          SourceLocation RBraceLoc, Decl *EnumDeclX,
14058                          ArrayRef<Decl *> Elements,
14059                          Scope *S, AttributeList *Attr) {
14060   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14061   QualType EnumType = Context.getTypeDeclType(Enum);
14062 
14063   if (Attr)
14064     ProcessDeclAttributeList(S, Enum, Attr);
14065 
14066   if (Enum->isDependentType()) {
14067     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14068       EnumConstantDecl *ECD =
14069         cast_or_null<EnumConstantDecl>(Elements[i]);
14070       if (!ECD) continue;
14071 
14072       ECD->setType(EnumType);
14073     }
14074 
14075     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14076     return;
14077   }
14078 
14079   // TODO: If the result value doesn't fit in an int, it must be a long or long
14080   // long value.  ISO C does not support this, but GCC does as an extension,
14081   // emit a warning.
14082   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14083   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14084   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14085 
14086   // Verify that all the values are okay, compute the size of the values, and
14087   // reverse the list.
14088   unsigned NumNegativeBits = 0;
14089   unsigned NumPositiveBits = 0;
14090 
14091   // Keep track of whether all elements have type int.
14092   bool AllElementsInt = true;
14093 
14094   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14095     EnumConstantDecl *ECD =
14096       cast_or_null<EnumConstantDecl>(Elements[i]);
14097     if (!ECD) continue;  // Already issued a diagnostic.
14098 
14099     const llvm::APSInt &InitVal = ECD->getInitVal();
14100 
14101     // Keep track of the size of positive and negative values.
14102     if (InitVal.isUnsigned() || InitVal.isNonNegative())
14103       NumPositiveBits = std::max(NumPositiveBits,
14104                                  (unsigned)InitVal.getActiveBits());
14105     else
14106       NumNegativeBits = std::max(NumNegativeBits,
14107                                  (unsigned)InitVal.getMinSignedBits());
14108 
14109     // Keep track of whether every enum element has type int (very commmon).
14110     if (AllElementsInt)
14111       AllElementsInt = ECD->getType() == Context.IntTy;
14112   }
14113 
14114   // Figure out the type that should be used for this enum.
14115   QualType BestType;
14116   unsigned BestWidth;
14117 
14118   // C++0x N3000 [conv.prom]p3:
14119   //   An rvalue of an unscoped enumeration type whose underlying
14120   //   type is not fixed can be converted to an rvalue of the first
14121   //   of the following types that can represent all the values of
14122   //   the enumeration: int, unsigned int, long int, unsigned long
14123   //   int, long long int, or unsigned long long int.
14124   // C99 6.4.4.3p2:
14125   //   An identifier declared as an enumeration constant has type int.
14126   // The C99 rule is modified by a gcc extension
14127   QualType BestPromotionType;
14128 
14129   bool Packed = Enum->hasAttr<PackedAttr>();
14130   // -fshort-enums is the equivalent to specifying the packed attribute on all
14131   // enum definitions.
14132   if (LangOpts.ShortEnums)
14133     Packed = true;
14134 
14135   if (Enum->isFixed()) {
14136     BestType = Enum->getIntegerType();
14137     if (BestType->isPromotableIntegerType())
14138       BestPromotionType = Context.getPromotedIntegerType(BestType);
14139     else
14140       BestPromotionType = BestType;
14141 
14142     BestWidth = Context.getIntWidth(BestType);
14143   }
14144   else if (NumNegativeBits) {
14145     // If there is a negative value, figure out the smallest integer type (of
14146     // int/long/longlong) that fits.
14147     // If it's packed, check also if it fits a char or a short.
14148     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14149       BestType = Context.SignedCharTy;
14150       BestWidth = CharWidth;
14151     } else if (Packed && NumNegativeBits <= ShortWidth &&
14152                NumPositiveBits < ShortWidth) {
14153       BestType = Context.ShortTy;
14154       BestWidth = ShortWidth;
14155     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14156       BestType = Context.IntTy;
14157       BestWidth = IntWidth;
14158     } else {
14159       BestWidth = Context.getTargetInfo().getLongWidth();
14160 
14161       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14162         BestType = Context.LongTy;
14163       } else {
14164         BestWidth = Context.getTargetInfo().getLongLongWidth();
14165 
14166         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14167           Diag(Enum->getLocation(), diag::ext_enum_too_large);
14168         BestType = Context.LongLongTy;
14169       }
14170     }
14171     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14172   } else {
14173     // If there is no negative value, figure out the smallest type that fits
14174     // all of the enumerator values.
14175     // If it's packed, check also if it fits a char or a short.
14176     if (Packed && NumPositiveBits <= CharWidth) {
14177       BestType = Context.UnsignedCharTy;
14178       BestPromotionType = Context.IntTy;
14179       BestWidth = CharWidth;
14180     } else if (Packed && NumPositiveBits <= ShortWidth) {
14181       BestType = Context.UnsignedShortTy;
14182       BestPromotionType = Context.IntTy;
14183       BestWidth = ShortWidth;
14184     } else if (NumPositiveBits <= IntWidth) {
14185       BestType = Context.UnsignedIntTy;
14186       BestWidth = IntWidth;
14187       BestPromotionType
14188         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14189                            ? Context.UnsignedIntTy : Context.IntTy;
14190     } else if (NumPositiveBits <=
14191                (BestWidth = Context.getTargetInfo().getLongWidth())) {
14192       BestType = Context.UnsignedLongTy;
14193       BestPromotionType
14194         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14195                            ? Context.UnsignedLongTy : Context.LongTy;
14196     } else {
14197       BestWidth = Context.getTargetInfo().getLongLongWidth();
14198       assert(NumPositiveBits <= BestWidth &&
14199              "How could an initializer get larger than ULL?");
14200       BestType = Context.UnsignedLongLongTy;
14201       BestPromotionType
14202         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14203                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
14204     }
14205   }
14206 
14207   FlagEnumAttr *FEAttr = Enum->getAttr<FlagEnumAttr>();
14208   if (FEAttr)
14209     FEAttr->getFlagBits() = llvm::APInt(BestWidth, 0);
14210 
14211   // Loop over all of the enumerator constants, changing their types to match
14212   // the type of the enum if needed. If we have a flag type, we also prepare the
14213   // FlagBits cache.
14214   for (auto *D : Elements) {
14215     auto *ECD = cast_or_null<EnumConstantDecl>(D);
14216     if (!ECD) continue;  // Already issued a diagnostic.
14217 
14218     // Standard C says the enumerators have int type, but we allow, as an
14219     // extension, the enumerators to be larger than int size.  If each
14220     // enumerator value fits in an int, type it as an int, otherwise type it the
14221     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
14222     // that X has type 'int', not 'unsigned'.
14223 
14224     // Determine whether the value fits into an int.
14225     llvm::APSInt InitVal = ECD->getInitVal();
14226 
14227     // If it fits into an integer type, force it.  Otherwise force it to match
14228     // the enum decl type.
14229     QualType NewTy;
14230     unsigned NewWidth;
14231     bool NewSign;
14232     if (!getLangOpts().CPlusPlus &&
14233         !Enum->isFixed() &&
14234         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14235       NewTy = Context.IntTy;
14236       NewWidth = IntWidth;
14237       NewSign = true;
14238     } else if (ECD->getType() == BestType) {
14239       // Already the right type!
14240       if (getLangOpts().CPlusPlus)
14241         // C++ [dcl.enum]p4: Following the closing brace of an
14242         // enum-specifier, each enumerator has the type of its
14243         // enumeration.
14244         ECD->setType(EnumType);
14245       goto flagbits;
14246     } else {
14247       NewTy = BestType;
14248       NewWidth = BestWidth;
14249       NewSign = BestType->isSignedIntegerOrEnumerationType();
14250     }
14251 
14252     // Adjust the APSInt value.
14253     InitVal = InitVal.extOrTrunc(NewWidth);
14254     InitVal.setIsSigned(NewSign);
14255     ECD->setInitVal(InitVal);
14256 
14257     // Adjust the Expr initializer and type.
14258     if (ECD->getInitExpr() &&
14259         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14260       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14261                                                 CK_IntegralCast,
14262                                                 ECD->getInitExpr(),
14263                                                 /*base paths*/ nullptr,
14264                                                 VK_RValue));
14265     if (getLangOpts().CPlusPlus)
14266       // C++ [dcl.enum]p4: Following the closing brace of an
14267       // enum-specifier, each enumerator has the type of its
14268       // enumeration.
14269       ECD->setType(EnumType);
14270     else
14271       ECD->setType(NewTy);
14272 
14273 flagbits:
14274     // Check to see if we have a constant with exactly one bit set. Note that x
14275     // & (x - 1) will be nonzero if and only if x has more than one bit set.
14276     if (FEAttr) {
14277       llvm::APInt ExtVal = InitVal.zextOrSelf(BestWidth);
14278       if (ExtVal != 0 && !(ExtVal & (ExtVal - 1))) {
14279         FEAttr->getFlagBits() |= ExtVal;
14280       }
14281     }
14282   }
14283 
14284   if (FEAttr) {
14285     for (Decl *D : Elements) {
14286       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14287       if (!ECD) continue;  // Already issued a diagnostic.
14288 
14289       llvm::APSInt InitVal = ECD->getInitVal();
14290       if (InitVal != 0 && !IsValueInFlagEnum(Enum, InitVal, true))
14291         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14292           << ECD << Enum;
14293     }
14294   }
14295 
14296 
14297 
14298   Enum->completeDefinition(BestType, BestPromotionType,
14299                            NumPositiveBits, NumNegativeBits);
14300 
14301   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14302 
14303   // Now that the enum type is defined, ensure it's not been underaligned.
14304   if (Enum->hasAttrs())
14305     CheckAlignasUnderalignment(Enum);
14306 }
14307 
14308 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
14309                                   SourceLocation StartLoc,
14310                                   SourceLocation EndLoc) {
14311   StringLiteral *AsmString = cast<StringLiteral>(expr);
14312 
14313   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
14314                                                    AsmString, StartLoc,
14315                                                    EndLoc);
14316   CurContext->addDecl(New);
14317   return New;
14318 }
14319 
14320 static void checkModuleImportContext(Sema &S, Module *M,
14321                                      SourceLocation ImportLoc,
14322                                      DeclContext *DC) {
14323   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14324     switch (LSD->getLanguage()) {
14325     case LinkageSpecDecl::lang_c:
14326       if (!M->IsExternC) {
14327         S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
14328           << M->getFullModuleName();
14329         S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
14330         return;
14331       }
14332       break;
14333     case LinkageSpecDecl::lang_cxx:
14334       break;
14335     }
14336     DC = LSD->getParent();
14337   }
14338 
14339   while (isa<LinkageSpecDecl>(DC))
14340     DC = DC->getParent();
14341   if (!isa<TranslationUnitDecl>(DC)) {
14342     S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
14343       << M->getFullModuleName() << DC;
14344     S.Diag(cast<Decl>(DC)->getLocStart(),
14345            diag::note_module_import_not_at_top_level)
14346       << DC;
14347   }
14348 }
14349 
14350 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
14351                                    SourceLocation ImportLoc,
14352                                    ModuleIdPath Path) {
14353   Module *Mod =
14354       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
14355                                    /*IsIncludeDirective=*/false);
14356   if (!Mod)
14357     return true;
14358 
14359   VisibleModules.setVisible(Mod, ImportLoc);
14360 
14361   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
14362 
14363   // FIXME: we should support importing a submodule within a different submodule
14364   // of the same top-level module. Until we do, make it an error rather than
14365   // silently ignoring the import.
14366   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
14367     Diag(ImportLoc, diag::err_module_self_import)
14368         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
14369   else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
14370     Diag(ImportLoc, diag::err_module_import_in_implementation)
14371         << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
14372 
14373   SmallVector<SourceLocation, 2> IdentifierLocs;
14374   Module *ModCheck = Mod;
14375   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
14376     // If we've run out of module parents, just drop the remaining identifiers.
14377     // We need the length to be consistent.
14378     if (!ModCheck)
14379       break;
14380     ModCheck = ModCheck->Parent;
14381 
14382     IdentifierLocs.push_back(Path[I].second);
14383   }
14384 
14385   ImportDecl *Import = ImportDecl::Create(Context,
14386                                           Context.getTranslationUnitDecl(),
14387                                           AtLoc.isValid()? AtLoc : ImportLoc,
14388                                           Mod, IdentifierLocs);
14389   Context.getTranslationUnitDecl()->addDecl(Import);
14390   return Import;
14391 }
14392 
14393 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
14394   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14395 
14396   // Determine whether we're in the #include buffer for a module. The #includes
14397   // in that buffer do not qualify as module imports; they're just an
14398   // implementation detail of us building the module.
14399   //
14400   // FIXME: Should we even get ActOnModuleInclude calls for those?
14401   bool IsInModuleIncludes =
14402       TUKind == TU_Module &&
14403       getSourceManager().isWrittenInMainFile(DirectiveLoc);
14404 
14405   // If this module import was due to an inclusion directive, create an
14406   // implicit import declaration to capture it in the AST.
14407   if (!IsInModuleIncludes) {
14408     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14409     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14410                                                      DirectiveLoc, Mod,
14411                                                      DirectiveLoc);
14412     TU->addDecl(ImportD);
14413     Consumer.HandleImplicitImportDecl(ImportD);
14414   }
14415 
14416   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
14417   VisibleModules.setVisible(Mod, DirectiveLoc);
14418 }
14419 
14420 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
14421   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14422 
14423   if (getLangOpts().ModulesLocalVisibility)
14424     VisibleModulesStack.push_back(std::move(VisibleModules));
14425   VisibleModules.setVisible(Mod, DirectiveLoc);
14426 }
14427 
14428 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
14429   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14430 
14431   if (getLangOpts().ModulesLocalVisibility) {
14432     VisibleModules = std::move(VisibleModulesStack.back());
14433     VisibleModulesStack.pop_back();
14434     VisibleModules.setVisible(Mod, DirectiveLoc);
14435   }
14436 }
14437 
14438 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
14439                                                       Module *Mod) {
14440   // Bail if we're not allowed to implicitly import a module here.
14441   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
14442     return;
14443 
14444   // Create the implicit import declaration.
14445   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14446   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14447                                                    Loc, Mod, Loc);
14448   TU->addDecl(ImportD);
14449   Consumer.HandleImplicitImportDecl(ImportD);
14450 
14451   // Make the module visible.
14452   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
14453   VisibleModules.setVisible(Mod, Loc);
14454 }
14455 
14456 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
14457                                       IdentifierInfo* AliasName,
14458                                       SourceLocation PragmaLoc,
14459                                       SourceLocation NameLoc,
14460                                       SourceLocation AliasNameLoc) {
14461   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
14462                                          LookupOrdinaryName);
14463   AsmLabelAttr *Attr =
14464       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
14465 
14466   // If a declaration that:
14467   // 1) declares a function or a variable
14468   // 2) has external linkage
14469   // already exists, add a label attribute to it.
14470   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
14471     if (isDeclExternC(PrevDecl))
14472       PrevDecl->addAttr(Attr);
14473     else
14474       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
14475           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
14476   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
14477   } else
14478     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
14479 }
14480 
14481 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
14482                              SourceLocation PragmaLoc,
14483                              SourceLocation NameLoc) {
14484   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
14485 
14486   if (PrevDecl) {
14487     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
14488   } else {
14489     (void)WeakUndeclaredIdentifiers.insert(
14490       std::pair<IdentifierInfo*,WeakInfo>
14491         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
14492   }
14493 }
14494 
14495 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
14496                                 IdentifierInfo* AliasName,
14497                                 SourceLocation PragmaLoc,
14498                                 SourceLocation NameLoc,
14499                                 SourceLocation AliasNameLoc) {
14500   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
14501                                     LookupOrdinaryName);
14502   WeakInfo W = WeakInfo(Name, NameLoc);
14503 
14504   if (PrevDecl) {
14505     if (!PrevDecl->hasAttr<AliasAttr>())
14506       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
14507         DeclApplyPragmaWeak(TUScope, ND, W);
14508   } else {
14509     (void)WeakUndeclaredIdentifiers.insert(
14510       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
14511   }
14512 }
14513 
14514 Decl *Sema::getObjCDeclContext() const {
14515   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
14516 }
14517 
14518 AvailabilityResult Sema::getCurContextAvailability() const {
14519   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
14520   if (!D)
14521     return AR_Available;
14522 
14523   // If we are within an Objective-C method, we should consult
14524   // both the availability of the method as well as the
14525   // enclosing class.  If the class is (say) deprecated,
14526   // the entire method is considered deprecated from the
14527   // purpose of checking if the current context is deprecated.
14528   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
14529     AvailabilityResult R = MD->getAvailability();
14530     if (R != AR_Available)
14531       return R;
14532     D = MD->getClassInterface();
14533   }
14534   // If we are within an Objective-c @implementation, it
14535   // gets the same availability context as the @interface.
14536   else if (const ObjCImplementationDecl *ID =
14537             dyn_cast<ObjCImplementationDecl>(D)) {
14538     D = ID->getClassInterface();
14539   }
14540   // Recover from user error.
14541   return D ? D->getAvailability() : AR_Available;
14542 }
14543