1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 using namespace clang;
51 using namespace sema;
52 
53 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
54   if (OwnedType) {
55     Decl *Group[2] = { OwnedType, Ptr };
56     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
57   }
58 
59   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
60 }
61 
62 namespace {
63 
64 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
65  public:
66   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
67                        bool AllowTemplates=false)
68       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
69         AllowClassTemplates(AllowTemplates) {
70     WantExpressionKeywords = false;
71     WantCXXNamedCasts = false;
72     WantRemainingKeywords = false;
73   }
74 
75   bool ValidateCandidate(const TypoCorrection &candidate) override {
76     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
77       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
78       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
79       return (IsType || AllowedTemplate) &&
80              (AllowInvalidDecl || !ND->isInvalidDecl());
81     }
82     return !WantClassName && candidate.isKeyword();
83   }
84 
85  private:
86   bool AllowInvalidDecl;
87   bool WantClassName;
88   bool AllowClassTemplates;
89 };
90 
91 }
92 
93 /// \brief Determine whether the token kind starts a simple-type-specifier.
94 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
95   switch (Kind) {
96   // FIXME: Take into account the current language when deciding whether a
97   // token kind is a valid type specifier
98   case tok::kw_short:
99   case tok::kw_long:
100   case tok::kw___int64:
101   case tok::kw___int128:
102   case tok::kw_signed:
103   case tok::kw_unsigned:
104   case tok::kw_void:
105   case tok::kw_char:
106   case tok::kw_int:
107   case tok::kw_half:
108   case tok::kw_float:
109   case tok::kw_double:
110   case tok::kw_wchar_t:
111   case tok::kw_bool:
112   case tok::kw___underlying_type:
113   case tok::kw___auto_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, S);
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 (S.getLangOpts().CPlusPlus &&
1832           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1833           Decl->getAnonDeclWithTypedefName())
1834         continue;
1835     }
1836 
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(Scope *S, TypedefNameDecl *New,
1883                                 LookupResult &OldDecls) {
1884   // If the new decl is known invalid already, don't bother doing any
1885   // merging checks.
1886   if (New->isInvalidDecl()) return;
1887 
1888   // Allow multiple definitions for ObjC built-in typedefs.
1889   // FIXME: Verify the underlying types are equivalent!
1890   if (getLangOpts().ObjC1) {
1891     const IdentifierInfo *TypeID = New->getIdentifier();
1892     switch (TypeID->getLength()) {
1893     default: break;
1894     case 2:
1895       {
1896         if (!TypeID->isStr("id"))
1897           break;
1898         QualType T = New->getUnderlyingType();
1899         if (!T->isPointerType())
1900           break;
1901         if (!T->isVoidPointerType()) {
1902           QualType PT = T->getAs<PointerType>()->getPointeeType();
1903           if (!PT->isStructureType())
1904             break;
1905         }
1906         Context.setObjCIdRedefinitionType(T);
1907         // Install the built-in type for 'id', ignoring the current definition.
1908         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1909         return;
1910       }
1911     case 5:
1912       if (!TypeID->isStr("Class"))
1913         break;
1914       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1915       // Install the built-in type for 'Class', ignoring the current definition.
1916       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1917       return;
1918     case 3:
1919       if (!TypeID->isStr("SEL"))
1920         break;
1921       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1922       // Install the built-in type for 'SEL', ignoring the current definition.
1923       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1924       return;
1925     }
1926     // Fall through - the typedef name was not a builtin type.
1927   }
1928 
1929   // Verify the old decl was also a type.
1930   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1931   if (!Old) {
1932     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1933       << New->getDeclName();
1934 
1935     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1936     if (OldD->getLocation().isValid())
1937       Diag(OldD->getLocation(), diag::note_previous_definition);
1938 
1939     return New->setInvalidDecl();
1940   }
1941 
1942   // If the old declaration is invalid, just give up here.
1943   if (Old->isInvalidDecl())
1944     return New->setInvalidDecl();
1945 
1946   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1947     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
1948     auto *NewTag = New->getAnonDeclWithTypedefName();
1949     NamedDecl *Hidden = nullptr;
1950     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
1951         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
1952         !hasVisibleDefinition(OldTag, &Hidden)) {
1953       // There is a definition of this tag, but it is not visible. Use it
1954       // instead of our tag.
1955       New->setTypeForDecl(OldTD->getTypeForDecl());
1956       if (OldTD->isModed())
1957         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
1958                                     OldTD->getUnderlyingType());
1959       else
1960         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
1961 
1962       // Make the old tag definition visible.
1963       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
1964 
1965       // If this was an unscoped enumeration, yank all of its enumerators
1966       // out of the scope.
1967       if (isa<EnumDecl>(NewTag)) {
1968         Scope *EnumScope = getNonFieldDeclScope(S);
1969         for (auto *D : NewTag->decls()) {
1970           auto *ED = cast<EnumConstantDecl>(D);
1971           assert(EnumScope->isDeclScope(ED));
1972           EnumScope->RemoveDecl(ED);
1973           IdResolver.RemoveDecl(ED);
1974           ED->getLexicalDeclContext()->removeDecl(ED);
1975         }
1976       }
1977     }
1978   }
1979 
1980   // If the typedef types are not identical, reject them in all languages and
1981   // with any extensions enabled.
1982   if (isIncompatibleTypedef(Old, New))
1983     return;
1984 
1985   // The types match.  Link up the redeclaration chain and merge attributes if
1986   // the old declaration was a typedef.
1987   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1988     New->setPreviousDecl(Typedef);
1989     mergeDeclAttributes(New, Old);
1990   }
1991 
1992   if (getLangOpts().MicrosoftExt)
1993     return;
1994 
1995   if (getLangOpts().CPlusPlus) {
1996     // C++ [dcl.typedef]p2:
1997     //   In a given non-class scope, a typedef specifier can be used to
1998     //   redefine the name of any type declared in that scope to refer
1999     //   to the type to which it already refers.
2000     if (!isa<CXXRecordDecl>(CurContext))
2001       return;
2002 
2003     // C++0x [dcl.typedef]p4:
2004     //   In a given class scope, a typedef specifier can be used to redefine
2005     //   any class-name declared in that scope that is not also a typedef-name
2006     //   to refer to the type to which it already refers.
2007     //
2008     // This wording came in via DR424, which was a correction to the
2009     // wording in DR56, which accidentally banned code like:
2010     //
2011     //   struct S {
2012     //     typedef struct A { } A;
2013     //   };
2014     //
2015     // in the C++03 standard. We implement the C++0x semantics, which
2016     // allow the above but disallow
2017     //
2018     //   struct S {
2019     //     typedef int I;
2020     //     typedef int I;
2021     //   };
2022     //
2023     // since that was the intent of DR56.
2024     if (!isa<TypedefNameDecl>(Old))
2025       return;
2026 
2027     Diag(New->getLocation(), diag::err_redefinition)
2028       << New->getDeclName();
2029     Diag(Old->getLocation(), diag::note_previous_definition);
2030     return New->setInvalidDecl();
2031   }
2032 
2033   // Modules always permit redefinition of typedefs, as does C11.
2034   if (getLangOpts().Modules || getLangOpts().C11)
2035     return;
2036 
2037   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2038   // is normally mapped to an error, but can be controlled with
2039   // -Wtypedef-redefinition.  If either the original or the redefinition is
2040   // in a system header, don't emit this for compatibility with GCC.
2041   if (getDiagnostics().getSuppressSystemWarnings() &&
2042       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2043        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2044     return;
2045 
2046   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2047     << New->getDeclName();
2048   Diag(Old->getLocation(), diag::note_previous_definition);
2049 }
2050 
2051 /// DeclhasAttr - returns true if decl Declaration already has the target
2052 /// attribute.
2053 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2054   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2055   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2056   for (const auto *i : D->attrs())
2057     if (i->getKind() == A->getKind()) {
2058       if (Ann) {
2059         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2060           return true;
2061         continue;
2062       }
2063       // FIXME: Don't hardcode this check
2064       if (OA && isa<OwnershipAttr>(i))
2065         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2066       return true;
2067     }
2068 
2069   return false;
2070 }
2071 
2072 static bool isAttributeTargetADefinition(Decl *D) {
2073   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2074     return VD->isThisDeclarationADefinition();
2075   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2076     return TD->isCompleteDefinition() || TD->isBeingDefined();
2077   return true;
2078 }
2079 
2080 /// Merge alignment attributes from \p Old to \p New, taking into account the
2081 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2082 ///
2083 /// \return \c true if any attributes were added to \p New.
2084 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2085   // Look for alignas attributes on Old, and pick out whichever attribute
2086   // specifies the strictest alignment requirement.
2087   AlignedAttr *OldAlignasAttr = nullptr;
2088   AlignedAttr *OldStrictestAlignAttr = nullptr;
2089   unsigned OldAlign = 0;
2090   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2091     // FIXME: We have no way of representing inherited dependent alignments
2092     // in a case like:
2093     //   template<int A, int B> struct alignas(A) X;
2094     //   template<int A, int B> struct alignas(B) X {};
2095     // For now, we just ignore any alignas attributes which are not on the
2096     // definition in such a case.
2097     if (I->isAlignmentDependent())
2098       return false;
2099 
2100     if (I->isAlignas())
2101       OldAlignasAttr = I;
2102 
2103     unsigned Align = I->getAlignment(S.Context);
2104     if (Align > OldAlign) {
2105       OldAlign = Align;
2106       OldStrictestAlignAttr = I;
2107     }
2108   }
2109 
2110   // Look for alignas attributes on New.
2111   AlignedAttr *NewAlignasAttr = nullptr;
2112   unsigned NewAlign = 0;
2113   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2114     if (I->isAlignmentDependent())
2115       return false;
2116 
2117     if (I->isAlignas())
2118       NewAlignasAttr = I;
2119 
2120     unsigned Align = I->getAlignment(S.Context);
2121     if (Align > NewAlign)
2122       NewAlign = Align;
2123   }
2124 
2125   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2126     // Both declarations have 'alignas' attributes. We require them to match.
2127     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2128     // fall short. (If two declarations both have alignas, they must both match
2129     // every definition, and so must match each other if there is a definition.)
2130 
2131     // If either declaration only contains 'alignas(0)' specifiers, then it
2132     // specifies the natural alignment for the type.
2133     if (OldAlign == 0 || NewAlign == 0) {
2134       QualType Ty;
2135       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2136         Ty = VD->getType();
2137       else
2138         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2139 
2140       if (OldAlign == 0)
2141         OldAlign = S.Context.getTypeAlign(Ty);
2142       if (NewAlign == 0)
2143         NewAlign = S.Context.getTypeAlign(Ty);
2144     }
2145 
2146     if (OldAlign != NewAlign) {
2147       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2148         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2149         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2150       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2151     }
2152   }
2153 
2154   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2155     // C++11 [dcl.align]p6:
2156     //   if any declaration of an entity has an alignment-specifier,
2157     //   every defining declaration of that entity shall specify an
2158     //   equivalent alignment.
2159     // C11 6.7.5/7:
2160     //   If the definition of an object does not have an alignment
2161     //   specifier, any other declaration of that object shall also
2162     //   have no alignment specifier.
2163     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2164       << OldAlignasAttr;
2165     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2166       << OldAlignasAttr;
2167   }
2168 
2169   bool AnyAdded = false;
2170 
2171   // Ensure we have an attribute representing the strictest alignment.
2172   if (OldAlign > NewAlign) {
2173     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2174     Clone->setInherited(true);
2175     New->addAttr(Clone);
2176     AnyAdded = true;
2177   }
2178 
2179   // Ensure we have an alignas attribute if the old declaration had one.
2180   if (OldAlignasAttr && !NewAlignasAttr &&
2181       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2182     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2183     Clone->setInherited(true);
2184     New->addAttr(Clone);
2185     AnyAdded = true;
2186   }
2187 
2188   return AnyAdded;
2189 }
2190 
2191 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2192                                const InheritableAttr *Attr,
2193                                Sema::AvailabilityMergeKind AMK) {
2194   InheritableAttr *NewAttr = nullptr;
2195   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2196   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2197     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2198                                       AA->getIntroduced(), AA->getDeprecated(),
2199                                       AA->getObsoleted(), AA->getUnavailable(),
2200                                       AA->getMessage(), AMK,
2201                                       AttrSpellingListIndex);
2202   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2203     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2204                                     AttrSpellingListIndex);
2205   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2206     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2207                                         AttrSpellingListIndex);
2208   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2209     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2210                                    AttrSpellingListIndex);
2211   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2212     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2213                                    AttrSpellingListIndex);
2214   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2215     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2216                                 FA->getFormatIdx(), FA->getFirstArg(),
2217                                 AttrSpellingListIndex);
2218   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2219     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2220                                  AttrSpellingListIndex);
2221   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2222     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2223                                        AttrSpellingListIndex,
2224                                        IA->getSemanticSpelling());
2225   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2226     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2227                                       &S.Context.Idents.get(AA->getSpelling()),
2228                                       AttrSpellingListIndex);
2229   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2230     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2231   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2232     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2233   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2234     NewAttr = S.mergeInternalLinkageAttr(
2235         D, InternalLinkageA->getRange(),
2236         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2237         AttrSpellingListIndex);
2238   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2239     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2240                                 &S.Context.Idents.get(CommonA->getSpelling()),
2241                                 AttrSpellingListIndex);
2242   else if (isa<AlignedAttr>(Attr))
2243     // AlignedAttrs are handled separately, because we need to handle all
2244     // such attributes on a declaration at the same time.
2245     NewAttr = nullptr;
2246   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2247            (AMK == Sema::AMK_Override ||
2248             AMK == Sema::AMK_ProtocolImplementation))
2249     NewAttr = nullptr;
2250   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2251     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2252 
2253   if (NewAttr) {
2254     NewAttr->setInherited(true);
2255     D->addAttr(NewAttr);
2256     return true;
2257   }
2258 
2259   return false;
2260 }
2261 
2262 static const Decl *getDefinition(const Decl *D) {
2263   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2264     return TD->getDefinition();
2265   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2266     const VarDecl *Def = VD->getDefinition();
2267     if (Def)
2268       return Def;
2269     return VD->getActingDefinition();
2270   }
2271   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2272     const FunctionDecl* Def;
2273     if (FD->isDefined(Def))
2274       return Def;
2275   }
2276   return nullptr;
2277 }
2278 
2279 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2280   for (const auto *Attribute : D->attrs())
2281     if (Attribute->getKind() == Kind)
2282       return true;
2283   return false;
2284 }
2285 
2286 /// checkNewAttributesAfterDef - If we already have a definition, check that
2287 /// there are no new attributes in this declaration.
2288 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2289   if (!New->hasAttrs())
2290     return;
2291 
2292   const Decl *Def = getDefinition(Old);
2293   if (!Def || Def == New)
2294     return;
2295 
2296   AttrVec &NewAttributes = New->getAttrs();
2297   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2298     const Attr *NewAttribute = NewAttributes[I];
2299 
2300     if (isa<AliasAttr>(NewAttribute)) {
2301       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2302         Sema::SkipBodyInfo SkipBody;
2303         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2304 
2305         // If we're skipping this definition, drop the "alias" attribute.
2306         if (SkipBody.ShouldSkip) {
2307           NewAttributes.erase(NewAttributes.begin() + I);
2308           --E;
2309           continue;
2310         }
2311       } else {
2312         VarDecl *VD = cast<VarDecl>(New);
2313         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2314                                 VarDecl::TentativeDefinition
2315                             ? diag::err_alias_after_tentative
2316                             : diag::err_redefinition;
2317         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2318         S.Diag(Def->getLocation(), diag::note_previous_definition);
2319         VD->setInvalidDecl();
2320       }
2321       ++I;
2322       continue;
2323     }
2324 
2325     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2326       // Tentative definitions are only interesting for the alias check above.
2327       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2328         ++I;
2329         continue;
2330       }
2331     }
2332 
2333     if (hasAttribute(Def, NewAttribute->getKind())) {
2334       ++I;
2335       continue; // regular attr merging will take care of validating this.
2336     }
2337 
2338     if (isa<C11NoReturnAttr>(NewAttribute)) {
2339       // C's _Noreturn is allowed to be added to a function after it is defined.
2340       ++I;
2341       continue;
2342     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2343       if (AA->isAlignas()) {
2344         // C++11 [dcl.align]p6:
2345         //   if any declaration of an entity has an alignment-specifier,
2346         //   every defining declaration of that entity shall specify an
2347         //   equivalent alignment.
2348         // C11 6.7.5/7:
2349         //   If the definition of an object does not have an alignment
2350         //   specifier, any other declaration of that object shall also
2351         //   have no alignment specifier.
2352         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2353           << AA;
2354         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2355           << AA;
2356         NewAttributes.erase(NewAttributes.begin() + I);
2357         --E;
2358         continue;
2359       }
2360     }
2361 
2362     S.Diag(NewAttribute->getLocation(),
2363            diag::warn_attribute_precede_definition);
2364     S.Diag(Def->getLocation(), diag::note_previous_definition);
2365     NewAttributes.erase(NewAttributes.begin() + I);
2366     --E;
2367   }
2368 }
2369 
2370 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2371 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2372                                AvailabilityMergeKind AMK) {
2373   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2374     UsedAttr *NewAttr = OldAttr->clone(Context);
2375     NewAttr->setInherited(true);
2376     New->addAttr(NewAttr);
2377   }
2378 
2379   if (!Old->hasAttrs() && !New->hasAttrs())
2380     return;
2381 
2382   // attributes declared post-definition are currently ignored
2383   checkNewAttributesAfterDef(*this, New, Old);
2384 
2385   if (!Old->hasAttrs())
2386     return;
2387 
2388   bool foundAny = New->hasAttrs();
2389 
2390   // Ensure that any moving of objects within the allocated map is done before
2391   // we process them.
2392   if (!foundAny) New->setAttrs(AttrVec());
2393 
2394   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2395     // Ignore deprecated/unavailable/availability attributes if requested.
2396     AvailabilityMergeKind LocalAMK = AMK_None;
2397     if (isa<DeprecatedAttr>(I) ||
2398         isa<UnavailableAttr>(I) ||
2399         isa<AvailabilityAttr>(I)) {
2400       switch (AMK) {
2401       case AMK_None:
2402         continue;
2403 
2404       case AMK_Redeclaration:
2405       case AMK_Override:
2406       case AMK_ProtocolImplementation:
2407         LocalAMK = AMK;
2408         break;
2409       }
2410     }
2411 
2412     // Already handled.
2413     if (isa<UsedAttr>(I))
2414       continue;
2415 
2416     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2417       foundAny = true;
2418   }
2419 
2420   if (mergeAlignedAttrs(*this, New, Old))
2421     foundAny = true;
2422 
2423   if (!foundAny) New->dropAttrs();
2424 }
2425 
2426 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2427 /// to the new one.
2428 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2429                                      const ParmVarDecl *oldDecl,
2430                                      Sema &S) {
2431   // C++11 [dcl.attr.depend]p2:
2432   //   The first declaration of a function shall specify the
2433   //   carries_dependency attribute for its declarator-id if any declaration
2434   //   of the function specifies the carries_dependency attribute.
2435   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2436   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2437     S.Diag(CDA->getLocation(),
2438            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2439     // Find the first declaration of the parameter.
2440     // FIXME: Should we build redeclaration chains for function parameters?
2441     const FunctionDecl *FirstFD =
2442       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2443     const ParmVarDecl *FirstVD =
2444       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2445     S.Diag(FirstVD->getLocation(),
2446            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2447   }
2448 
2449   if (!oldDecl->hasAttrs())
2450     return;
2451 
2452   bool foundAny = newDecl->hasAttrs();
2453 
2454   // Ensure that any moving of objects within the allocated map is
2455   // done before we process them.
2456   if (!foundAny) newDecl->setAttrs(AttrVec());
2457 
2458   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2459     if (!DeclHasAttr(newDecl, I)) {
2460       InheritableAttr *newAttr =
2461         cast<InheritableParamAttr>(I->clone(S.Context));
2462       newAttr->setInherited(true);
2463       newDecl->addAttr(newAttr);
2464       foundAny = true;
2465     }
2466   }
2467 
2468   if (!foundAny) newDecl->dropAttrs();
2469 }
2470 
2471 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2472                                 const ParmVarDecl *OldParam,
2473                                 Sema &S) {
2474   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2475     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2476       if (*Oldnullability != *Newnullability) {
2477         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2478           << DiagNullabilityKind(
2479                *Newnullability,
2480                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2481                 != 0))
2482           << DiagNullabilityKind(
2483                *Oldnullability,
2484                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2485                 != 0));
2486         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2487       }
2488     } else {
2489       QualType NewT = NewParam->getType();
2490       NewT = S.Context.getAttributedType(
2491                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2492                          NewT, NewT);
2493       NewParam->setType(NewT);
2494     }
2495   }
2496 }
2497 
2498 namespace {
2499 
2500 /// Used in MergeFunctionDecl to keep track of function parameters in
2501 /// C.
2502 struct GNUCompatibleParamWarning {
2503   ParmVarDecl *OldParm;
2504   ParmVarDecl *NewParm;
2505   QualType PromotedType;
2506 };
2507 
2508 }
2509 
2510 /// getSpecialMember - get the special member enum for a method.
2511 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2512   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2513     if (Ctor->isDefaultConstructor())
2514       return Sema::CXXDefaultConstructor;
2515 
2516     if (Ctor->isCopyConstructor())
2517       return Sema::CXXCopyConstructor;
2518 
2519     if (Ctor->isMoveConstructor())
2520       return Sema::CXXMoveConstructor;
2521   } else if (isa<CXXDestructorDecl>(MD)) {
2522     return Sema::CXXDestructor;
2523   } else if (MD->isCopyAssignmentOperator()) {
2524     return Sema::CXXCopyAssignment;
2525   } else if (MD->isMoveAssignmentOperator()) {
2526     return Sema::CXXMoveAssignment;
2527   }
2528 
2529   return Sema::CXXInvalid;
2530 }
2531 
2532 // Determine whether the previous declaration was a definition, implicit
2533 // declaration, or a declaration.
2534 template <typename T>
2535 static std::pair<diag::kind, SourceLocation>
2536 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2537   diag::kind PrevDiag;
2538   SourceLocation OldLocation = Old->getLocation();
2539   if (Old->isThisDeclarationADefinition())
2540     PrevDiag = diag::note_previous_definition;
2541   else if (Old->isImplicit()) {
2542     PrevDiag = diag::note_previous_implicit_declaration;
2543     if (OldLocation.isInvalid())
2544       OldLocation = New->getLocation();
2545   } else
2546     PrevDiag = diag::note_previous_declaration;
2547   return std::make_pair(PrevDiag, OldLocation);
2548 }
2549 
2550 /// canRedefineFunction - checks if a function can be redefined. Currently,
2551 /// only extern inline functions can be redefined, and even then only in
2552 /// GNU89 mode.
2553 static bool canRedefineFunction(const FunctionDecl *FD,
2554                                 const LangOptions& LangOpts) {
2555   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2556           !LangOpts.CPlusPlus &&
2557           FD->isInlineSpecified() &&
2558           FD->getStorageClass() == SC_Extern);
2559 }
2560 
2561 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2562   const AttributedType *AT = T->getAs<AttributedType>();
2563   while (AT && !AT->isCallingConv())
2564     AT = AT->getModifiedType()->getAs<AttributedType>();
2565   return AT;
2566 }
2567 
2568 template <typename T>
2569 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2570   const DeclContext *DC = Old->getDeclContext();
2571   if (DC->isRecord())
2572     return false;
2573 
2574   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2575   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2576     return true;
2577   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2578     return true;
2579   return false;
2580 }
2581 
2582 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2583 static bool isExternC(VarTemplateDecl *) { return false; }
2584 
2585 /// \brief Check whether a redeclaration of an entity introduced by a
2586 /// using-declaration is valid, given that we know it's not an overload
2587 /// (nor a hidden tag declaration).
2588 template<typename ExpectedDecl>
2589 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2590                                    ExpectedDecl *New) {
2591   // C++11 [basic.scope.declarative]p4:
2592   //   Given a set of declarations in a single declarative region, each of
2593   //   which specifies the same unqualified name,
2594   //   -- they shall all refer to the same entity, or all refer to functions
2595   //      and function templates; or
2596   //   -- exactly one declaration shall declare a class name or enumeration
2597   //      name that is not a typedef name and the other declarations shall all
2598   //      refer to the same variable or enumerator, or all refer to functions
2599   //      and function templates; in this case the class name or enumeration
2600   //      name is hidden (3.3.10).
2601 
2602   // C++11 [namespace.udecl]p14:
2603   //   If a function declaration in namespace scope or block scope has the
2604   //   same name and the same parameter-type-list as a function introduced
2605   //   by a using-declaration, and the declarations do not declare the same
2606   //   function, the program is ill-formed.
2607 
2608   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2609   if (Old &&
2610       !Old->getDeclContext()->getRedeclContext()->Equals(
2611           New->getDeclContext()->getRedeclContext()) &&
2612       !(isExternC(Old) && isExternC(New)))
2613     Old = nullptr;
2614 
2615   if (!Old) {
2616     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2617     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2618     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2619     return true;
2620   }
2621   return false;
2622 }
2623 
2624 /// MergeFunctionDecl - We just parsed a function 'New' from
2625 /// declarator D which has the same name and scope as a previous
2626 /// declaration 'Old'.  Figure out how to resolve this situation,
2627 /// merging decls or emitting diagnostics as appropriate.
2628 ///
2629 /// In C++, New and Old must be declarations that are not
2630 /// overloaded. Use IsOverload to determine whether New and Old are
2631 /// overloaded, and to select the Old declaration that New should be
2632 /// merged with.
2633 ///
2634 /// Returns true if there was an error, false otherwise.
2635 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2636                              Scope *S, bool MergeTypeWithOld) {
2637   // Verify the old decl was also a function.
2638   FunctionDecl *Old = OldD->getAsFunction();
2639   if (!Old) {
2640     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2641       if (New->getFriendObjectKind()) {
2642         Diag(New->getLocation(), diag::err_using_decl_friend);
2643         Diag(Shadow->getTargetDecl()->getLocation(),
2644              diag::note_using_decl_target);
2645         Diag(Shadow->getUsingDecl()->getLocation(),
2646              diag::note_using_decl) << 0;
2647         return true;
2648       }
2649 
2650       // Check whether the two declarations might declare the same function.
2651       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2652         return true;
2653       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2654     } else {
2655       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2656         << New->getDeclName();
2657       Diag(OldD->getLocation(), diag::note_previous_definition);
2658       return true;
2659     }
2660   }
2661 
2662   // If the old declaration is invalid, just give up here.
2663   if (Old->isInvalidDecl())
2664     return true;
2665 
2666   diag::kind PrevDiag;
2667   SourceLocation OldLocation;
2668   std::tie(PrevDiag, OldLocation) =
2669       getNoteDiagForInvalidRedeclaration(Old, New);
2670 
2671   // Don't complain about this if we're in GNU89 mode and the old function
2672   // is an extern inline function.
2673   // Don't complain about specializations. They are not supposed to have
2674   // storage classes.
2675   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2676       New->getStorageClass() == SC_Static &&
2677       Old->hasExternalFormalLinkage() &&
2678       !New->getTemplateSpecializationInfo() &&
2679       !canRedefineFunction(Old, getLangOpts())) {
2680     if (getLangOpts().MicrosoftExt) {
2681       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2682       Diag(OldLocation, PrevDiag);
2683     } else {
2684       Diag(New->getLocation(), diag::err_static_non_static) << New;
2685       Diag(OldLocation, PrevDiag);
2686       return true;
2687     }
2688   }
2689 
2690   if (New->hasAttr<InternalLinkageAttr>() &&
2691       !Old->hasAttr<InternalLinkageAttr>()) {
2692     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2693         << New->getDeclName();
2694     Diag(Old->getLocation(), diag::note_previous_definition);
2695     New->dropAttr<InternalLinkageAttr>();
2696   }
2697 
2698   // If a function is first declared with a calling convention, but is later
2699   // declared or defined without one, all following decls assume the calling
2700   // convention of the first.
2701   //
2702   // It's OK if a function is first declared without a calling convention,
2703   // but is later declared or defined with the default calling convention.
2704   //
2705   // To test if either decl has an explicit calling convention, we look for
2706   // AttributedType sugar nodes on the type as written.  If they are missing or
2707   // were canonicalized away, we assume the calling convention was implicit.
2708   //
2709   // Note also that we DO NOT return at this point, because we still have
2710   // other tests to run.
2711   QualType OldQType = Context.getCanonicalType(Old->getType());
2712   QualType NewQType = Context.getCanonicalType(New->getType());
2713   const FunctionType *OldType = cast<FunctionType>(OldQType);
2714   const FunctionType *NewType = cast<FunctionType>(NewQType);
2715   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2716   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2717   bool RequiresAdjustment = false;
2718 
2719   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2720     FunctionDecl *First = Old->getFirstDecl();
2721     const FunctionType *FT =
2722         First->getType().getCanonicalType()->castAs<FunctionType>();
2723     FunctionType::ExtInfo FI = FT->getExtInfo();
2724     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2725     if (!NewCCExplicit) {
2726       // Inherit the CC from the previous declaration if it was specified
2727       // there but not here.
2728       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2729       RequiresAdjustment = true;
2730     } else {
2731       // Calling conventions aren't compatible, so complain.
2732       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2733       Diag(New->getLocation(), diag::err_cconv_change)
2734         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2735         << !FirstCCExplicit
2736         << (!FirstCCExplicit ? "" :
2737             FunctionType::getNameForCallConv(FI.getCC()));
2738 
2739       // Put the note on the first decl, since it is the one that matters.
2740       Diag(First->getLocation(), diag::note_previous_declaration);
2741       return true;
2742     }
2743   }
2744 
2745   // FIXME: diagnose the other way around?
2746   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2747     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2748     RequiresAdjustment = true;
2749   }
2750 
2751   // Merge regparm attribute.
2752   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2753       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2754     if (NewTypeInfo.getHasRegParm()) {
2755       Diag(New->getLocation(), diag::err_regparm_mismatch)
2756         << NewType->getRegParmType()
2757         << OldType->getRegParmType();
2758       Diag(OldLocation, diag::note_previous_declaration);
2759       return true;
2760     }
2761 
2762     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2763     RequiresAdjustment = true;
2764   }
2765 
2766   // Merge ns_returns_retained attribute.
2767   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2768     if (NewTypeInfo.getProducesResult()) {
2769       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2770       Diag(OldLocation, diag::note_previous_declaration);
2771       return true;
2772     }
2773 
2774     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2775     RequiresAdjustment = true;
2776   }
2777 
2778   if (RequiresAdjustment) {
2779     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2780     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2781     New->setType(QualType(AdjustedType, 0));
2782     NewQType = Context.getCanonicalType(New->getType());
2783     NewType = cast<FunctionType>(NewQType);
2784   }
2785 
2786   // If this redeclaration makes the function inline, we may need to add it to
2787   // UndefinedButUsed.
2788   if (!Old->isInlined() && New->isInlined() &&
2789       !New->hasAttr<GNUInlineAttr>() &&
2790       !getLangOpts().GNUInline &&
2791       Old->isUsed(false) &&
2792       !Old->isDefined() && !New->isThisDeclarationADefinition())
2793     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2794                                            SourceLocation()));
2795 
2796   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2797   // about it.
2798   if (New->hasAttr<GNUInlineAttr>() &&
2799       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2800     UndefinedButUsed.erase(Old->getCanonicalDecl());
2801   }
2802 
2803   if (getLangOpts().CPlusPlus) {
2804     // (C++98 13.1p2):
2805     //   Certain function declarations cannot be overloaded:
2806     //     -- Function declarations that differ only in the return type
2807     //        cannot be overloaded.
2808 
2809     // Go back to the type source info to compare the declared return types,
2810     // per C++1y [dcl.type.auto]p13:
2811     //   Redeclarations or specializations of a function or function template
2812     //   with a declared return type that uses a placeholder type shall also
2813     //   use that placeholder, not a deduced type.
2814     QualType OldDeclaredReturnType =
2815         (Old->getTypeSourceInfo()
2816              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2817              : OldType)->getReturnType();
2818     QualType NewDeclaredReturnType =
2819         (New->getTypeSourceInfo()
2820              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2821              : NewType)->getReturnType();
2822     QualType ResQT;
2823     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2824         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2825           New->isLocalExternDecl())) {
2826       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2827           OldDeclaredReturnType->isObjCObjectPointerType())
2828         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2829       if (ResQT.isNull()) {
2830         if (New->isCXXClassMember() && New->isOutOfLine())
2831           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2832               << New << New->getReturnTypeSourceRange();
2833         else
2834           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2835               << New->getReturnTypeSourceRange();
2836         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2837                                     << Old->getReturnTypeSourceRange();
2838         return true;
2839       }
2840       else
2841         NewQType = ResQT;
2842     }
2843 
2844     QualType OldReturnType = OldType->getReturnType();
2845     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2846     if (OldReturnType != NewReturnType) {
2847       // If this function has a deduced return type and has already been
2848       // defined, copy the deduced value from the old declaration.
2849       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2850       if (OldAT && OldAT->isDeduced()) {
2851         New->setType(
2852             SubstAutoType(New->getType(),
2853                           OldAT->isDependentType() ? Context.DependentTy
2854                                                    : OldAT->getDeducedType()));
2855         NewQType = Context.getCanonicalType(
2856             SubstAutoType(NewQType,
2857                           OldAT->isDependentType() ? Context.DependentTy
2858                                                    : OldAT->getDeducedType()));
2859       }
2860     }
2861 
2862     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2863     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2864     if (OldMethod && NewMethod) {
2865       // Preserve triviality.
2866       NewMethod->setTrivial(OldMethod->isTrivial());
2867 
2868       // MSVC allows explicit template specialization at class scope:
2869       // 2 CXXMethodDecls referring to the same function will be injected.
2870       // We don't want a redeclaration error.
2871       bool IsClassScopeExplicitSpecialization =
2872                               OldMethod->isFunctionTemplateSpecialization() &&
2873                               NewMethod->isFunctionTemplateSpecialization();
2874       bool isFriend = NewMethod->getFriendObjectKind();
2875 
2876       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2877           !IsClassScopeExplicitSpecialization) {
2878         //    -- Member function declarations with the same name and the
2879         //       same parameter types cannot be overloaded if any of them
2880         //       is a static member function declaration.
2881         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2882           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2883           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2884           return true;
2885         }
2886 
2887         // C++ [class.mem]p1:
2888         //   [...] A member shall not be declared twice in the
2889         //   member-specification, except that a nested class or member
2890         //   class template can be declared and then later defined.
2891         if (ActiveTemplateInstantiations.empty()) {
2892           unsigned NewDiag;
2893           if (isa<CXXConstructorDecl>(OldMethod))
2894             NewDiag = diag::err_constructor_redeclared;
2895           else if (isa<CXXDestructorDecl>(NewMethod))
2896             NewDiag = diag::err_destructor_redeclared;
2897           else if (isa<CXXConversionDecl>(NewMethod))
2898             NewDiag = diag::err_conv_function_redeclared;
2899           else
2900             NewDiag = diag::err_member_redeclared;
2901 
2902           Diag(New->getLocation(), NewDiag);
2903         } else {
2904           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2905             << New << New->getType();
2906         }
2907         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2908         return true;
2909 
2910       // Complain if this is an explicit declaration of a special
2911       // member that was initially declared implicitly.
2912       //
2913       // As an exception, it's okay to befriend such methods in order
2914       // to permit the implicit constructor/destructor/operator calls.
2915       } else if (OldMethod->isImplicit()) {
2916         if (isFriend) {
2917           NewMethod->setImplicit();
2918         } else {
2919           Diag(NewMethod->getLocation(),
2920                diag::err_definition_of_implicitly_declared_member)
2921             << New << getSpecialMember(OldMethod);
2922           return true;
2923         }
2924       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2925         Diag(NewMethod->getLocation(),
2926              diag::err_definition_of_explicitly_defaulted_member)
2927           << getSpecialMember(OldMethod);
2928         return true;
2929       }
2930     }
2931 
2932     // C++11 [dcl.attr.noreturn]p1:
2933     //   The first declaration of a function shall specify the noreturn
2934     //   attribute if any declaration of that function specifies the noreturn
2935     //   attribute.
2936     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2937     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2938       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2939       Diag(Old->getFirstDecl()->getLocation(),
2940            diag::note_noreturn_missing_first_decl);
2941     }
2942 
2943     // C++11 [dcl.attr.depend]p2:
2944     //   The first declaration of a function shall specify the
2945     //   carries_dependency attribute for its declarator-id if any declaration
2946     //   of the function specifies the carries_dependency attribute.
2947     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2948     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2949       Diag(CDA->getLocation(),
2950            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2951       Diag(Old->getFirstDecl()->getLocation(),
2952            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2953     }
2954 
2955     // (C++98 8.3.5p3):
2956     //   All declarations for a function shall agree exactly in both the
2957     //   return type and the parameter-type-list.
2958     // We also want to respect all the extended bits except noreturn.
2959 
2960     // noreturn should now match unless the old type info didn't have it.
2961     QualType OldQTypeForComparison = OldQType;
2962     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2963       assert(OldQType == QualType(OldType, 0));
2964       const FunctionType *OldTypeForComparison
2965         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2966       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2967       assert(OldQTypeForComparison.isCanonical());
2968     }
2969 
2970     if (haveIncompatibleLanguageLinkages(Old, New)) {
2971       // As a special case, retain the language linkage from previous
2972       // declarations of a friend function as an extension.
2973       //
2974       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2975       // and is useful because there's otherwise no way to specify language
2976       // linkage within class scope.
2977       //
2978       // Check cautiously as the friend object kind isn't yet complete.
2979       if (New->getFriendObjectKind() != Decl::FOK_None) {
2980         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2981         Diag(OldLocation, PrevDiag);
2982       } else {
2983         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2984         Diag(OldLocation, PrevDiag);
2985         return true;
2986       }
2987     }
2988 
2989     if (OldQTypeForComparison == NewQType)
2990       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2991 
2992     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2993         New->isLocalExternDecl()) {
2994       // It's OK if we couldn't merge types for a local function declaraton
2995       // if either the old or new type is dependent. We'll merge the types
2996       // when we instantiate the function.
2997       return false;
2998     }
2999 
3000     // Fall through for conflicting redeclarations and redefinitions.
3001   }
3002 
3003   // C: Function types need to be compatible, not identical. This handles
3004   // duplicate function decls like "void f(int); void f(enum X);" properly.
3005   if (!getLangOpts().CPlusPlus &&
3006       Context.typesAreCompatible(OldQType, NewQType)) {
3007     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3008     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3009     const FunctionProtoType *OldProto = nullptr;
3010     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3011         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3012       // The old declaration provided a function prototype, but the
3013       // new declaration does not. Merge in the prototype.
3014       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3015       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3016       NewQType =
3017           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3018                                   OldProto->getExtProtoInfo());
3019       New->setType(NewQType);
3020       New->setHasInheritedPrototype();
3021 
3022       // Synthesize parameters with the same types.
3023       SmallVector<ParmVarDecl*, 16> Params;
3024       for (const auto &ParamType : OldProto->param_types()) {
3025         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3026                                                  SourceLocation(), nullptr,
3027                                                  ParamType, /*TInfo=*/nullptr,
3028                                                  SC_None, nullptr);
3029         Param->setScopeInfo(0, Params.size());
3030         Param->setImplicit();
3031         Params.push_back(Param);
3032       }
3033 
3034       New->setParams(Params);
3035     }
3036 
3037     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3038   }
3039 
3040   // GNU C permits a K&R definition to follow a prototype declaration
3041   // if the declared types of the parameters in the K&R definition
3042   // match the types in the prototype declaration, even when the
3043   // promoted types of the parameters from the K&R definition differ
3044   // from the types in the prototype. GCC then keeps the types from
3045   // the prototype.
3046   //
3047   // If a variadic prototype is followed by a non-variadic K&R definition,
3048   // the K&R definition becomes variadic.  This is sort of an edge case, but
3049   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3050   // C99 6.9.1p8.
3051   if (!getLangOpts().CPlusPlus &&
3052       Old->hasPrototype() && !New->hasPrototype() &&
3053       New->getType()->getAs<FunctionProtoType>() &&
3054       Old->getNumParams() == New->getNumParams()) {
3055     SmallVector<QualType, 16> ArgTypes;
3056     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3057     const FunctionProtoType *OldProto
3058       = Old->getType()->getAs<FunctionProtoType>();
3059     const FunctionProtoType *NewProto
3060       = New->getType()->getAs<FunctionProtoType>();
3061 
3062     // Determine whether this is the GNU C extension.
3063     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3064                                                NewProto->getReturnType());
3065     bool LooseCompatible = !MergedReturn.isNull();
3066     for (unsigned Idx = 0, End = Old->getNumParams();
3067          LooseCompatible && Idx != End; ++Idx) {
3068       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3069       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3070       if (Context.typesAreCompatible(OldParm->getType(),
3071                                      NewProto->getParamType(Idx))) {
3072         ArgTypes.push_back(NewParm->getType());
3073       } else if (Context.typesAreCompatible(OldParm->getType(),
3074                                             NewParm->getType(),
3075                                             /*CompareUnqualified=*/true)) {
3076         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3077                                            NewProto->getParamType(Idx) };
3078         Warnings.push_back(Warn);
3079         ArgTypes.push_back(NewParm->getType());
3080       } else
3081         LooseCompatible = false;
3082     }
3083 
3084     if (LooseCompatible) {
3085       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3086         Diag(Warnings[Warn].NewParm->getLocation(),
3087              diag::ext_param_promoted_not_compatible_with_prototype)
3088           << Warnings[Warn].PromotedType
3089           << Warnings[Warn].OldParm->getType();
3090         if (Warnings[Warn].OldParm->getLocation().isValid())
3091           Diag(Warnings[Warn].OldParm->getLocation(),
3092                diag::note_previous_declaration);
3093       }
3094 
3095       if (MergeTypeWithOld)
3096         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3097                                              OldProto->getExtProtoInfo()));
3098       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3099     }
3100 
3101     // Fall through to diagnose conflicting types.
3102   }
3103 
3104   // A function that has already been declared has been redeclared or
3105   // defined with a different type; show an appropriate diagnostic.
3106 
3107   // If the previous declaration was an implicitly-generated builtin
3108   // declaration, then at the very least we should use a specialized note.
3109   unsigned BuiltinID;
3110   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3111     // If it's actually a library-defined builtin function like 'malloc'
3112     // or 'printf', just warn about the incompatible redeclaration.
3113     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3114       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3115       Diag(OldLocation, diag::note_previous_builtin_declaration)
3116         << Old << Old->getType();
3117 
3118       // If this is a global redeclaration, just forget hereafter
3119       // about the "builtin-ness" of the function.
3120       //
3121       // Doing this for local extern declarations is problematic.  If
3122       // the builtin declaration remains visible, a second invalid
3123       // local declaration will produce a hard error; if it doesn't
3124       // remain visible, a single bogus local redeclaration (which is
3125       // actually only a warning) could break all the downstream code.
3126       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3127         New->getIdentifier()->revertBuiltin();
3128 
3129       return false;
3130     }
3131 
3132     PrevDiag = diag::note_previous_builtin_declaration;
3133   }
3134 
3135   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3136   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3137   return true;
3138 }
3139 
3140 /// \brief Completes the merge of two function declarations that are
3141 /// known to be compatible.
3142 ///
3143 /// This routine handles the merging of attributes and other
3144 /// properties of function declarations from the old declaration to
3145 /// the new declaration, once we know that New is in fact a
3146 /// redeclaration of Old.
3147 ///
3148 /// \returns false
3149 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3150                                         Scope *S, bool MergeTypeWithOld) {
3151   // Merge the attributes
3152   mergeDeclAttributes(New, Old);
3153 
3154   // Merge "pure" flag.
3155   if (Old->isPure())
3156     New->setPure();
3157 
3158   // Merge "used" flag.
3159   if (Old->getMostRecentDecl()->isUsed(false))
3160     New->setIsUsed();
3161 
3162   // Merge attributes from the parameters.  These can mismatch with K&R
3163   // declarations.
3164   if (New->getNumParams() == Old->getNumParams())
3165       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3166         ParmVarDecl *NewParam = New->getParamDecl(i);
3167         ParmVarDecl *OldParam = Old->getParamDecl(i);
3168         mergeParamDeclAttributes(NewParam, OldParam, *this);
3169         mergeParamDeclTypes(NewParam, OldParam, *this);
3170       }
3171 
3172   if (getLangOpts().CPlusPlus)
3173     return MergeCXXFunctionDecl(New, Old, S);
3174 
3175   // Merge the function types so the we get the composite types for the return
3176   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3177   // was visible.
3178   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3179   if (!Merged.isNull() && MergeTypeWithOld)
3180     New->setType(Merged);
3181 
3182   return false;
3183 }
3184 
3185 
3186 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3187                                 ObjCMethodDecl *oldMethod) {
3188 
3189   // Merge the attributes, including deprecated/unavailable
3190   AvailabilityMergeKind MergeKind =
3191     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3192       ? AMK_ProtocolImplementation
3193       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3194                                                        : AMK_Override;
3195 
3196   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3197 
3198   // Merge attributes from the parameters.
3199   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3200                                        oe = oldMethod->param_end();
3201   for (ObjCMethodDecl::param_iterator
3202          ni = newMethod->param_begin(), ne = newMethod->param_end();
3203        ni != ne && oi != oe; ++ni, ++oi)
3204     mergeParamDeclAttributes(*ni, *oi, *this);
3205 
3206   CheckObjCMethodOverride(newMethod, oldMethod);
3207 }
3208 
3209 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3210 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3211 /// emitting diagnostics as appropriate.
3212 ///
3213 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3214 /// to here in AddInitializerToDecl. We can't check them before the initializer
3215 /// is attached.
3216 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3217                              bool MergeTypeWithOld) {
3218   if (New->isInvalidDecl() || Old->isInvalidDecl())
3219     return;
3220 
3221   QualType MergedT;
3222   if (getLangOpts().CPlusPlus) {
3223     if (New->getType()->isUndeducedType()) {
3224       // We don't know what the new type is until the initializer is attached.
3225       return;
3226     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3227       // These could still be something that needs exception specs checked.
3228       return MergeVarDeclExceptionSpecs(New, Old);
3229     }
3230     // C++ [basic.link]p10:
3231     //   [...] the types specified by all declarations referring to a given
3232     //   object or function shall be identical, except that declarations for an
3233     //   array object can specify array types that differ by the presence or
3234     //   absence of a major array bound (8.3.4).
3235     else if (Old->getType()->isIncompleteArrayType() &&
3236              New->getType()->isArrayType()) {
3237       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3238       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3239       if (Context.hasSameType(OldArray->getElementType(),
3240                               NewArray->getElementType()))
3241         MergedT = New->getType();
3242     } else if (Old->getType()->isArrayType() &&
3243                New->getType()->isIncompleteArrayType()) {
3244       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3245       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3246       if (Context.hasSameType(OldArray->getElementType(),
3247                               NewArray->getElementType()))
3248         MergedT = Old->getType();
3249     } else if (New->getType()->isObjCObjectPointerType() &&
3250                Old->getType()->isObjCObjectPointerType()) {
3251       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3252                                               Old->getType());
3253     }
3254   } else {
3255     // C 6.2.7p2:
3256     //   All declarations that refer to the same object or function shall have
3257     //   compatible type.
3258     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3259   }
3260   if (MergedT.isNull()) {
3261     // It's OK if we couldn't merge types if either type is dependent, for a
3262     // block-scope variable. In other cases (static data members of class
3263     // templates, variable templates, ...), we require the types to be
3264     // equivalent.
3265     // FIXME: The C++ standard doesn't say anything about this.
3266     if ((New->getType()->isDependentType() ||
3267          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3268       // If the old type was dependent, we can't merge with it, so the new type
3269       // becomes dependent for now. We'll reproduce the original type when we
3270       // instantiate the TypeSourceInfo for the variable.
3271       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3272         New->setType(Context.DependentTy);
3273       return;
3274     }
3275 
3276     // FIXME: Even if this merging succeeds, some other non-visible declaration
3277     // of this variable might have an incompatible type. For instance:
3278     //
3279     //   extern int arr[];
3280     //   void f() { extern int arr[2]; }
3281     //   void g() { extern int arr[3]; }
3282     //
3283     // Neither C nor C++ requires a diagnostic for this, but we should still try
3284     // to diagnose it.
3285     Diag(New->getLocation(), New->isThisDeclarationADefinition()
3286                                  ? diag::err_redefinition_different_type
3287                                  : diag::err_redeclaration_different_type)
3288         << New->getDeclName() << New->getType() << Old->getType();
3289 
3290     diag::kind PrevDiag;
3291     SourceLocation OldLocation;
3292     std::tie(PrevDiag, OldLocation) =
3293         getNoteDiagForInvalidRedeclaration(Old, New);
3294     Diag(OldLocation, PrevDiag);
3295     return New->setInvalidDecl();
3296   }
3297 
3298   // Don't actually update the type on the new declaration if the old
3299   // declaration was an extern declaration in a different scope.
3300   if (MergeTypeWithOld)
3301     New->setType(MergedT);
3302 }
3303 
3304 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3305                                   LookupResult &Previous) {
3306   // C11 6.2.7p4:
3307   //   For an identifier with internal or external linkage declared
3308   //   in a scope in which a prior declaration of that identifier is
3309   //   visible, if the prior declaration specifies internal or
3310   //   external linkage, the type of the identifier at the later
3311   //   declaration becomes the composite type.
3312   //
3313   // If the variable isn't visible, we do not merge with its type.
3314   if (Previous.isShadowed())
3315     return false;
3316 
3317   if (S.getLangOpts().CPlusPlus) {
3318     // C++11 [dcl.array]p3:
3319     //   If there is a preceding declaration of the entity in the same
3320     //   scope in which the bound was specified, an omitted array bound
3321     //   is taken to be the same as in that earlier declaration.
3322     return NewVD->isPreviousDeclInSameBlockScope() ||
3323            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3324             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3325   } else {
3326     // If the old declaration was function-local, don't merge with its
3327     // type unless we're in the same function.
3328     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3329            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3330   }
3331 }
3332 
3333 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3334 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3335 /// situation, merging decls or emitting diagnostics as appropriate.
3336 ///
3337 /// Tentative definition rules (C99 6.9.2p2) are checked by
3338 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3339 /// definitions here, since the initializer hasn't been attached.
3340 ///
3341 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3342   // If the new decl is already invalid, don't do any other checking.
3343   if (New->isInvalidDecl())
3344     return;
3345 
3346   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3347     return;
3348 
3349   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3350 
3351   // Verify the old decl was also a variable or variable template.
3352   VarDecl *Old = nullptr;
3353   VarTemplateDecl *OldTemplate = nullptr;
3354   if (Previous.isSingleResult()) {
3355     if (NewTemplate) {
3356       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3357       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3358 
3359       if (auto *Shadow =
3360               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3361         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3362           return New->setInvalidDecl();
3363     } else {
3364       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3365 
3366       if (auto *Shadow =
3367               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3368         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3369           return New->setInvalidDecl();
3370     }
3371   }
3372   if (!Old) {
3373     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3374       << New->getDeclName();
3375     Diag(Previous.getRepresentativeDecl()->getLocation(),
3376          diag::note_previous_definition);
3377     return New->setInvalidDecl();
3378   }
3379 
3380   // Ensure the template parameters are compatible.
3381   if (NewTemplate &&
3382       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3383                                       OldTemplate->getTemplateParameters(),
3384                                       /*Complain=*/true, TPL_TemplateMatch))
3385     return New->setInvalidDecl();
3386 
3387   // C++ [class.mem]p1:
3388   //   A member shall not be declared twice in the member-specification [...]
3389   //
3390   // Here, we need only consider static data members.
3391   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3392     Diag(New->getLocation(), diag::err_duplicate_member)
3393       << New->getIdentifier();
3394     Diag(Old->getLocation(), diag::note_previous_declaration);
3395     New->setInvalidDecl();
3396   }
3397 
3398   mergeDeclAttributes(New, Old);
3399   // Warn if an already-declared variable is made a weak_import in a subsequent
3400   // declaration
3401   if (New->hasAttr<WeakImportAttr>() &&
3402       Old->getStorageClass() == SC_None &&
3403       !Old->hasAttr<WeakImportAttr>()) {
3404     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3405     Diag(Old->getLocation(), diag::note_previous_definition);
3406     // Remove weak_import attribute on new declaration.
3407     New->dropAttr<WeakImportAttr>();
3408   }
3409 
3410   if (New->hasAttr<InternalLinkageAttr>() &&
3411       !Old->hasAttr<InternalLinkageAttr>()) {
3412     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3413         << New->getDeclName();
3414     Diag(Old->getLocation(), diag::note_previous_definition);
3415     New->dropAttr<InternalLinkageAttr>();
3416   }
3417 
3418   // Merge the types.
3419   VarDecl *MostRecent = Old->getMostRecentDecl();
3420   if (MostRecent != Old) {
3421     MergeVarDeclTypes(New, MostRecent,
3422                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3423     if (New->isInvalidDecl())
3424       return;
3425   }
3426 
3427   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3428   if (New->isInvalidDecl())
3429     return;
3430 
3431   diag::kind PrevDiag;
3432   SourceLocation OldLocation;
3433   std::tie(PrevDiag, OldLocation) =
3434       getNoteDiagForInvalidRedeclaration(Old, New);
3435 
3436   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3437   if (New->getStorageClass() == SC_Static &&
3438       !New->isStaticDataMember() &&
3439       Old->hasExternalFormalLinkage()) {
3440     if (getLangOpts().MicrosoftExt) {
3441       Diag(New->getLocation(), diag::ext_static_non_static)
3442           << New->getDeclName();
3443       Diag(OldLocation, PrevDiag);
3444     } else {
3445       Diag(New->getLocation(), diag::err_static_non_static)
3446           << New->getDeclName();
3447       Diag(OldLocation, PrevDiag);
3448       return New->setInvalidDecl();
3449     }
3450   }
3451   // C99 6.2.2p4:
3452   //   For an identifier declared with the storage-class specifier
3453   //   extern in a scope in which a prior declaration of that
3454   //   identifier is visible,23) if the prior declaration specifies
3455   //   internal or external linkage, the linkage of the identifier at
3456   //   the later declaration is the same as the linkage specified at
3457   //   the prior declaration. If no prior declaration is visible, or
3458   //   if the prior declaration specifies no linkage, then the
3459   //   identifier has external linkage.
3460   if (New->hasExternalStorage() && Old->hasLinkage())
3461     /* Okay */;
3462   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3463            !New->isStaticDataMember() &&
3464            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3465     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3466     Diag(OldLocation, PrevDiag);
3467     return New->setInvalidDecl();
3468   }
3469 
3470   // Check if extern is followed by non-extern and vice-versa.
3471   if (New->hasExternalStorage() &&
3472       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3473     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3474     Diag(OldLocation, PrevDiag);
3475     return New->setInvalidDecl();
3476   }
3477   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3478       !New->hasExternalStorage()) {
3479     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3480     Diag(OldLocation, PrevDiag);
3481     return New->setInvalidDecl();
3482   }
3483 
3484   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3485 
3486   // FIXME: The test for external storage here seems wrong? We still
3487   // need to check for mismatches.
3488   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3489       // Don't complain about out-of-line definitions of static members.
3490       !(Old->getLexicalDeclContext()->isRecord() &&
3491         !New->getLexicalDeclContext()->isRecord())) {
3492     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3493     Diag(OldLocation, PrevDiag);
3494     return New->setInvalidDecl();
3495   }
3496 
3497   if (New->getTLSKind() != Old->getTLSKind()) {
3498     if (!Old->getTLSKind()) {
3499       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3500       Diag(OldLocation, PrevDiag);
3501     } else if (!New->getTLSKind()) {
3502       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3503       Diag(OldLocation, PrevDiag);
3504     } else {
3505       // Do not allow redeclaration to change the variable between requiring
3506       // static and dynamic initialization.
3507       // FIXME: GCC allows this, but uses the TLS keyword on the first
3508       // declaration to determine the kind. Do we need to be compatible here?
3509       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3510         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3511       Diag(OldLocation, PrevDiag);
3512     }
3513   }
3514 
3515   // C++ doesn't have tentative definitions, so go right ahead and check here.
3516   VarDecl *Def;
3517   if (getLangOpts().CPlusPlus &&
3518       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3519       (Def = Old->getDefinition())) {
3520     NamedDecl *Hidden = nullptr;
3521     if (!hasVisibleDefinition(Def, &Hidden) &&
3522         (New->getFormalLinkage() == InternalLinkage ||
3523          New->getDescribedVarTemplate() ||
3524          New->getNumTemplateParameterLists() ||
3525          New->getDeclContext()->isDependentContext())) {
3526       // The previous definition is hidden, and multiple definitions are
3527       // permitted (in separate TUs). Form another definition of it.
3528     } else {
3529       Diag(New->getLocation(), diag::err_redefinition) << New;
3530       Diag(Def->getLocation(), diag::note_previous_definition);
3531       New->setInvalidDecl();
3532       return;
3533     }
3534   }
3535 
3536   if (haveIncompatibleLanguageLinkages(Old, New)) {
3537     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3538     Diag(OldLocation, PrevDiag);
3539     New->setInvalidDecl();
3540     return;
3541   }
3542 
3543   // Merge "used" flag.
3544   if (Old->getMostRecentDecl()->isUsed(false))
3545     New->setIsUsed();
3546 
3547   // Keep a chain of previous declarations.
3548   New->setPreviousDecl(Old);
3549   if (NewTemplate)
3550     NewTemplate->setPreviousDecl(OldTemplate);
3551 
3552   // Inherit access appropriately.
3553   New->setAccess(Old->getAccess());
3554   if (NewTemplate)
3555     NewTemplate->setAccess(New->getAccess());
3556 }
3557 
3558 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3559 /// no declarator (e.g. "struct foo;") is parsed.
3560 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3561                                        DeclSpec &DS) {
3562   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3563 }
3564 
3565 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3566 // disambiguate entities defined in different scopes.
3567 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3568 // compatibility.
3569 // We will pick our mangling number depending on which version of MSVC is being
3570 // targeted.
3571 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3572   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3573              ? S->getMSCurManglingNumber()
3574              : S->getMSLastManglingNumber();
3575 }
3576 
3577 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3578   if (!Context.getLangOpts().CPlusPlus)
3579     return;
3580 
3581   if (isa<CXXRecordDecl>(Tag->getParent())) {
3582     // If this tag is the direct child of a class, number it if
3583     // it is anonymous.
3584     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3585       return;
3586     MangleNumberingContext &MCtx =
3587         Context.getManglingNumberContext(Tag->getParent());
3588     Context.setManglingNumber(
3589         Tag, MCtx.getManglingNumber(
3590                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3591     return;
3592   }
3593 
3594   // If this tag isn't a direct child of a class, number it if it is local.
3595   Decl *ManglingContextDecl;
3596   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3597           Tag->getDeclContext(), ManglingContextDecl)) {
3598     Context.setManglingNumber(
3599         Tag, MCtx->getManglingNumber(
3600                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3601   }
3602 }
3603 
3604 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3605                                         TypedefNameDecl *NewTD) {
3606   if (TagFromDeclSpec->isInvalidDecl())
3607     return;
3608 
3609   // Do nothing if the tag already has a name for linkage purposes.
3610   if (TagFromDeclSpec->hasNameForLinkage())
3611     return;
3612 
3613   // A well-formed anonymous tag must always be a TUK_Definition.
3614   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3615 
3616   // The type must match the tag exactly;  no qualifiers allowed.
3617   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3618                            Context.getTagDeclType(TagFromDeclSpec))) {
3619     if (getLangOpts().CPlusPlus)
3620       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3621     return;
3622   }
3623 
3624   // If we've already computed linkage for the anonymous tag, then
3625   // adding a typedef name for the anonymous decl can change that
3626   // linkage, which might be a serious problem.  Diagnose this as
3627   // unsupported and ignore the typedef name.  TODO: we should
3628   // pursue this as a language defect and establish a formal rule
3629   // for how to handle it.
3630   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3631     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3632 
3633     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3634     tagLoc = getLocForEndOfToken(tagLoc);
3635 
3636     llvm::SmallString<40> textToInsert;
3637     textToInsert += ' ';
3638     textToInsert += NewTD->getIdentifier()->getName();
3639     Diag(tagLoc, diag::note_typedef_changes_linkage)
3640         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3641     return;
3642   }
3643 
3644   // Otherwise, set this is the anon-decl typedef for the tag.
3645   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3646 }
3647 
3648 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3649   switch (T) {
3650   case DeclSpec::TST_class:
3651     return 0;
3652   case DeclSpec::TST_struct:
3653     return 1;
3654   case DeclSpec::TST_interface:
3655     return 2;
3656   case DeclSpec::TST_union:
3657     return 3;
3658   case DeclSpec::TST_enum:
3659     return 4;
3660   default:
3661     llvm_unreachable("unexpected type specifier");
3662   }
3663 }
3664 
3665 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3666 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3667 /// parameters to cope with template friend declarations.
3668 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3669                                        DeclSpec &DS,
3670                                        MultiTemplateParamsArg TemplateParams,
3671                                        bool IsExplicitInstantiation) {
3672   Decl *TagD = nullptr;
3673   TagDecl *Tag = nullptr;
3674   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3675       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3676       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3677       DS.getTypeSpecType() == DeclSpec::TST_union ||
3678       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3679     TagD = DS.getRepAsDecl();
3680 
3681     if (!TagD) // We probably had an error
3682       return nullptr;
3683 
3684     // Note that the above type specs guarantee that the
3685     // type rep is a Decl, whereas in many of the others
3686     // it's a Type.
3687     if (isa<TagDecl>(TagD))
3688       Tag = cast<TagDecl>(TagD);
3689     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3690       Tag = CTD->getTemplatedDecl();
3691   }
3692 
3693   if (Tag) {
3694     handleTagNumbering(Tag, S);
3695     Tag->setFreeStanding();
3696     if (Tag->isInvalidDecl())
3697       return Tag;
3698   }
3699 
3700   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3701     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3702     // or incomplete types shall not be restrict-qualified."
3703     if (TypeQuals & DeclSpec::TQ_restrict)
3704       Diag(DS.getRestrictSpecLoc(),
3705            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3706            << DS.getSourceRange();
3707   }
3708 
3709   if (DS.isConstexprSpecified()) {
3710     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3711     // and definitions of functions and variables.
3712     if (Tag)
3713       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3714           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3715     else
3716       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3717     // Don't emit warnings after this error.
3718     return TagD;
3719   }
3720 
3721   if (DS.isConceptSpecified()) {
3722     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3723     // either a function concept and its definition or a variable concept and
3724     // its initializer.
3725     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3726     return TagD;
3727   }
3728 
3729   DiagnoseFunctionSpecifiers(DS);
3730 
3731   if (DS.isFriendSpecified()) {
3732     // If we're dealing with a decl but not a TagDecl, assume that
3733     // whatever routines created it handled the friendship aspect.
3734     if (TagD && !Tag)
3735       return nullptr;
3736     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3737   }
3738 
3739   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3740   bool IsExplicitSpecialization =
3741     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3742   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3743       !IsExplicitInstantiation && !IsExplicitSpecialization) {
3744     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3745     // nested-name-specifier unless it is an explicit instantiation
3746     // or an explicit specialization.
3747     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3748     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3749         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3750     return nullptr;
3751   }
3752 
3753   // Track whether this decl-specifier declares anything.
3754   bool DeclaresAnything = true;
3755 
3756   // Handle anonymous struct definitions.
3757   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3758     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3759         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3760       if (getLangOpts().CPlusPlus ||
3761           Record->getDeclContext()->isRecord())
3762         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3763                                            Context.getPrintingPolicy());
3764 
3765       DeclaresAnything = false;
3766     }
3767   }
3768 
3769   // C11 6.7.2.1p2:
3770   //   A struct-declaration that does not declare an anonymous structure or
3771   //   anonymous union shall contain a struct-declarator-list.
3772   //
3773   // This rule also existed in C89 and C99; the grammar for struct-declaration
3774   // did not permit a struct-declaration without a struct-declarator-list.
3775   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3776       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3777     // Check for Microsoft C extension: anonymous struct/union member.
3778     // Handle 2 kinds of anonymous struct/union:
3779     //   struct STRUCT;
3780     //   union UNION;
3781     // and
3782     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3783     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3784     if ((Tag && Tag->getDeclName()) ||
3785         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3786       RecordDecl *Record = nullptr;
3787       if (Tag)
3788         Record = dyn_cast<RecordDecl>(Tag);
3789       else if (const RecordType *RT =
3790                    DS.getRepAsType().get()->getAsStructureType())
3791         Record = RT->getDecl();
3792       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3793         Record = UT->getDecl();
3794 
3795       if (Record && getLangOpts().MicrosoftExt) {
3796         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3797           << Record->isUnion() << DS.getSourceRange();
3798         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3799       }
3800 
3801       DeclaresAnything = false;
3802     }
3803   }
3804 
3805   // Skip all the checks below if we have a type error.
3806   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3807       (TagD && TagD->isInvalidDecl()))
3808     return TagD;
3809 
3810   if (getLangOpts().CPlusPlus &&
3811       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3812     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3813       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3814           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3815         DeclaresAnything = false;
3816 
3817   if (!DS.isMissingDeclaratorOk()) {
3818     // Customize diagnostic for a typedef missing a name.
3819     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3820       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3821         << DS.getSourceRange();
3822     else
3823       DeclaresAnything = false;
3824   }
3825 
3826   if (DS.isModulePrivateSpecified() &&
3827       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3828     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3829       << Tag->getTagKind()
3830       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3831 
3832   ActOnDocumentableDecl(TagD);
3833 
3834   // C 6.7/2:
3835   //   A declaration [...] shall declare at least a declarator [...], a tag,
3836   //   or the members of an enumeration.
3837   // C++ [dcl.dcl]p3:
3838   //   [If there are no declarators], and except for the declaration of an
3839   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3840   //   names into the program, or shall redeclare a name introduced by a
3841   //   previous declaration.
3842   if (!DeclaresAnything) {
3843     // In C, we allow this as a (popular) extension / bug. Don't bother
3844     // producing further diagnostics for redundant qualifiers after this.
3845     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3846     return TagD;
3847   }
3848 
3849   // C++ [dcl.stc]p1:
3850   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3851   //   init-declarator-list of the declaration shall not be empty.
3852   // C++ [dcl.fct.spec]p1:
3853   //   If a cv-qualifier appears in a decl-specifier-seq, the
3854   //   init-declarator-list of the declaration shall not be empty.
3855   //
3856   // Spurious qualifiers here appear to be valid in C.
3857   unsigned DiagID = diag::warn_standalone_specifier;
3858   if (getLangOpts().CPlusPlus)
3859     DiagID = diag::ext_standalone_specifier;
3860 
3861   // Note that a linkage-specification sets a storage class, but
3862   // 'extern "C" struct foo;' is actually valid and not theoretically
3863   // useless.
3864   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3865     if (SCS == DeclSpec::SCS_mutable)
3866       // Since mutable is not a viable storage class specifier in C, there is
3867       // no reason to treat it as an extension. Instead, diagnose as an error.
3868       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3869     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3870       Diag(DS.getStorageClassSpecLoc(), DiagID)
3871         << DeclSpec::getSpecifierName(SCS);
3872   }
3873 
3874   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3875     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3876       << DeclSpec::getSpecifierName(TSCS);
3877   if (DS.getTypeQualifiers()) {
3878     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3879       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3880     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3881       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3882     // Restrict is covered above.
3883     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3884       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3885   }
3886 
3887   // Warn about ignored type attributes, for example:
3888   // __attribute__((aligned)) struct A;
3889   // Attributes should be placed after tag to apply to type declaration.
3890   if (!DS.getAttributes().empty()) {
3891     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3892     if (TypeSpecType == DeclSpec::TST_class ||
3893         TypeSpecType == DeclSpec::TST_struct ||
3894         TypeSpecType == DeclSpec::TST_interface ||
3895         TypeSpecType == DeclSpec::TST_union ||
3896         TypeSpecType == DeclSpec::TST_enum) {
3897       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
3898            attrs = attrs->getNext())
3899         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3900             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
3901     }
3902   }
3903 
3904   return TagD;
3905 }
3906 
3907 /// We are trying to inject an anonymous member into the given scope;
3908 /// check if there's an existing declaration that can't be overloaded.
3909 ///
3910 /// \return true if this is a forbidden redeclaration
3911 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3912                                          Scope *S,
3913                                          DeclContext *Owner,
3914                                          DeclarationName Name,
3915                                          SourceLocation NameLoc,
3916                                          bool IsUnion) {
3917   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3918                  Sema::ForRedeclaration);
3919   if (!SemaRef.LookupName(R, S)) return false;
3920 
3921   if (R.getAsSingle<TagDecl>())
3922     return false;
3923 
3924   // Pick a representative declaration.
3925   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3926   assert(PrevDecl && "Expected a non-null Decl");
3927 
3928   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3929     return false;
3930 
3931   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
3932     << IsUnion << Name;
3933   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3934 
3935   return true;
3936 }
3937 
3938 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3939 /// anonymous struct or union AnonRecord into the owning context Owner
3940 /// and scope S. This routine will be invoked just after we realize
3941 /// that an unnamed union or struct is actually an anonymous union or
3942 /// struct, e.g.,
3943 ///
3944 /// @code
3945 /// union {
3946 ///   int i;
3947 ///   float f;
3948 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3949 ///    // f into the surrounding scope.x
3950 /// @endcode
3951 ///
3952 /// This routine is recursive, injecting the names of nested anonymous
3953 /// structs/unions into the owning context and scope as well.
3954 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3955                                          DeclContext *Owner,
3956                                          RecordDecl *AnonRecord,
3957                                          AccessSpecifier AS,
3958                                          SmallVectorImpl<NamedDecl *> &Chaining,
3959                                          bool MSAnonStruct) {
3960   bool Invalid = false;
3961 
3962   // Look every FieldDecl and IndirectFieldDecl with a name.
3963   for (auto *D : AnonRecord->decls()) {
3964     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3965         cast<NamedDecl>(D)->getDeclName()) {
3966       ValueDecl *VD = cast<ValueDecl>(D);
3967       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3968                                        VD->getLocation(),
3969                                        AnonRecord->isUnion())) {
3970         // C++ [class.union]p2:
3971         //   The names of the members of an anonymous union shall be
3972         //   distinct from the names of any other entity in the
3973         //   scope in which the anonymous union is declared.
3974         Invalid = true;
3975       } else {
3976         // C++ [class.union]p2:
3977         //   For the purpose of name lookup, after the anonymous union
3978         //   definition, the members of the anonymous union are
3979         //   considered to have been defined in the scope in which the
3980         //   anonymous union is declared.
3981         unsigned OldChainingSize = Chaining.size();
3982         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3983           Chaining.append(IF->chain_begin(), IF->chain_end());
3984         else
3985           Chaining.push_back(VD);
3986 
3987         assert(Chaining.size() >= 2);
3988         NamedDecl **NamedChain =
3989           new (SemaRef.Context)NamedDecl*[Chaining.size()];
3990         for (unsigned i = 0; i < Chaining.size(); i++)
3991           NamedChain[i] = Chaining[i];
3992 
3993         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
3994             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
3995             VD->getType(), NamedChain, Chaining.size());
3996 
3997         for (const auto *Attr : VD->attrs())
3998           IndirectField->addAttr(Attr->clone(SemaRef.Context));
3999 
4000         IndirectField->setAccess(AS);
4001         IndirectField->setImplicit();
4002         SemaRef.PushOnScopeChains(IndirectField, S);
4003 
4004         // That includes picking up the appropriate access specifier.
4005         if (AS != AS_none) IndirectField->setAccess(AS);
4006 
4007         Chaining.resize(OldChainingSize);
4008       }
4009     }
4010   }
4011 
4012   return Invalid;
4013 }
4014 
4015 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4016 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4017 /// illegal input values are mapped to SC_None.
4018 static StorageClass
4019 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4020   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4021   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4022          "Parser allowed 'typedef' as storage class VarDecl.");
4023   switch (StorageClassSpec) {
4024   case DeclSpec::SCS_unspecified:    return SC_None;
4025   case DeclSpec::SCS_extern:
4026     if (DS.isExternInLinkageSpec())
4027       return SC_None;
4028     return SC_Extern;
4029   case DeclSpec::SCS_static:         return SC_Static;
4030   case DeclSpec::SCS_auto:           return SC_Auto;
4031   case DeclSpec::SCS_register:       return SC_Register;
4032   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4033     // Illegal SCSs map to None: error reporting is up to the caller.
4034   case DeclSpec::SCS_mutable:        // Fall through.
4035   case DeclSpec::SCS_typedef:        return SC_None;
4036   }
4037   llvm_unreachable("unknown storage class specifier");
4038 }
4039 
4040 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4041   assert(Record->hasInClassInitializer());
4042 
4043   for (const auto *I : Record->decls()) {
4044     const auto *FD = dyn_cast<FieldDecl>(I);
4045     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4046       FD = IFD->getAnonField();
4047     if (FD && FD->hasInClassInitializer())
4048       return FD->getLocation();
4049   }
4050 
4051   llvm_unreachable("couldn't find in-class initializer");
4052 }
4053 
4054 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4055                                       SourceLocation DefaultInitLoc) {
4056   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4057     return;
4058 
4059   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4060   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4061 }
4062 
4063 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4064                                       CXXRecordDecl *AnonUnion) {
4065   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4066     return;
4067 
4068   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4069 }
4070 
4071 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4072 /// anonymous structure or union. Anonymous unions are a C++ feature
4073 /// (C++ [class.union]) and a C11 feature; anonymous structures
4074 /// are a C11 feature and GNU C++ extension.
4075 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4076                                         AccessSpecifier AS,
4077                                         RecordDecl *Record,
4078                                         const PrintingPolicy &Policy) {
4079   DeclContext *Owner = Record->getDeclContext();
4080 
4081   // Diagnose whether this anonymous struct/union is an extension.
4082   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4083     Diag(Record->getLocation(), diag::ext_anonymous_union);
4084   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4085     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4086   else if (!Record->isUnion() && !getLangOpts().C11)
4087     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4088 
4089   // C and C++ require different kinds of checks for anonymous
4090   // structs/unions.
4091   bool Invalid = false;
4092   if (getLangOpts().CPlusPlus) {
4093     const char *PrevSpec = nullptr;
4094     unsigned DiagID;
4095     if (Record->isUnion()) {
4096       // C++ [class.union]p6:
4097       //   Anonymous unions declared in a named namespace or in the
4098       //   global namespace shall be declared static.
4099       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4100           (isa<TranslationUnitDecl>(Owner) ||
4101            (isa<NamespaceDecl>(Owner) &&
4102             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4103         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4104           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4105 
4106         // Recover by adding 'static'.
4107         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4108                                PrevSpec, DiagID, Policy);
4109       }
4110       // C++ [class.union]p6:
4111       //   A storage class is not allowed in a declaration of an
4112       //   anonymous union in a class scope.
4113       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4114                isa<RecordDecl>(Owner)) {
4115         Diag(DS.getStorageClassSpecLoc(),
4116              diag::err_anonymous_union_with_storage_spec)
4117           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4118 
4119         // Recover by removing the storage specifier.
4120         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4121                                SourceLocation(),
4122                                PrevSpec, DiagID, Context.getPrintingPolicy());
4123       }
4124     }
4125 
4126     // Ignore const/volatile/restrict qualifiers.
4127     if (DS.getTypeQualifiers()) {
4128       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4129         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4130           << Record->isUnion() << "const"
4131           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4132       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4133         Diag(DS.getVolatileSpecLoc(),
4134              diag::ext_anonymous_struct_union_qualified)
4135           << Record->isUnion() << "volatile"
4136           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4137       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4138         Diag(DS.getRestrictSpecLoc(),
4139              diag::ext_anonymous_struct_union_qualified)
4140           << Record->isUnion() << "restrict"
4141           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4142       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4143         Diag(DS.getAtomicSpecLoc(),
4144              diag::ext_anonymous_struct_union_qualified)
4145           << Record->isUnion() << "_Atomic"
4146           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4147 
4148       DS.ClearTypeQualifiers();
4149     }
4150 
4151     // C++ [class.union]p2:
4152     //   The member-specification of an anonymous union shall only
4153     //   define non-static data members. [Note: nested types and
4154     //   functions cannot be declared within an anonymous union. ]
4155     for (auto *Mem : Record->decls()) {
4156       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4157         // C++ [class.union]p3:
4158         //   An anonymous union shall not have private or protected
4159         //   members (clause 11).
4160         assert(FD->getAccess() != AS_none);
4161         if (FD->getAccess() != AS_public) {
4162           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4163             << Record->isUnion() << (FD->getAccess() == AS_protected);
4164           Invalid = true;
4165         }
4166 
4167         // C++ [class.union]p1
4168         //   An object of a class with a non-trivial constructor, a non-trivial
4169         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4170         //   assignment operator cannot be a member of a union, nor can an
4171         //   array of such objects.
4172         if (CheckNontrivialField(FD))
4173           Invalid = true;
4174       } else if (Mem->isImplicit()) {
4175         // Any implicit members are fine.
4176       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4177         // This is a type that showed up in an
4178         // elaborated-type-specifier inside the anonymous struct or
4179         // union, but which actually declares a type outside of the
4180         // anonymous struct or union. It's okay.
4181       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4182         if (!MemRecord->isAnonymousStructOrUnion() &&
4183             MemRecord->getDeclName()) {
4184           // Visual C++ allows type definition in anonymous struct or union.
4185           if (getLangOpts().MicrosoftExt)
4186             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4187               << Record->isUnion();
4188           else {
4189             // This is a nested type declaration.
4190             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4191               << Record->isUnion();
4192             Invalid = true;
4193           }
4194         } else {
4195           // This is an anonymous type definition within another anonymous type.
4196           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4197           // not part of standard C++.
4198           Diag(MemRecord->getLocation(),
4199                diag::ext_anonymous_record_with_anonymous_type)
4200             << Record->isUnion();
4201         }
4202       } else if (isa<AccessSpecDecl>(Mem)) {
4203         // Any access specifier is fine.
4204       } else if (isa<StaticAssertDecl>(Mem)) {
4205         // In C++1z, static_assert declarations are also fine.
4206       } else {
4207         // We have something that isn't a non-static data
4208         // member. Complain about it.
4209         unsigned DK = diag::err_anonymous_record_bad_member;
4210         if (isa<TypeDecl>(Mem))
4211           DK = diag::err_anonymous_record_with_type;
4212         else if (isa<FunctionDecl>(Mem))
4213           DK = diag::err_anonymous_record_with_function;
4214         else if (isa<VarDecl>(Mem))
4215           DK = diag::err_anonymous_record_with_static;
4216 
4217         // Visual C++ allows type definition in anonymous struct or union.
4218         if (getLangOpts().MicrosoftExt &&
4219             DK == diag::err_anonymous_record_with_type)
4220           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4221             << Record->isUnion();
4222         else {
4223           Diag(Mem->getLocation(), DK) << Record->isUnion();
4224           Invalid = true;
4225         }
4226       }
4227     }
4228 
4229     // C++11 [class.union]p8 (DR1460):
4230     //   At most one variant member of a union may have a
4231     //   brace-or-equal-initializer.
4232     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4233         Owner->isRecord())
4234       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4235                                 cast<CXXRecordDecl>(Record));
4236   }
4237 
4238   if (!Record->isUnion() && !Owner->isRecord()) {
4239     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4240       << getLangOpts().CPlusPlus;
4241     Invalid = true;
4242   }
4243 
4244   // Mock up a declarator.
4245   Declarator Dc(DS, Declarator::MemberContext);
4246   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4247   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4248 
4249   // Create a declaration for this anonymous struct/union.
4250   NamedDecl *Anon = nullptr;
4251   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4252     Anon = FieldDecl::Create(Context, OwningClass,
4253                              DS.getLocStart(),
4254                              Record->getLocation(),
4255                              /*IdentifierInfo=*/nullptr,
4256                              Context.getTypeDeclType(Record),
4257                              TInfo,
4258                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4259                              /*InitStyle=*/ICIS_NoInit);
4260     Anon->setAccess(AS);
4261     if (getLangOpts().CPlusPlus)
4262       FieldCollector->Add(cast<FieldDecl>(Anon));
4263   } else {
4264     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4265     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4266     if (SCSpec == DeclSpec::SCS_mutable) {
4267       // mutable can only appear on non-static class members, so it's always
4268       // an error here
4269       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4270       Invalid = true;
4271       SC = SC_None;
4272     }
4273 
4274     Anon = VarDecl::Create(Context, Owner,
4275                            DS.getLocStart(),
4276                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4277                            Context.getTypeDeclType(Record),
4278                            TInfo, SC);
4279 
4280     // Default-initialize the implicit variable. This initialization will be
4281     // trivial in almost all cases, except if a union member has an in-class
4282     // initializer:
4283     //   union { int n = 0; };
4284     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4285   }
4286   Anon->setImplicit();
4287 
4288   // Mark this as an anonymous struct/union type.
4289   Record->setAnonymousStructOrUnion(true);
4290 
4291   // Add the anonymous struct/union object to the current
4292   // context. We'll be referencing this object when we refer to one of
4293   // its members.
4294   Owner->addDecl(Anon);
4295 
4296   // Inject the members of the anonymous struct/union into the owning
4297   // context and into the identifier resolver chain for name lookup
4298   // purposes.
4299   SmallVector<NamedDecl*, 2> Chain;
4300   Chain.push_back(Anon);
4301 
4302   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
4303                                           Chain, false))
4304     Invalid = true;
4305 
4306   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4307     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4308       Decl *ManglingContextDecl;
4309       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4310               NewVD->getDeclContext(), ManglingContextDecl)) {
4311         Context.setManglingNumber(
4312             NewVD, MCtx->getManglingNumber(
4313                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4314         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4315       }
4316     }
4317   }
4318 
4319   if (Invalid)
4320     Anon->setInvalidDecl();
4321 
4322   return Anon;
4323 }
4324 
4325 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4326 /// Microsoft C anonymous structure.
4327 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4328 /// Example:
4329 ///
4330 /// struct A { int a; };
4331 /// struct B { struct A; int b; };
4332 ///
4333 /// void foo() {
4334 ///   B var;
4335 ///   var.a = 3;
4336 /// }
4337 ///
4338 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4339                                            RecordDecl *Record) {
4340   assert(Record && "expected a record!");
4341 
4342   // Mock up a declarator.
4343   Declarator Dc(DS, Declarator::TypeNameContext);
4344   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4345   assert(TInfo && "couldn't build declarator info for anonymous struct");
4346 
4347   auto *ParentDecl = cast<RecordDecl>(CurContext);
4348   QualType RecTy = Context.getTypeDeclType(Record);
4349 
4350   // Create a declaration for this anonymous struct.
4351   NamedDecl *Anon = FieldDecl::Create(Context,
4352                              ParentDecl,
4353                              DS.getLocStart(),
4354                              DS.getLocStart(),
4355                              /*IdentifierInfo=*/nullptr,
4356                              RecTy,
4357                              TInfo,
4358                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4359                              /*InitStyle=*/ICIS_NoInit);
4360   Anon->setImplicit();
4361 
4362   // Add the anonymous struct object to the current context.
4363   CurContext->addDecl(Anon);
4364 
4365   // Inject the members of the anonymous struct into the current
4366   // context and into the identifier resolver chain for name lookup
4367   // purposes.
4368   SmallVector<NamedDecl*, 2> Chain;
4369   Chain.push_back(Anon);
4370 
4371   RecordDecl *RecordDef = Record->getDefinition();
4372   if (RequireCompleteType(Anon->getLocation(), RecTy,
4373                           diag::err_field_incomplete) ||
4374       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4375                                           AS_none, Chain, true)) {
4376     Anon->setInvalidDecl();
4377     ParentDecl->setInvalidDecl();
4378   }
4379 
4380   return Anon;
4381 }
4382 
4383 /// GetNameForDeclarator - Determine the full declaration name for the
4384 /// given Declarator.
4385 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4386   return GetNameFromUnqualifiedId(D.getName());
4387 }
4388 
4389 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4390 DeclarationNameInfo
4391 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4392   DeclarationNameInfo NameInfo;
4393   NameInfo.setLoc(Name.StartLocation);
4394 
4395   switch (Name.getKind()) {
4396 
4397   case UnqualifiedId::IK_ImplicitSelfParam:
4398   case UnqualifiedId::IK_Identifier:
4399     NameInfo.setName(Name.Identifier);
4400     NameInfo.setLoc(Name.StartLocation);
4401     return NameInfo;
4402 
4403   case UnqualifiedId::IK_OperatorFunctionId:
4404     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4405                                            Name.OperatorFunctionId.Operator));
4406     NameInfo.setLoc(Name.StartLocation);
4407     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4408       = Name.OperatorFunctionId.SymbolLocations[0];
4409     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4410       = Name.EndLocation.getRawEncoding();
4411     return NameInfo;
4412 
4413   case UnqualifiedId::IK_LiteralOperatorId:
4414     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4415                                                            Name.Identifier));
4416     NameInfo.setLoc(Name.StartLocation);
4417     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4418     return NameInfo;
4419 
4420   case UnqualifiedId::IK_ConversionFunctionId: {
4421     TypeSourceInfo *TInfo;
4422     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4423     if (Ty.isNull())
4424       return DeclarationNameInfo();
4425     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4426                                                Context.getCanonicalType(Ty)));
4427     NameInfo.setLoc(Name.StartLocation);
4428     NameInfo.setNamedTypeInfo(TInfo);
4429     return NameInfo;
4430   }
4431 
4432   case UnqualifiedId::IK_ConstructorName: {
4433     TypeSourceInfo *TInfo;
4434     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4435     if (Ty.isNull())
4436       return DeclarationNameInfo();
4437     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4438                                               Context.getCanonicalType(Ty)));
4439     NameInfo.setLoc(Name.StartLocation);
4440     NameInfo.setNamedTypeInfo(TInfo);
4441     return NameInfo;
4442   }
4443 
4444   case UnqualifiedId::IK_ConstructorTemplateId: {
4445     // In well-formed code, we can only have a constructor
4446     // template-id that refers to the current context, so go there
4447     // to find the actual type being constructed.
4448     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4449     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4450       return DeclarationNameInfo();
4451 
4452     // Determine the type of the class being constructed.
4453     QualType CurClassType = Context.getTypeDeclType(CurClass);
4454 
4455     // FIXME: Check two things: that the template-id names the same type as
4456     // CurClassType, and that the template-id does not occur when the name
4457     // was qualified.
4458 
4459     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4460                                     Context.getCanonicalType(CurClassType)));
4461     NameInfo.setLoc(Name.StartLocation);
4462     // FIXME: should we retrieve TypeSourceInfo?
4463     NameInfo.setNamedTypeInfo(nullptr);
4464     return NameInfo;
4465   }
4466 
4467   case UnqualifiedId::IK_DestructorName: {
4468     TypeSourceInfo *TInfo;
4469     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4470     if (Ty.isNull())
4471       return DeclarationNameInfo();
4472     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4473                                               Context.getCanonicalType(Ty)));
4474     NameInfo.setLoc(Name.StartLocation);
4475     NameInfo.setNamedTypeInfo(TInfo);
4476     return NameInfo;
4477   }
4478 
4479   case UnqualifiedId::IK_TemplateId: {
4480     TemplateName TName = Name.TemplateId->Template.get();
4481     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4482     return Context.getNameForTemplate(TName, TNameLoc);
4483   }
4484 
4485   } // switch (Name.getKind())
4486 
4487   llvm_unreachable("Unknown name kind");
4488 }
4489 
4490 static QualType getCoreType(QualType Ty) {
4491   do {
4492     if (Ty->isPointerType() || Ty->isReferenceType())
4493       Ty = Ty->getPointeeType();
4494     else if (Ty->isArrayType())
4495       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4496     else
4497       return Ty.withoutLocalFastQualifiers();
4498   } while (true);
4499 }
4500 
4501 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4502 /// and Definition have "nearly" matching parameters. This heuristic is
4503 /// used to improve diagnostics in the case where an out-of-line function
4504 /// definition doesn't match any declaration within the class or namespace.
4505 /// Also sets Params to the list of indices to the parameters that differ
4506 /// between the declaration and the definition. If hasSimilarParameters
4507 /// returns true and Params is empty, then all of the parameters match.
4508 static bool hasSimilarParameters(ASTContext &Context,
4509                                      FunctionDecl *Declaration,
4510                                      FunctionDecl *Definition,
4511                                      SmallVectorImpl<unsigned> &Params) {
4512   Params.clear();
4513   if (Declaration->param_size() != Definition->param_size())
4514     return false;
4515   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4516     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4517     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4518 
4519     // The parameter types are identical
4520     if (Context.hasSameType(DefParamTy, DeclParamTy))
4521       continue;
4522 
4523     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4524     QualType DefParamBaseTy = getCoreType(DefParamTy);
4525     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4526     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4527 
4528     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4529         (DeclTyName && DeclTyName == DefTyName))
4530       Params.push_back(Idx);
4531     else  // The two parameters aren't even close
4532       return false;
4533   }
4534 
4535   return true;
4536 }
4537 
4538 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4539 /// declarator needs to be rebuilt in the current instantiation.
4540 /// Any bits of declarator which appear before the name are valid for
4541 /// consideration here.  That's specifically the type in the decl spec
4542 /// and the base type in any member-pointer chunks.
4543 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4544                                                     DeclarationName Name) {
4545   // The types we specifically need to rebuild are:
4546   //   - typenames, typeofs, and decltypes
4547   //   - types which will become injected class names
4548   // Of course, we also need to rebuild any type referencing such a
4549   // type.  It's safest to just say "dependent", but we call out a
4550   // few cases here.
4551 
4552   DeclSpec &DS = D.getMutableDeclSpec();
4553   switch (DS.getTypeSpecType()) {
4554   case DeclSpec::TST_typename:
4555   case DeclSpec::TST_typeofType:
4556   case DeclSpec::TST_underlyingType:
4557   case DeclSpec::TST_atomic: {
4558     // Grab the type from the parser.
4559     TypeSourceInfo *TSI = nullptr;
4560     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4561     if (T.isNull() || !T->isDependentType()) break;
4562 
4563     // Make sure there's a type source info.  This isn't really much
4564     // of a waste; most dependent types should have type source info
4565     // attached already.
4566     if (!TSI)
4567       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4568 
4569     // Rebuild the type in the current instantiation.
4570     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4571     if (!TSI) return true;
4572 
4573     // Store the new type back in the decl spec.
4574     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4575     DS.UpdateTypeRep(LocType);
4576     break;
4577   }
4578 
4579   case DeclSpec::TST_decltype:
4580   case DeclSpec::TST_typeofExpr: {
4581     Expr *E = DS.getRepAsExpr();
4582     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4583     if (Result.isInvalid()) return true;
4584     DS.UpdateExprRep(Result.get());
4585     break;
4586   }
4587 
4588   default:
4589     // Nothing to do for these decl specs.
4590     break;
4591   }
4592 
4593   // It doesn't matter what order we do this in.
4594   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4595     DeclaratorChunk &Chunk = D.getTypeObject(I);
4596 
4597     // The only type information in the declarator which can come
4598     // before the declaration name is the base type of a member
4599     // pointer.
4600     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4601       continue;
4602 
4603     // Rebuild the scope specifier in-place.
4604     CXXScopeSpec &SS = Chunk.Mem.Scope();
4605     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4606       return true;
4607   }
4608 
4609   return false;
4610 }
4611 
4612 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4613   D.setFunctionDefinitionKind(FDK_Declaration);
4614   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4615 
4616   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4617       Dcl && Dcl->getDeclContext()->isFileContext())
4618     Dcl->setTopLevelDeclInObjCContainer();
4619 
4620   return Dcl;
4621 }
4622 
4623 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4624 ///   If T is the name of a class, then each of the following shall have a
4625 ///   name different from T:
4626 ///     - every static data member of class T;
4627 ///     - every member function of class T
4628 ///     - every member of class T that is itself a type;
4629 /// \returns true if the declaration name violates these rules.
4630 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4631                                    DeclarationNameInfo NameInfo) {
4632   DeclarationName Name = NameInfo.getName();
4633 
4634   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4635     if (Record->getIdentifier() && Record->getDeclName() == Name) {
4636       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4637       return true;
4638     }
4639 
4640   return false;
4641 }
4642 
4643 /// \brief Diagnose a declaration whose declarator-id has the given
4644 /// nested-name-specifier.
4645 ///
4646 /// \param SS The nested-name-specifier of the declarator-id.
4647 ///
4648 /// \param DC The declaration context to which the nested-name-specifier
4649 /// resolves.
4650 ///
4651 /// \param Name The name of the entity being declared.
4652 ///
4653 /// \param Loc The location of the name of the entity being declared.
4654 ///
4655 /// \returns true if we cannot safely recover from this error, false otherwise.
4656 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4657                                         DeclarationName Name,
4658                                         SourceLocation Loc) {
4659   DeclContext *Cur = CurContext;
4660   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4661     Cur = Cur->getParent();
4662 
4663   // If the user provided a superfluous scope specifier that refers back to the
4664   // class in which the entity is already declared, diagnose and ignore it.
4665   //
4666   // class X {
4667   //   void X::f();
4668   // };
4669   //
4670   // Note, it was once ill-formed to give redundant qualification in all
4671   // contexts, but that rule was removed by DR482.
4672   if (Cur->Equals(DC)) {
4673     if (Cur->isRecord()) {
4674       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4675                                       : diag::err_member_extra_qualification)
4676         << Name << FixItHint::CreateRemoval(SS.getRange());
4677       SS.clear();
4678     } else {
4679       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4680     }
4681     return false;
4682   }
4683 
4684   // Check whether the qualifying scope encloses the scope of the original
4685   // declaration.
4686   if (!Cur->Encloses(DC)) {
4687     if (Cur->isRecord())
4688       Diag(Loc, diag::err_member_qualification)
4689         << Name << SS.getRange();
4690     else if (isa<TranslationUnitDecl>(DC))
4691       Diag(Loc, diag::err_invalid_declarator_global_scope)
4692         << Name << SS.getRange();
4693     else if (isa<FunctionDecl>(Cur))
4694       Diag(Loc, diag::err_invalid_declarator_in_function)
4695         << Name << SS.getRange();
4696     else if (isa<BlockDecl>(Cur))
4697       Diag(Loc, diag::err_invalid_declarator_in_block)
4698         << Name << SS.getRange();
4699     else
4700       Diag(Loc, diag::err_invalid_declarator_scope)
4701       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4702 
4703     return true;
4704   }
4705 
4706   if (Cur->isRecord()) {
4707     // Cannot qualify members within a class.
4708     Diag(Loc, diag::err_member_qualification)
4709       << Name << SS.getRange();
4710     SS.clear();
4711 
4712     // C++ constructors and destructors with incorrect scopes can break
4713     // our AST invariants by having the wrong underlying types. If
4714     // that's the case, then drop this declaration entirely.
4715     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4716          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4717         !Context.hasSameType(Name.getCXXNameType(),
4718                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4719       return true;
4720 
4721     return false;
4722   }
4723 
4724   // C++11 [dcl.meaning]p1:
4725   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4726   //   not begin with a decltype-specifer"
4727   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4728   while (SpecLoc.getPrefix())
4729     SpecLoc = SpecLoc.getPrefix();
4730   if (dyn_cast_or_null<DecltypeType>(
4731         SpecLoc.getNestedNameSpecifier()->getAsType()))
4732     Diag(Loc, diag::err_decltype_in_declarator)
4733       << SpecLoc.getTypeLoc().getSourceRange();
4734 
4735   return false;
4736 }
4737 
4738 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4739                                   MultiTemplateParamsArg TemplateParamLists) {
4740   // TODO: consider using NameInfo for diagnostic.
4741   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4742   DeclarationName Name = NameInfo.getName();
4743 
4744   // All of these full declarators require an identifier.  If it doesn't have
4745   // one, the ParsedFreeStandingDeclSpec action should be used.
4746   if (!Name) {
4747     if (!D.isInvalidType())  // Reject this if we think it is valid.
4748       Diag(D.getDeclSpec().getLocStart(),
4749            diag::err_declarator_need_ident)
4750         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4751     return nullptr;
4752   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4753     return nullptr;
4754 
4755   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4756   // we find one that is.
4757   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4758          (S->getFlags() & Scope::TemplateParamScope) != 0)
4759     S = S->getParent();
4760 
4761   DeclContext *DC = CurContext;
4762   if (D.getCXXScopeSpec().isInvalid())
4763     D.setInvalidType();
4764   else if (D.getCXXScopeSpec().isSet()) {
4765     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4766                                         UPPC_DeclarationQualifier))
4767       return nullptr;
4768 
4769     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4770     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4771     if (!DC || isa<EnumDecl>(DC)) {
4772       // If we could not compute the declaration context, it's because the
4773       // declaration context is dependent but does not refer to a class,
4774       // class template, or class template partial specialization. Complain
4775       // and return early, to avoid the coming semantic disaster.
4776       Diag(D.getIdentifierLoc(),
4777            diag::err_template_qualified_declarator_no_match)
4778         << D.getCXXScopeSpec().getScopeRep()
4779         << D.getCXXScopeSpec().getRange();
4780       return nullptr;
4781     }
4782     bool IsDependentContext = DC->isDependentContext();
4783 
4784     if (!IsDependentContext &&
4785         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4786       return nullptr;
4787 
4788     // If a class is incomplete, do not parse entities inside it.
4789     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4790       Diag(D.getIdentifierLoc(),
4791            diag::err_member_def_undefined_record)
4792         << Name << DC << D.getCXXScopeSpec().getRange();
4793       return nullptr;
4794     }
4795     if (!D.getDeclSpec().isFriendSpecified()) {
4796       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4797                                       Name, D.getIdentifierLoc())) {
4798         if (DC->isRecord())
4799           return nullptr;
4800 
4801         D.setInvalidType();
4802       }
4803     }
4804 
4805     // Check whether we need to rebuild the type of the given
4806     // declaration in the current instantiation.
4807     if (EnteringContext && IsDependentContext &&
4808         TemplateParamLists.size() != 0) {
4809       ContextRAII SavedContext(*this, DC);
4810       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4811         D.setInvalidType();
4812     }
4813   }
4814 
4815   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4816   QualType R = TInfo->getType();
4817 
4818   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4819     // If this is a typedef, we'll end up spewing multiple diagnostics.
4820     // Just return early; it's safer. If this is a function, let the
4821     // "constructor cannot have a return type" diagnostic handle it.
4822     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4823       return nullptr;
4824 
4825   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4826                                       UPPC_DeclarationType))
4827     D.setInvalidType();
4828 
4829   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4830                         ForRedeclaration);
4831 
4832   // See if this is a redefinition of a variable in the same scope.
4833   if (!D.getCXXScopeSpec().isSet()) {
4834     bool IsLinkageLookup = false;
4835     bool CreateBuiltins = false;
4836 
4837     // If the declaration we're planning to build will be a function
4838     // or object with linkage, then look for another declaration with
4839     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4840     //
4841     // If the declaration we're planning to build will be declared with
4842     // external linkage in the translation unit, create any builtin with
4843     // the same name.
4844     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4845       /* Do nothing*/;
4846     else if (CurContext->isFunctionOrMethod() &&
4847              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4848               R->isFunctionType())) {
4849       IsLinkageLookup = true;
4850       CreateBuiltins =
4851           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4852     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4853                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4854       CreateBuiltins = true;
4855 
4856     if (IsLinkageLookup)
4857       Previous.clear(LookupRedeclarationWithLinkage);
4858 
4859     LookupName(Previous, S, CreateBuiltins);
4860   } else { // Something like "int foo::x;"
4861     LookupQualifiedName(Previous, DC);
4862 
4863     // C++ [dcl.meaning]p1:
4864     //   When the declarator-id is qualified, the declaration shall refer to a
4865     //  previously declared member of the class or namespace to which the
4866     //  qualifier refers (or, in the case of a namespace, of an element of the
4867     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4868     //  thereof; [...]
4869     //
4870     // Note that we already checked the context above, and that we do not have
4871     // enough information to make sure that Previous contains the declaration
4872     // we want to match. For example, given:
4873     //
4874     //   class X {
4875     //     void f();
4876     //     void f(float);
4877     //   };
4878     //
4879     //   void X::f(int) { } // ill-formed
4880     //
4881     // In this case, Previous will point to the overload set
4882     // containing the two f's declared in X, but neither of them
4883     // matches.
4884 
4885     // C++ [dcl.meaning]p1:
4886     //   [...] the member shall not merely have been introduced by a
4887     //   using-declaration in the scope of the class or namespace nominated by
4888     //   the nested-name-specifier of the declarator-id.
4889     RemoveUsingDecls(Previous);
4890   }
4891 
4892   if (Previous.isSingleResult() &&
4893       Previous.getFoundDecl()->isTemplateParameter()) {
4894     // Maybe we will complain about the shadowed template parameter.
4895     if (!D.isInvalidType())
4896       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4897                                       Previous.getFoundDecl());
4898 
4899     // Just pretend that we didn't see the previous declaration.
4900     Previous.clear();
4901   }
4902 
4903   // In C++, the previous declaration we find might be a tag type
4904   // (class or enum). In this case, the new declaration will hide the
4905   // tag type. Note that this does does not apply if we're declaring a
4906   // typedef (C++ [dcl.typedef]p4).
4907   if (Previous.isSingleTagDecl() &&
4908       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4909     Previous.clear();
4910 
4911   // Check that there are no default arguments other than in the parameters
4912   // of a function declaration (C++ only).
4913   if (getLangOpts().CPlusPlus)
4914     CheckExtraCXXDefaultArguments(D);
4915 
4916   if (D.getDeclSpec().isConceptSpecified()) {
4917     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
4918     // applied only to the definition of a function template or variable
4919     // template, declared in namespace scope
4920     if (!TemplateParamLists.size()) {
4921       Diag(D.getDeclSpec().getConceptSpecLoc(),
4922            diag:: err_concept_wrong_decl_kind);
4923       return nullptr;
4924     }
4925 
4926     if (!DC->getRedeclContext()->isFileContext()) {
4927       Diag(D.getIdentifierLoc(),
4928            diag::err_concept_decls_may_only_appear_in_namespace_scope);
4929       return nullptr;
4930     }
4931   }
4932 
4933   NamedDecl *New;
4934 
4935   bool AddToScope = true;
4936   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4937     if (TemplateParamLists.size()) {
4938       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4939       return nullptr;
4940     }
4941 
4942     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4943   } else if (R->isFunctionType()) {
4944     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4945                                   TemplateParamLists,
4946                                   AddToScope);
4947   } else {
4948     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4949                                   AddToScope);
4950   }
4951 
4952   if (!New)
4953     return nullptr;
4954 
4955   // If this has an identifier and is not an invalid redeclaration or
4956   // function template specialization, add it to the scope stack.
4957   if (New->getDeclName() && AddToScope &&
4958        !(D.isRedeclaration() && New->isInvalidDecl())) {
4959     // Only make a locally-scoped extern declaration visible if it is the first
4960     // declaration of this entity. Qualified lookup for such an entity should
4961     // only find this declaration if there is no visible declaration of it.
4962     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4963     PushOnScopeChains(New, S, AddToContext);
4964     if (!AddToContext)
4965       CurContext->addHiddenDecl(New);
4966   }
4967 
4968   return New;
4969 }
4970 
4971 /// Helper method to turn variable array types into constant array
4972 /// types in certain situations which would otherwise be errors (for
4973 /// GCC compatibility).
4974 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4975                                                     ASTContext &Context,
4976                                                     bool &SizeIsNegative,
4977                                                     llvm::APSInt &Oversized) {
4978   // This method tries to turn a variable array into a constant
4979   // array even when the size isn't an ICE.  This is necessary
4980   // for compatibility with code that depends on gcc's buggy
4981   // constant expression folding, like struct {char x[(int)(char*)2];}
4982   SizeIsNegative = false;
4983   Oversized = 0;
4984 
4985   if (T->isDependentType())
4986     return QualType();
4987 
4988   QualifierCollector Qs;
4989   const Type *Ty = Qs.strip(T);
4990 
4991   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4992     QualType Pointee = PTy->getPointeeType();
4993     QualType FixedType =
4994         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4995                                             Oversized);
4996     if (FixedType.isNull()) return FixedType;
4997     FixedType = Context.getPointerType(FixedType);
4998     return Qs.apply(Context, FixedType);
4999   }
5000   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5001     QualType Inner = PTy->getInnerType();
5002     QualType FixedType =
5003         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5004                                             Oversized);
5005     if (FixedType.isNull()) return FixedType;
5006     FixedType = Context.getParenType(FixedType);
5007     return Qs.apply(Context, FixedType);
5008   }
5009 
5010   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5011   if (!VLATy)
5012     return QualType();
5013   // FIXME: We should probably handle this case
5014   if (VLATy->getElementType()->isVariablyModifiedType())
5015     return QualType();
5016 
5017   llvm::APSInt Res;
5018   if (!VLATy->getSizeExpr() ||
5019       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5020     return QualType();
5021 
5022   // Check whether the array size is negative.
5023   if (Res.isSigned() && Res.isNegative()) {
5024     SizeIsNegative = true;
5025     return QualType();
5026   }
5027 
5028   // Check whether the array is too large to be addressed.
5029   unsigned ActiveSizeBits
5030     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5031                                               Res);
5032   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5033     Oversized = Res;
5034     return QualType();
5035   }
5036 
5037   return Context.getConstantArrayType(VLATy->getElementType(),
5038                                       Res, ArrayType::Normal, 0);
5039 }
5040 
5041 static void
5042 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5043   SrcTL = SrcTL.getUnqualifiedLoc();
5044   DstTL = DstTL.getUnqualifiedLoc();
5045   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5046     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5047     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5048                                       DstPTL.getPointeeLoc());
5049     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5050     return;
5051   }
5052   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5053     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5054     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5055                                       DstPTL.getInnerLoc());
5056     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5057     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5058     return;
5059   }
5060   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5061   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5062   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5063   TypeLoc DstElemTL = DstATL.getElementLoc();
5064   DstElemTL.initializeFullCopy(SrcElemTL);
5065   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5066   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5067   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5068 }
5069 
5070 /// Helper method to turn variable array types into constant array
5071 /// types in certain situations which would otherwise be errors (for
5072 /// GCC compatibility).
5073 static TypeSourceInfo*
5074 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5075                                               ASTContext &Context,
5076                                               bool &SizeIsNegative,
5077                                               llvm::APSInt &Oversized) {
5078   QualType FixedTy
5079     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5080                                           SizeIsNegative, Oversized);
5081   if (FixedTy.isNull())
5082     return nullptr;
5083   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5084   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5085                                     FixedTInfo->getTypeLoc());
5086   return FixedTInfo;
5087 }
5088 
5089 /// \brief Register the given locally-scoped extern "C" declaration so
5090 /// that it can be found later for redeclarations. We include any extern "C"
5091 /// declaration that is not visible in the translation unit here, not just
5092 /// function-scope declarations.
5093 void
5094 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5095   if (!getLangOpts().CPlusPlus &&
5096       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5097     // Don't need to track declarations in the TU in C.
5098     return;
5099 
5100   // Note that we have a locally-scoped external with this name.
5101   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5102 }
5103 
5104 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5105   // FIXME: We can have multiple results via __attribute__((overloadable)).
5106   auto Result = Context.getExternCContextDecl()->lookup(Name);
5107   return Result.empty() ? nullptr : *Result.begin();
5108 }
5109 
5110 /// \brief Diagnose function specifiers on a declaration of an identifier that
5111 /// does not identify a function.
5112 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5113   // FIXME: We should probably indicate the identifier in question to avoid
5114   // confusion for constructs like "inline int a(), b;"
5115   if (DS.isInlineSpecified())
5116     Diag(DS.getInlineSpecLoc(),
5117          diag::err_inline_non_function);
5118 
5119   if (DS.isVirtualSpecified())
5120     Diag(DS.getVirtualSpecLoc(),
5121          diag::err_virtual_non_function);
5122 
5123   if (DS.isExplicitSpecified())
5124     Diag(DS.getExplicitSpecLoc(),
5125          diag::err_explicit_non_function);
5126 
5127   if (DS.isNoreturnSpecified())
5128     Diag(DS.getNoreturnSpecLoc(),
5129          diag::err_noreturn_non_function);
5130 }
5131 
5132 NamedDecl*
5133 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5134                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5135   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5136   if (D.getCXXScopeSpec().isSet()) {
5137     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5138       << D.getCXXScopeSpec().getRange();
5139     D.setInvalidType();
5140     // Pretend we didn't see the scope specifier.
5141     DC = CurContext;
5142     Previous.clear();
5143   }
5144 
5145   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5146 
5147   if (D.getDeclSpec().isConstexprSpecified())
5148     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5149       << 1;
5150   if (D.getDeclSpec().isConceptSpecified())
5151     Diag(D.getDeclSpec().getConceptSpecLoc(),
5152          diag::err_concept_wrong_decl_kind);
5153 
5154   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5155     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5156       << D.getName().getSourceRange();
5157     return nullptr;
5158   }
5159 
5160   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5161   if (!NewTD) return nullptr;
5162 
5163   // Handle attributes prior to checking for duplicates in MergeVarDecl
5164   ProcessDeclAttributes(S, NewTD, D);
5165 
5166   CheckTypedefForVariablyModifiedType(S, NewTD);
5167 
5168   bool Redeclaration = D.isRedeclaration();
5169   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5170   D.setRedeclaration(Redeclaration);
5171   return ND;
5172 }
5173 
5174 void
5175 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5176   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5177   // then it shall have block scope.
5178   // Note that variably modified types must be fixed before merging the decl so
5179   // that redeclarations will match.
5180   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5181   QualType T = TInfo->getType();
5182   if (T->isVariablyModifiedType()) {
5183     getCurFunction()->setHasBranchProtectedScope();
5184 
5185     if (S->getFnParent() == nullptr) {
5186       bool SizeIsNegative;
5187       llvm::APSInt Oversized;
5188       TypeSourceInfo *FixedTInfo =
5189         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5190                                                       SizeIsNegative,
5191                                                       Oversized);
5192       if (FixedTInfo) {
5193         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5194         NewTD->setTypeSourceInfo(FixedTInfo);
5195       } else {
5196         if (SizeIsNegative)
5197           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5198         else if (T->isVariableArrayType())
5199           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5200         else if (Oversized.getBoolValue())
5201           Diag(NewTD->getLocation(), diag::err_array_too_large)
5202             << Oversized.toString(10);
5203         else
5204           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5205         NewTD->setInvalidDecl();
5206       }
5207     }
5208   }
5209 }
5210 
5211 
5212 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5213 /// declares a typedef-name, either using the 'typedef' type specifier or via
5214 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5215 NamedDecl*
5216 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5217                            LookupResult &Previous, bool &Redeclaration) {
5218   // Merge the decl with the existing one if appropriate. If the decl is
5219   // in an outer scope, it isn't the same thing.
5220   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5221                        /*AllowInlineNamespace*/false);
5222   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5223   if (!Previous.empty()) {
5224     Redeclaration = true;
5225     MergeTypedefNameDecl(S, NewTD, Previous);
5226   }
5227 
5228   // If this is the C FILE type, notify the AST context.
5229   if (IdentifierInfo *II = NewTD->getIdentifier())
5230     if (!NewTD->isInvalidDecl() &&
5231         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5232       if (II->isStr("FILE"))
5233         Context.setFILEDecl(NewTD);
5234       else if (II->isStr("jmp_buf"))
5235         Context.setjmp_bufDecl(NewTD);
5236       else if (II->isStr("sigjmp_buf"))
5237         Context.setsigjmp_bufDecl(NewTD);
5238       else if (II->isStr("ucontext_t"))
5239         Context.setucontext_tDecl(NewTD);
5240     }
5241 
5242   return NewTD;
5243 }
5244 
5245 /// \brief Determines whether the given declaration is an out-of-scope
5246 /// previous declaration.
5247 ///
5248 /// This routine should be invoked when name lookup has found a
5249 /// previous declaration (PrevDecl) that is not in the scope where a
5250 /// new declaration by the same name is being introduced. If the new
5251 /// declaration occurs in a local scope, previous declarations with
5252 /// linkage may still be considered previous declarations (C99
5253 /// 6.2.2p4-5, C++ [basic.link]p6).
5254 ///
5255 /// \param PrevDecl the previous declaration found by name
5256 /// lookup
5257 ///
5258 /// \param DC the context in which the new declaration is being
5259 /// declared.
5260 ///
5261 /// \returns true if PrevDecl is an out-of-scope previous declaration
5262 /// for a new delcaration with the same name.
5263 static bool
5264 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5265                                 ASTContext &Context) {
5266   if (!PrevDecl)
5267     return false;
5268 
5269   if (!PrevDecl->hasLinkage())
5270     return false;
5271 
5272   if (Context.getLangOpts().CPlusPlus) {
5273     // C++ [basic.link]p6:
5274     //   If there is a visible declaration of an entity with linkage
5275     //   having the same name and type, ignoring entities declared
5276     //   outside the innermost enclosing namespace scope, the block
5277     //   scope declaration declares that same entity and receives the
5278     //   linkage of the previous declaration.
5279     DeclContext *OuterContext = DC->getRedeclContext();
5280     if (!OuterContext->isFunctionOrMethod())
5281       // This rule only applies to block-scope declarations.
5282       return false;
5283 
5284     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5285     if (PrevOuterContext->isRecord())
5286       // We found a member function: ignore it.
5287       return false;
5288 
5289     // Find the innermost enclosing namespace for the new and
5290     // previous declarations.
5291     OuterContext = OuterContext->getEnclosingNamespaceContext();
5292     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5293 
5294     // The previous declaration is in a different namespace, so it
5295     // isn't the same function.
5296     if (!OuterContext->Equals(PrevOuterContext))
5297       return false;
5298   }
5299 
5300   return true;
5301 }
5302 
5303 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5304   CXXScopeSpec &SS = D.getCXXScopeSpec();
5305   if (!SS.isSet()) return;
5306   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5307 }
5308 
5309 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5310   QualType type = decl->getType();
5311   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5312   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5313     // Various kinds of declaration aren't allowed to be __autoreleasing.
5314     unsigned kind = -1U;
5315     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5316       if (var->hasAttr<BlocksAttr>())
5317         kind = 0; // __block
5318       else if (!var->hasLocalStorage())
5319         kind = 1; // global
5320     } else if (isa<ObjCIvarDecl>(decl)) {
5321       kind = 3; // ivar
5322     } else if (isa<FieldDecl>(decl)) {
5323       kind = 2; // field
5324     }
5325 
5326     if (kind != -1U) {
5327       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5328         << kind;
5329     }
5330   } else if (lifetime == Qualifiers::OCL_None) {
5331     // Try to infer lifetime.
5332     if (!type->isObjCLifetimeType())
5333       return false;
5334 
5335     lifetime = type->getObjCARCImplicitLifetime();
5336     type = Context.getLifetimeQualifiedType(type, lifetime);
5337     decl->setType(type);
5338   }
5339 
5340   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5341     // Thread-local variables cannot have lifetime.
5342     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5343         var->getTLSKind()) {
5344       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5345         << var->getType();
5346       return true;
5347     }
5348   }
5349 
5350   return false;
5351 }
5352 
5353 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5354   // Ensure that an auto decl is deduced otherwise the checks below might cache
5355   // the wrong linkage.
5356   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5357 
5358   // 'weak' only applies to declarations with external linkage.
5359   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5360     if (!ND.isExternallyVisible()) {
5361       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5362       ND.dropAttr<WeakAttr>();
5363     }
5364   }
5365   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5366     if (ND.isExternallyVisible()) {
5367       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5368       ND.dropAttr<WeakRefAttr>();
5369       ND.dropAttr<AliasAttr>();
5370     }
5371   }
5372 
5373   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5374     if (VD->hasInit()) {
5375       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5376         assert(VD->isThisDeclarationADefinition() &&
5377                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5378         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
5379         VD->dropAttr<AliasAttr>();
5380       }
5381     }
5382   }
5383 
5384   // 'selectany' only applies to externally visible variable declarations.
5385   // It does not apply to functions.
5386   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5387     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5388       S.Diag(Attr->getLocation(),
5389              diag::err_attribute_selectany_non_extern_data);
5390       ND.dropAttr<SelectAnyAttr>();
5391     }
5392   }
5393 
5394   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5395     // dll attributes require external linkage. Static locals may have external
5396     // linkage but still cannot be explicitly imported or exported.
5397     auto *VD = dyn_cast<VarDecl>(&ND);
5398     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5399       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5400         << &ND << Attr;
5401       ND.setInvalidDecl();
5402     }
5403   }
5404 
5405   // Virtual functions cannot be marked as 'notail'.
5406   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5407     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5408       if (MD->isVirtual()) {
5409         S.Diag(ND.getLocation(),
5410                diag::err_invalid_attribute_on_virtual_function)
5411             << Attr;
5412         ND.dropAttr<NotTailCalledAttr>();
5413       }
5414 }
5415 
5416 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5417                                            NamedDecl *NewDecl,
5418                                            bool IsSpecialization) {
5419   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5420     OldDecl = OldTD->getTemplatedDecl();
5421   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5422     NewDecl = NewTD->getTemplatedDecl();
5423 
5424   if (!OldDecl || !NewDecl)
5425     return;
5426 
5427   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5428   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5429   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5430   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5431 
5432   // dllimport and dllexport are inheritable attributes so we have to exclude
5433   // inherited attribute instances.
5434   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5435                     (NewExportAttr && !NewExportAttr->isInherited());
5436 
5437   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5438   // the only exception being explicit specializations.
5439   // Implicitly generated declarations are also excluded for now because there
5440   // is no other way to switch these to use dllimport or dllexport.
5441   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5442 
5443   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5444     // Allow with a warning for free functions and global variables.
5445     bool JustWarn = false;
5446     if (!OldDecl->isCXXClassMember()) {
5447       auto *VD = dyn_cast<VarDecl>(OldDecl);
5448       if (VD && !VD->getDescribedVarTemplate())
5449         JustWarn = true;
5450       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5451       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5452         JustWarn = true;
5453     }
5454 
5455     // We cannot change a declaration that's been used because IR has already
5456     // been emitted. Dllimported functions will still work though (modulo
5457     // address equality) as they can use the thunk.
5458     if (OldDecl->isUsed())
5459       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5460         JustWarn = false;
5461 
5462     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5463                                : diag::err_attribute_dll_redeclaration;
5464     S.Diag(NewDecl->getLocation(), DiagID)
5465         << NewDecl
5466         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5467     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5468     if (!JustWarn) {
5469       NewDecl->setInvalidDecl();
5470       return;
5471     }
5472   }
5473 
5474   // A redeclaration is not allowed to drop a dllimport attribute, the only
5475   // exceptions being inline function definitions, local extern declarations,
5476   // and qualified friend declarations.
5477   // NB: MSVC converts such a declaration to dllexport.
5478   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5479   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5480     // Ignore static data because out-of-line definitions are diagnosed
5481     // separately.
5482     IsStaticDataMember = VD->isStaticDataMember();
5483   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5484     IsInline = FD->isInlined();
5485     IsQualifiedFriend = FD->getQualifier() &&
5486                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5487   }
5488 
5489   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5490       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5491     S.Diag(NewDecl->getLocation(),
5492            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5493       << NewDecl << OldImportAttr;
5494     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5495     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5496     OldDecl->dropAttr<DLLImportAttr>();
5497     NewDecl->dropAttr<DLLImportAttr>();
5498   } else if (IsInline && OldImportAttr &&
5499              !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5500     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5501     OldDecl->dropAttr<DLLImportAttr>();
5502     NewDecl->dropAttr<DLLImportAttr>();
5503     S.Diag(NewDecl->getLocation(),
5504            diag::warn_dllimport_dropped_from_inline_function)
5505         << NewDecl << OldImportAttr;
5506   }
5507 }
5508 
5509 /// Given that we are within the definition of the given function,
5510 /// will that definition behave like C99's 'inline', where the
5511 /// definition is discarded except for optimization purposes?
5512 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5513   // Try to avoid calling GetGVALinkageForFunction.
5514 
5515   // All cases of this require the 'inline' keyword.
5516   if (!FD->isInlined()) return false;
5517 
5518   // This is only possible in C++ with the gnu_inline attribute.
5519   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5520     return false;
5521 
5522   // Okay, go ahead and call the relatively-more-expensive function.
5523 
5524 #ifndef NDEBUG
5525   // AST quite reasonably asserts that it's working on a function
5526   // definition.  We don't really have a way to tell it that we're
5527   // currently defining the function, so just lie to it in +Asserts
5528   // builds.  This is an awful hack.
5529   FD->setLazyBody(1);
5530 #endif
5531 
5532   bool isC99Inline =
5533       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5534 
5535 #ifndef NDEBUG
5536   FD->setLazyBody(0);
5537 #endif
5538 
5539   return isC99Inline;
5540 }
5541 
5542 /// Determine whether a variable is extern "C" prior to attaching
5543 /// an initializer. We can't just call isExternC() here, because that
5544 /// will also compute and cache whether the declaration is externally
5545 /// visible, which might change when we attach the initializer.
5546 ///
5547 /// This can only be used if the declaration is known to not be a
5548 /// redeclaration of an internal linkage declaration.
5549 ///
5550 /// For instance:
5551 ///
5552 ///   auto x = []{};
5553 ///
5554 /// Attaching the initializer here makes this declaration not externally
5555 /// visible, because its type has internal linkage.
5556 ///
5557 /// FIXME: This is a hack.
5558 template<typename T>
5559 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5560   if (S.getLangOpts().CPlusPlus) {
5561     // In C++, the overloadable attribute negates the effects of extern "C".
5562     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5563       return false;
5564 
5565     // So do CUDA's host/device attributes if overloading is enabled.
5566     if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
5567         (D->template hasAttr<CUDADeviceAttr>() ||
5568          D->template hasAttr<CUDAHostAttr>()))
5569       return false;
5570   }
5571   return D->isExternC();
5572 }
5573 
5574 static bool shouldConsiderLinkage(const VarDecl *VD) {
5575   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5576   if (DC->isFunctionOrMethod())
5577     return VD->hasExternalStorage();
5578   if (DC->isFileContext())
5579     return true;
5580   if (DC->isRecord())
5581     return false;
5582   llvm_unreachable("Unexpected context");
5583 }
5584 
5585 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5586   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5587   if (DC->isFileContext() || DC->isFunctionOrMethod())
5588     return true;
5589   if (DC->isRecord())
5590     return false;
5591   llvm_unreachable("Unexpected context");
5592 }
5593 
5594 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5595                           AttributeList::Kind Kind) {
5596   for (const AttributeList *L = AttrList; L; L = L->getNext())
5597     if (L->getKind() == Kind)
5598       return true;
5599   return false;
5600 }
5601 
5602 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5603                           AttributeList::Kind Kind) {
5604   // Check decl attributes on the DeclSpec.
5605   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5606     return true;
5607 
5608   // Walk the declarator structure, checking decl attributes that were in a type
5609   // position to the decl itself.
5610   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5611     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5612       return true;
5613   }
5614 
5615   // Finally, check attributes on the decl itself.
5616   return hasParsedAttr(S, PD.getAttributes(), Kind);
5617 }
5618 
5619 /// Adjust the \c DeclContext for a function or variable that might be a
5620 /// function-local external declaration.
5621 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5622   if (!DC->isFunctionOrMethod())
5623     return false;
5624 
5625   // If this is a local extern function or variable declared within a function
5626   // template, don't add it into the enclosing namespace scope until it is
5627   // instantiated; it might have a dependent type right now.
5628   if (DC->isDependentContext())
5629     return true;
5630 
5631   // C++11 [basic.link]p7:
5632   //   When a block scope declaration of an entity with linkage is not found to
5633   //   refer to some other declaration, then that entity is a member of the
5634   //   innermost enclosing namespace.
5635   //
5636   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5637   // semantically-enclosing namespace, not a lexically-enclosing one.
5638   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5639     DC = DC->getParent();
5640   return true;
5641 }
5642 
5643 /// \brief Returns true if given declaration has external C language linkage.
5644 static bool isDeclExternC(const Decl *D) {
5645   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5646     return FD->isExternC();
5647   if (const auto *VD = dyn_cast<VarDecl>(D))
5648     return VD->isExternC();
5649 
5650   llvm_unreachable("Unknown type of decl!");
5651 }
5652 
5653 NamedDecl *
5654 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5655                               TypeSourceInfo *TInfo, LookupResult &Previous,
5656                               MultiTemplateParamsArg TemplateParamLists,
5657                               bool &AddToScope) {
5658   QualType R = TInfo->getType();
5659   DeclarationName Name = GetNameForDeclarator(D).getName();
5660 
5661   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5662   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5663 
5664   // dllimport globals without explicit storage class are treated as extern. We
5665   // have to change the storage class this early to get the right DeclContext.
5666   if (SC == SC_None && !DC->isRecord() &&
5667       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5668       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5669     SC = SC_Extern;
5670 
5671   DeclContext *OriginalDC = DC;
5672   bool IsLocalExternDecl = SC == SC_Extern &&
5673                            adjustContextForLocalExternDecl(DC);
5674 
5675   if (getLangOpts().OpenCL) {
5676     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5677     QualType NR = R;
5678     while (NR->isPointerType()) {
5679       if (NR->isFunctionPointerType()) {
5680         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5681         D.setInvalidType();
5682         break;
5683       }
5684       NR = NR->getPointeeType();
5685     }
5686 
5687     if (!getOpenCLOptions().cl_khr_fp16) {
5688       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5689       // half array type (unless the cl_khr_fp16 extension is enabled).
5690       if (Context.getBaseElementType(R)->isHalfType()) {
5691         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5692         D.setInvalidType();
5693       }
5694     }
5695   }
5696 
5697   if (SCSpec == DeclSpec::SCS_mutable) {
5698     // mutable can only appear on non-static class members, so it's always
5699     // an error here
5700     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5701     D.setInvalidType();
5702     SC = SC_None;
5703   }
5704 
5705   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5706       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5707                               D.getDeclSpec().getStorageClassSpecLoc())) {
5708     // In C++11, the 'register' storage class specifier is deprecated.
5709     // Suppress the warning in system macros, it's used in macros in some
5710     // popular C system headers, such as in glibc's htonl() macro.
5711     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5712          diag::warn_deprecated_register)
5713       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5714   }
5715 
5716   IdentifierInfo *II = Name.getAsIdentifierInfo();
5717   if (!II) {
5718     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5719       << Name;
5720     return nullptr;
5721   }
5722 
5723   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5724 
5725   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5726     // C99 6.9p2: The storage-class specifiers auto and register shall not
5727     // appear in the declaration specifiers in an external declaration.
5728     // Global Register+Asm is a GNU extension we support.
5729     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5730       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5731       D.setInvalidType();
5732     }
5733   }
5734 
5735   if (getLangOpts().OpenCL) {
5736     // OpenCL v1.2 s6.9.b p4:
5737     // The sampler type cannot be used with the __local and __global address
5738     // space qualifiers.
5739     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5740       R.getAddressSpace() == LangAS::opencl_global)) {
5741       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5742     }
5743 
5744     // OpenCL 1.2 spec, p6.9 r:
5745     // The event type cannot be used to declare a program scope variable.
5746     // The event type cannot be used with the __local, __constant and __global
5747     // address space qualifiers.
5748     if (R->isEventT()) {
5749       if (S->getParent() == nullptr) {
5750         Diag(D.getLocStart(), diag::err_event_t_global_var);
5751         D.setInvalidType();
5752       }
5753 
5754       if (R.getAddressSpace()) {
5755         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5756         D.setInvalidType();
5757       }
5758     }
5759   }
5760 
5761   bool IsExplicitSpecialization = false;
5762   bool IsVariableTemplateSpecialization = false;
5763   bool IsPartialSpecialization = false;
5764   bool IsVariableTemplate = false;
5765   VarDecl *NewVD = nullptr;
5766   VarTemplateDecl *NewTemplate = nullptr;
5767   TemplateParameterList *TemplateParams = nullptr;
5768   if (!getLangOpts().CPlusPlus) {
5769     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5770                             D.getIdentifierLoc(), II,
5771                             R, TInfo, SC);
5772 
5773     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5774       ParsingInitForAutoVars.insert(NewVD);
5775 
5776     if (D.isInvalidType())
5777       NewVD->setInvalidDecl();
5778   } else {
5779     bool Invalid = false;
5780 
5781     if (DC->isRecord() && !CurContext->isRecord()) {
5782       // This is an out-of-line definition of a static data member.
5783       switch (SC) {
5784       case SC_None:
5785         break;
5786       case SC_Static:
5787         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5788              diag::err_static_out_of_line)
5789           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5790         break;
5791       case SC_Auto:
5792       case SC_Register:
5793       case SC_Extern:
5794         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5795         // to names of variables declared in a block or to function parameters.
5796         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5797         // of class members
5798 
5799         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5800              diag::err_storage_class_for_static_member)
5801           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5802         break;
5803       case SC_PrivateExtern:
5804         llvm_unreachable("C storage class in c++!");
5805       }
5806     }
5807 
5808     if (SC == SC_Static && CurContext->isRecord()) {
5809       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5810         if (RD->isLocalClass())
5811           Diag(D.getIdentifierLoc(),
5812                diag::err_static_data_member_not_allowed_in_local_class)
5813             << Name << RD->getDeclName();
5814 
5815         // C++98 [class.union]p1: If a union contains a static data member,
5816         // the program is ill-formed. C++11 drops this restriction.
5817         if (RD->isUnion())
5818           Diag(D.getIdentifierLoc(),
5819                getLangOpts().CPlusPlus11
5820                  ? diag::warn_cxx98_compat_static_data_member_in_union
5821                  : diag::ext_static_data_member_in_union) << Name;
5822         // We conservatively disallow static data members in anonymous structs.
5823         else if (!RD->getDeclName())
5824           Diag(D.getIdentifierLoc(),
5825                diag::err_static_data_member_not_allowed_in_anon_struct)
5826             << Name << RD->isUnion();
5827       }
5828     }
5829 
5830     // Match up the template parameter lists with the scope specifier, then
5831     // determine whether we have a template or a template specialization.
5832     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5833         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5834         D.getCXXScopeSpec(),
5835         D.getName().getKind() == UnqualifiedId::IK_TemplateId
5836             ? D.getName().TemplateId
5837             : nullptr,
5838         TemplateParamLists,
5839         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5840 
5841     if (TemplateParams) {
5842       if (!TemplateParams->size() &&
5843           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5844         // There is an extraneous 'template<>' for this variable. Complain
5845         // about it, but allow the declaration of the variable.
5846         Diag(TemplateParams->getTemplateLoc(),
5847              diag::err_template_variable_noparams)
5848           << II
5849           << SourceRange(TemplateParams->getTemplateLoc(),
5850                          TemplateParams->getRAngleLoc());
5851         TemplateParams = nullptr;
5852       } else {
5853         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5854           // This is an explicit specialization or a partial specialization.
5855           // FIXME: Check that we can declare a specialization here.
5856           IsVariableTemplateSpecialization = true;
5857           IsPartialSpecialization = TemplateParams->size() > 0;
5858         } else { // if (TemplateParams->size() > 0)
5859           // This is a template declaration.
5860           IsVariableTemplate = true;
5861 
5862           // Check that we can declare a template here.
5863           if (CheckTemplateDeclScope(S, TemplateParams))
5864             return nullptr;
5865 
5866           // Only C++1y supports variable templates (N3651).
5867           Diag(D.getIdentifierLoc(),
5868                getLangOpts().CPlusPlus14
5869                    ? diag::warn_cxx11_compat_variable_template
5870                    : diag::ext_variable_template);
5871         }
5872       }
5873     } else {
5874       assert(
5875           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5876           "should have a 'template<>' for this decl");
5877     }
5878 
5879     if (IsVariableTemplateSpecialization) {
5880       SourceLocation TemplateKWLoc =
5881           TemplateParamLists.size() > 0
5882               ? TemplateParamLists[0]->getTemplateLoc()
5883               : SourceLocation();
5884       DeclResult Res = ActOnVarTemplateSpecialization(
5885           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5886           IsPartialSpecialization);
5887       if (Res.isInvalid())
5888         return nullptr;
5889       NewVD = cast<VarDecl>(Res.get());
5890       AddToScope = false;
5891     } else
5892       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5893                               D.getIdentifierLoc(), II, R, TInfo, SC);
5894 
5895     // If this is supposed to be a variable template, create it as such.
5896     if (IsVariableTemplate) {
5897       NewTemplate =
5898           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5899                                   TemplateParams, NewVD);
5900       NewVD->setDescribedVarTemplate(NewTemplate);
5901     }
5902 
5903     // If this decl has an auto type in need of deduction, make a note of the
5904     // Decl so we can diagnose uses of it in its own initializer.
5905     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5906       ParsingInitForAutoVars.insert(NewVD);
5907 
5908     if (D.isInvalidType() || Invalid) {
5909       NewVD->setInvalidDecl();
5910       if (NewTemplate)
5911         NewTemplate->setInvalidDecl();
5912     }
5913 
5914     SetNestedNameSpecifier(NewVD, D);
5915 
5916     // If we have any template parameter lists that don't directly belong to
5917     // the variable (matching the scope specifier), store them.
5918     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5919     if (TemplateParamLists.size() > VDTemplateParamLists)
5920       NewVD->setTemplateParameterListsInfo(
5921           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
5922 
5923     if (D.getDeclSpec().isConstexprSpecified())
5924       NewVD->setConstexpr(true);
5925 
5926     if (D.getDeclSpec().isConceptSpecified()) {
5927       NewVD->setConcept(true);
5928 
5929       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
5930       // be declared with the thread_local, inline, friend, or constexpr
5931       // specifiers, [...]
5932       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
5933         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5934              diag::err_concept_decl_invalid_specifiers)
5935             << 0 << 0;
5936         NewVD->setInvalidDecl(true);
5937       }
5938 
5939       if (D.getDeclSpec().isConstexprSpecified()) {
5940         Diag(D.getDeclSpec().getConstexprSpecLoc(),
5941              diag::err_concept_decl_invalid_specifiers)
5942             << 0 << 3;
5943         NewVD->setInvalidDecl(true);
5944       }
5945     }
5946   }
5947 
5948   // Set the lexical context. If the declarator has a C++ scope specifier, the
5949   // lexical context will be different from the semantic context.
5950   NewVD->setLexicalDeclContext(CurContext);
5951   if (NewTemplate)
5952     NewTemplate->setLexicalDeclContext(CurContext);
5953 
5954   if (IsLocalExternDecl)
5955     NewVD->setLocalExternDecl();
5956 
5957   bool EmitTLSUnsupportedError = false;
5958   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5959     // C++11 [dcl.stc]p4:
5960     //   When thread_local is applied to a variable of block scope the
5961     //   storage-class-specifier static is implied if it does not appear
5962     //   explicitly.
5963     // Core issue: 'static' is not implied if the variable is declared
5964     //   'extern'.
5965     if (NewVD->hasLocalStorage() &&
5966         (SCSpec != DeclSpec::SCS_unspecified ||
5967          TSCS != DeclSpec::TSCS_thread_local ||
5968          !DC->isFunctionOrMethod()))
5969       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5970            diag::err_thread_non_global)
5971         << DeclSpec::getSpecifierName(TSCS);
5972     else if (!Context.getTargetInfo().isTLSSupported()) {
5973       if (getLangOpts().CUDA) {
5974         // Postpone error emission until we've collected attributes required to
5975         // figure out whether it's a host or device variable and whether the
5976         // error should be ignored.
5977         EmitTLSUnsupportedError = true;
5978         // We still need to mark the variable as TLS so it shows up in AST with
5979         // proper storage class for other tools to use even if we're not going
5980         // to emit any code for it.
5981         NewVD->setTSCSpec(TSCS);
5982       } else
5983         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5984              diag::err_thread_unsupported);
5985     } else
5986       NewVD->setTSCSpec(TSCS);
5987   }
5988 
5989   // C99 6.7.4p3
5990   //   An inline definition of a function with external linkage shall
5991   //   not contain a definition of a modifiable object with static or
5992   //   thread storage duration...
5993   // We only apply this when the function is required to be defined
5994   // elsewhere, i.e. when the function is not 'extern inline'.  Note
5995   // that a local variable with thread storage duration still has to
5996   // be marked 'static'.  Also note that it's possible to get these
5997   // semantics in C++ using __attribute__((gnu_inline)).
5998   if (SC == SC_Static && S->getFnParent() != nullptr &&
5999       !NewVD->getType().isConstQualified()) {
6000     FunctionDecl *CurFD = getCurFunctionDecl();
6001     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6002       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6003            diag::warn_static_local_in_extern_inline);
6004       MaybeSuggestAddingStaticToDecl(CurFD);
6005     }
6006   }
6007 
6008   if (D.getDeclSpec().isModulePrivateSpecified()) {
6009     if (IsVariableTemplateSpecialization)
6010       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6011           << (IsPartialSpecialization ? 1 : 0)
6012           << FixItHint::CreateRemoval(
6013                  D.getDeclSpec().getModulePrivateSpecLoc());
6014     else if (IsExplicitSpecialization)
6015       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6016         << 2
6017         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6018     else if (NewVD->hasLocalStorage())
6019       Diag(NewVD->getLocation(), diag::err_module_private_local)
6020         << 0 << NewVD->getDeclName()
6021         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6022         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6023     else {
6024       NewVD->setModulePrivate();
6025       if (NewTemplate)
6026         NewTemplate->setModulePrivate();
6027     }
6028   }
6029 
6030   // Handle attributes prior to checking for duplicates in MergeVarDecl
6031   ProcessDeclAttributes(S, NewVD, D);
6032 
6033   if (getLangOpts().CUDA) {
6034     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6035       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6036            diag::err_thread_unsupported);
6037     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6038     // storage [duration]."
6039     if (SC == SC_None && S->getFnParent() != nullptr &&
6040         (NewVD->hasAttr<CUDASharedAttr>() ||
6041          NewVD->hasAttr<CUDAConstantAttr>())) {
6042       NewVD->setStorageClass(SC_Static);
6043     }
6044   }
6045 
6046   // Ensure that dllimport globals without explicit storage class are treated as
6047   // extern. The storage class is set above using parsed attributes. Now we can
6048   // check the VarDecl itself.
6049   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6050          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6051          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6052 
6053   // In auto-retain/release, infer strong retension for variables of
6054   // retainable type.
6055   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6056     NewVD->setInvalidDecl();
6057 
6058   // Handle GNU asm-label extension (encoded as an attribute).
6059   if (Expr *E = (Expr*)D.getAsmLabel()) {
6060     // The parser guarantees this is a string.
6061     StringLiteral *SE = cast<StringLiteral>(E);
6062     StringRef Label = SE->getString();
6063     if (S->getFnParent() != nullptr) {
6064       switch (SC) {
6065       case SC_None:
6066       case SC_Auto:
6067         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6068         break;
6069       case SC_Register:
6070         // Local Named register
6071         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6072             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6073           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6074         break;
6075       case SC_Static:
6076       case SC_Extern:
6077       case SC_PrivateExtern:
6078         break;
6079       }
6080     } else if (SC == SC_Register) {
6081       // Global Named register
6082       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6083         const auto &TI = Context.getTargetInfo();
6084         bool HasSizeMismatch;
6085 
6086         if (!TI.isValidGCCRegisterName(Label))
6087           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6088         else if (!TI.validateGlobalRegisterVariable(Label,
6089                                                     Context.getTypeSize(R),
6090                                                     HasSizeMismatch))
6091           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6092         else if (HasSizeMismatch)
6093           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6094       }
6095 
6096       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6097         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6098         NewVD->setInvalidDecl(true);
6099       }
6100     }
6101 
6102     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6103                                                 Context, Label, 0));
6104   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6105     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6106       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6107     if (I != ExtnameUndeclaredIdentifiers.end()) {
6108       if (isDeclExternC(NewVD)) {
6109         NewVD->addAttr(I->second);
6110         ExtnameUndeclaredIdentifiers.erase(I);
6111       } else
6112         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6113             << /*Variable*/1 << NewVD;
6114     }
6115   }
6116 
6117   // Diagnose shadowed variables before filtering for scope.
6118   if (D.getCXXScopeSpec().isEmpty())
6119     CheckShadow(S, NewVD, Previous);
6120 
6121   // Don't consider existing declarations that are in a different
6122   // scope and are out-of-semantic-context declarations (if the new
6123   // declaration has linkage).
6124   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6125                        D.getCXXScopeSpec().isNotEmpty() ||
6126                        IsExplicitSpecialization ||
6127                        IsVariableTemplateSpecialization);
6128 
6129   // Check whether the previous declaration is in the same block scope. This
6130   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6131   if (getLangOpts().CPlusPlus &&
6132       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6133     NewVD->setPreviousDeclInSameBlockScope(
6134         Previous.isSingleResult() && !Previous.isShadowed() &&
6135         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6136 
6137   if (!getLangOpts().CPlusPlus) {
6138     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6139   } else {
6140     // If this is an explicit specialization of a static data member, check it.
6141     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6142         CheckMemberSpecialization(NewVD, Previous))
6143       NewVD->setInvalidDecl();
6144 
6145     // Merge the decl with the existing one if appropriate.
6146     if (!Previous.empty()) {
6147       if (Previous.isSingleResult() &&
6148           isa<FieldDecl>(Previous.getFoundDecl()) &&
6149           D.getCXXScopeSpec().isSet()) {
6150         // The user tried to define a non-static data member
6151         // out-of-line (C++ [dcl.meaning]p1).
6152         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6153           << D.getCXXScopeSpec().getRange();
6154         Previous.clear();
6155         NewVD->setInvalidDecl();
6156       }
6157     } else if (D.getCXXScopeSpec().isSet()) {
6158       // No previous declaration in the qualifying scope.
6159       Diag(D.getIdentifierLoc(), diag::err_no_member)
6160         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6161         << D.getCXXScopeSpec().getRange();
6162       NewVD->setInvalidDecl();
6163     }
6164 
6165     if (!IsVariableTemplateSpecialization)
6166       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6167 
6168     if (NewTemplate) {
6169       VarTemplateDecl *PrevVarTemplate =
6170           NewVD->getPreviousDecl()
6171               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6172               : nullptr;
6173 
6174       // Check the template parameter list of this declaration, possibly
6175       // merging in the template parameter list from the previous variable
6176       // template declaration.
6177       if (CheckTemplateParameterList(
6178               TemplateParams,
6179               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6180                               : nullptr,
6181               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6182                DC->isDependentContext())
6183                   ? TPC_ClassTemplateMember
6184                   : TPC_VarTemplate))
6185         NewVD->setInvalidDecl();
6186 
6187       // If we are providing an explicit specialization of a static variable
6188       // template, make a note of that.
6189       if (PrevVarTemplate &&
6190           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6191         PrevVarTemplate->setMemberSpecialization();
6192     }
6193   }
6194 
6195   ProcessPragmaWeak(S, NewVD);
6196 
6197   // If this is the first declaration of an extern C variable, update
6198   // the map of such variables.
6199   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6200       isIncompleteDeclExternC(*this, NewVD))
6201     RegisterLocallyScopedExternCDecl(NewVD, S);
6202 
6203   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6204     Decl *ManglingContextDecl;
6205     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6206             NewVD->getDeclContext(), ManglingContextDecl)) {
6207       Context.setManglingNumber(
6208           NewVD, MCtx->getManglingNumber(
6209                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6210       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6211     }
6212   }
6213 
6214   // Special handling of variable named 'main'.
6215   if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6216       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6217       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6218 
6219     // C++ [basic.start.main]p3
6220     // A program that declares a variable main at global scope is ill-formed.
6221     if (getLangOpts().CPlusPlus)
6222       Diag(D.getLocStart(), diag::err_main_global_variable);
6223 
6224     // In C, and external-linkage variable named main results in undefined
6225     // behavior.
6226     else if (NewVD->hasExternalFormalLinkage())
6227       Diag(D.getLocStart(), diag::warn_main_redefined);
6228   }
6229 
6230   if (D.isRedeclaration() && !Previous.empty()) {
6231     checkDLLAttributeRedeclaration(
6232         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6233         IsExplicitSpecialization);
6234   }
6235 
6236   if (NewTemplate) {
6237     if (NewVD->isInvalidDecl())
6238       NewTemplate->setInvalidDecl();
6239     ActOnDocumentableDecl(NewTemplate);
6240     return NewTemplate;
6241   }
6242 
6243   return NewVD;
6244 }
6245 
6246 /// \brief Diagnose variable or built-in function shadowing.  Implements
6247 /// -Wshadow.
6248 ///
6249 /// This method is called whenever a VarDecl is added to a "useful"
6250 /// scope.
6251 ///
6252 /// \param S the scope in which the shadowing name is being declared
6253 /// \param R the lookup of the name
6254 ///
6255 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6256   // Return if warning is ignored.
6257   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6258     return;
6259 
6260   // Don't diagnose declarations at file scope.
6261   if (D->hasGlobalStorage())
6262     return;
6263 
6264   DeclContext *NewDC = D->getDeclContext();
6265 
6266   // Only diagnose if we're shadowing an unambiguous field or variable.
6267   if (R.getResultKind() != LookupResult::Found)
6268     return;
6269 
6270   NamedDecl* ShadowedDecl = R.getFoundDecl();
6271   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6272     return;
6273 
6274   // Fields are not shadowed by variables in C++ static methods.
6275   if (isa<FieldDecl>(ShadowedDecl))
6276     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6277       if (MD->isStatic())
6278         return;
6279 
6280   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6281     if (shadowedVar->isExternC()) {
6282       // For shadowing external vars, make sure that we point to the global
6283       // declaration, not a locally scoped extern declaration.
6284       for (auto I : shadowedVar->redecls())
6285         if (I->isFileVarDecl()) {
6286           ShadowedDecl = I;
6287           break;
6288         }
6289     }
6290 
6291   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6292 
6293   // Only warn about certain kinds of shadowing for class members.
6294   if (NewDC && NewDC->isRecord()) {
6295     // In particular, don't warn about shadowing non-class members.
6296     if (!OldDC->isRecord())
6297       return;
6298 
6299     // TODO: should we warn about static data members shadowing
6300     // static data members from base classes?
6301 
6302     // TODO: don't diagnose for inaccessible shadowed members.
6303     // This is hard to do perfectly because we might friend the
6304     // shadowing context, but that's just a false negative.
6305   }
6306 
6307   // Determine what kind of declaration we're shadowing.
6308   unsigned Kind;
6309   if (isa<RecordDecl>(OldDC)) {
6310     if (isa<FieldDecl>(ShadowedDecl))
6311       Kind = 3; // field
6312     else
6313       Kind = 2; // static data member
6314   } else if (OldDC->isFileContext())
6315     Kind = 1; // global
6316   else
6317     Kind = 0; // local
6318 
6319   DeclarationName Name = R.getLookupName();
6320 
6321   // Emit warning and note.
6322   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6323     return;
6324   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6325   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6326 }
6327 
6328 /// \brief Check -Wshadow without the advantage of a previous lookup.
6329 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6330   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6331     return;
6332 
6333   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6334                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6335   LookupName(R, S);
6336   CheckShadow(S, D, R);
6337 }
6338 
6339 /// Check for conflict between this global or extern "C" declaration and
6340 /// previous global or extern "C" declarations. This is only used in C++.
6341 template<typename T>
6342 static bool checkGlobalOrExternCConflict(
6343     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6344   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6345   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6346 
6347   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6348     // The common case: this global doesn't conflict with any extern "C"
6349     // declaration.
6350     return false;
6351   }
6352 
6353   if (Prev) {
6354     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6355       // Both the old and new declarations have C language linkage. This is a
6356       // redeclaration.
6357       Previous.clear();
6358       Previous.addDecl(Prev);
6359       return true;
6360     }
6361 
6362     // This is a global, non-extern "C" declaration, and there is a previous
6363     // non-global extern "C" declaration. Diagnose if this is a variable
6364     // declaration.
6365     if (!isa<VarDecl>(ND))
6366       return false;
6367   } else {
6368     // The declaration is extern "C". Check for any declaration in the
6369     // translation unit which might conflict.
6370     if (IsGlobal) {
6371       // We have already performed the lookup into the translation unit.
6372       IsGlobal = false;
6373       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6374            I != E; ++I) {
6375         if (isa<VarDecl>(*I)) {
6376           Prev = *I;
6377           break;
6378         }
6379       }
6380     } else {
6381       DeclContext::lookup_result R =
6382           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6383       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6384            I != E; ++I) {
6385         if (isa<VarDecl>(*I)) {
6386           Prev = *I;
6387           break;
6388         }
6389         // FIXME: If we have any other entity with this name in global scope,
6390         // the declaration is ill-formed, but that is a defect: it breaks the
6391         // 'stat' hack, for instance. Only variables can have mangled name
6392         // clashes with extern "C" declarations, so only they deserve a
6393         // diagnostic.
6394       }
6395     }
6396 
6397     if (!Prev)
6398       return false;
6399   }
6400 
6401   // Use the first declaration's location to ensure we point at something which
6402   // is lexically inside an extern "C" linkage-spec.
6403   assert(Prev && "should have found a previous declaration to diagnose");
6404   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6405     Prev = FD->getFirstDecl();
6406   else
6407     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6408 
6409   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6410     << IsGlobal << ND;
6411   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6412     << IsGlobal;
6413   return false;
6414 }
6415 
6416 /// Apply special rules for handling extern "C" declarations. Returns \c true
6417 /// if we have found that this is a redeclaration of some prior entity.
6418 ///
6419 /// Per C++ [dcl.link]p6:
6420 ///   Two declarations [for a function or variable] with C language linkage
6421 ///   with the same name that appear in different scopes refer to the same
6422 ///   [entity]. An entity with C language linkage shall not be declared with
6423 ///   the same name as an entity in global scope.
6424 template<typename T>
6425 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6426                                                   LookupResult &Previous) {
6427   if (!S.getLangOpts().CPlusPlus) {
6428     // In C, when declaring a global variable, look for a corresponding 'extern'
6429     // variable declared in function scope. We don't need this in C++, because
6430     // we find local extern decls in the surrounding file-scope DeclContext.
6431     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6432       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6433         Previous.clear();
6434         Previous.addDecl(Prev);
6435         return true;
6436       }
6437     }
6438     return false;
6439   }
6440 
6441   // A declaration in the translation unit can conflict with an extern "C"
6442   // declaration.
6443   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6444     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6445 
6446   // An extern "C" declaration can conflict with a declaration in the
6447   // translation unit or can be a redeclaration of an extern "C" declaration
6448   // in another scope.
6449   if (isIncompleteDeclExternC(S,ND))
6450     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6451 
6452   // Neither global nor extern "C": nothing to do.
6453   return false;
6454 }
6455 
6456 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6457   // If the decl is already known invalid, don't check it.
6458   if (NewVD->isInvalidDecl())
6459     return;
6460 
6461   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6462   QualType T = TInfo->getType();
6463 
6464   // Defer checking an 'auto' type until its initializer is attached.
6465   if (T->isUndeducedType())
6466     return;
6467 
6468   if (NewVD->hasAttrs())
6469     CheckAlignasUnderalignment(NewVD);
6470 
6471   if (T->isObjCObjectType()) {
6472     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6473       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6474     T = Context.getObjCObjectPointerType(T);
6475     NewVD->setType(T);
6476   }
6477 
6478   // Emit an error if an address space was applied to decl with local storage.
6479   // This includes arrays of objects with address space qualifiers, but not
6480   // automatic variables that point to other address spaces.
6481   // ISO/IEC TR 18037 S5.1.2
6482   if (!getLangOpts().OpenCL
6483       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6484     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6485     NewVD->setInvalidDecl();
6486     return;
6487   }
6488 
6489   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6490   // scope.
6491   if (getLangOpts().OpenCLVersion == 120 &&
6492       !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6493       NewVD->isStaticLocal()) {
6494     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6495     NewVD->setInvalidDecl();
6496     return;
6497   }
6498 
6499   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6500   // __constant address space.
6501   // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6502   // variables inside a function can also be declared in the global
6503   // address space.
6504   if (getLangOpts().OpenCL) {
6505     if (NewVD->isFileVarDecl()) {
6506       if (!T->isSamplerT() &&
6507           !(T.getAddressSpace() == LangAS::opencl_constant ||
6508             (T.getAddressSpace() == LangAS::opencl_global &&
6509              getLangOpts().OpenCLVersion == 200))) {
6510         if (getLangOpts().OpenCLVersion == 200)
6511           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6512               << "global or constant";
6513         else
6514           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6515               << "constant";
6516         NewVD->setInvalidDecl();
6517         return;
6518       }
6519     } else {
6520       // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6521       // variables inside a function can also be declared in the global
6522       // address space.
6523       if (NewVD->isStaticLocal() &&
6524           !(T.getAddressSpace() == LangAS::opencl_constant ||
6525             (T.getAddressSpace() == LangAS::opencl_global &&
6526              getLangOpts().OpenCLVersion == 200))) {
6527         if (getLangOpts().OpenCLVersion == 200)
6528           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6529               << "global or constant";
6530         else
6531           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6532               << "constant";
6533         NewVD->setInvalidDecl();
6534         return;
6535       }
6536       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6537       // in functions.
6538       if (T.getAddressSpace() == LangAS::opencl_constant ||
6539           T.getAddressSpace() == LangAS::opencl_local) {
6540         FunctionDecl *FD = getCurFunctionDecl();
6541         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6542           if (T.getAddressSpace() == LangAS::opencl_constant)
6543             Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable)
6544                 << "constant";
6545           else
6546             Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable)
6547                 << "local";
6548           NewVD->setInvalidDecl();
6549           return;
6550         }
6551       }
6552     }
6553   }
6554 
6555   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6556       && !NewVD->hasAttr<BlocksAttr>()) {
6557     if (getLangOpts().getGC() != LangOptions::NonGC)
6558       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6559     else {
6560       assert(!getLangOpts().ObjCAutoRefCount);
6561       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6562     }
6563   }
6564 
6565   bool isVM = T->isVariablyModifiedType();
6566   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6567       NewVD->hasAttr<BlocksAttr>())
6568     getCurFunction()->setHasBranchProtectedScope();
6569 
6570   if ((isVM && NewVD->hasLinkage()) ||
6571       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6572     bool SizeIsNegative;
6573     llvm::APSInt Oversized;
6574     TypeSourceInfo *FixedTInfo =
6575       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6576                                                     SizeIsNegative, Oversized);
6577     if (!FixedTInfo && T->isVariableArrayType()) {
6578       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6579       // FIXME: This won't give the correct result for
6580       // int a[10][n];
6581       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6582 
6583       if (NewVD->isFileVarDecl())
6584         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6585         << SizeRange;
6586       else if (NewVD->isStaticLocal())
6587         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6588         << SizeRange;
6589       else
6590         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6591         << SizeRange;
6592       NewVD->setInvalidDecl();
6593       return;
6594     }
6595 
6596     if (!FixedTInfo) {
6597       if (NewVD->isFileVarDecl())
6598         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6599       else
6600         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6601       NewVD->setInvalidDecl();
6602       return;
6603     }
6604 
6605     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6606     NewVD->setType(FixedTInfo->getType());
6607     NewVD->setTypeSourceInfo(FixedTInfo);
6608   }
6609 
6610   if (T->isVoidType()) {
6611     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6612     //                    of objects and functions.
6613     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6614       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6615         << T;
6616       NewVD->setInvalidDecl();
6617       return;
6618     }
6619   }
6620 
6621   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6622     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6623     NewVD->setInvalidDecl();
6624     return;
6625   }
6626 
6627   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6628     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6629     NewVD->setInvalidDecl();
6630     return;
6631   }
6632 
6633   if (NewVD->isConstexpr() && !T->isDependentType() &&
6634       RequireLiteralType(NewVD->getLocation(), T,
6635                          diag::err_constexpr_var_non_literal)) {
6636     NewVD->setInvalidDecl();
6637     return;
6638   }
6639 }
6640 
6641 /// \brief Perform semantic checking on a newly-created variable
6642 /// declaration.
6643 ///
6644 /// This routine performs all of the type-checking required for a
6645 /// variable declaration once it has been built. It is used both to
6646 /// check variables after they have been parsed and their declarators
6647 /// have been translated into a declaration, and to check variables
6648 /// that have been instantiated from a template.
6649 ///
6650 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6651 ///
6652 /// Returns true if the variable declaration is a redeclaration.
6653 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6654   CheckVariableDeclarationType(NewVD);
6655 
6656   // If the decl is already known invalid, don't check it.
6657   if (NewVD->isInvalidDecl())
6658     return false;
6659 
6660   // If we did not find anything by this name, look for a non-visible
6661   // extern "C" declaration with the same name.
6662   if (Previous.empty() &&
6663       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6664     Previous.setShadowed();
6665 
6666   if (!Previous.empty()) {
6667     MergeVarDecl(NewVD, Previous);
6668     return true;
6669   }
6670   return false;
6671 }
6672 
6673 namespace {
6674 struct FindOverriddenMethod {
6675   Sema *S;
6676   CXXMethodDecl *Method;
6677 
6678   /// Member lookup function that determines whether a given C++
6679   /// method overrides a method in a base class, to be used with
6680   /// CXXRecordDecl::lookupInBases().
6681   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6682     RecordDecl *BaseRecord =
6683         Specifier->getType()->getAs<RecordType>()->getDecl();
6684 
6685     DeclarationName Name = Method->getDeclName();
6686 
6687     // FIXME: Do we care about other names here too?
6688     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6689       // We really want to find the base class destructor here.
6690       QualType T = S->Context.getTypeDeclType(BaseRecord);
6691       CanQualType CT = S->Context.getCanonicalType(T);
6692 
6693       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
6694     }
6695 
6696     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6697          Path.Decls = Path.Decls.slice(1)) {
6698       NamedDecl *D = Path.Decls.front();
6699       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6700         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
6701           return true;
6702       }
6703     }
6704 
6705     return false;
6706   }
6707 };
6708 
6709 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6710 } // end anonymous namespace
6711 
6712 /// \brief Report an error regarding overriding, along with any relevant
6713 /// overriden methods.
6714 ///
6715 /// \param DiagID the primary error to report.
6716 /// \param MD the overriding method.
6717 /// \param OEK which overrides to include as notes.
6718 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6719                             OverrideErrorKind OEK = OEK_All) {
6720   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6721   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6722                                       E = MD->end_overridden_methods();
6723        I != E; ++I) {
6724     // This check (& the OEK parameter) could be replaced by a predicate, but
6725     // without lambdas that would be overkill. This is still nicer than writing
6726     // out the diag loop 3 times.
6727     if ((OEK == OEK_All) ||
6728         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6729         (OEK == OEK_Deleted && (*I)->isDeleted()))
6730       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6731   }
6732 }
6733 
6734 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6735 /// and if so, check that it's a valid override and remember it.
6736 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6737   // Look for methods in base classes that this method might override.
6738   CXXBasePaths Paths;
6739   FindOverriddenMethod FOM;
6740   FOM.Method = MD;
6741   FOM.S = this;
6742   bool hasDeletedOverridenMethods = false;
6743   bool hasNonDeletedOverridenMethods = false;
6744   bool AddedAny = false;
6745   if (DC->lookupInBases(FOM, Paths)) {
6746     for (auto *I : Paths.found_decls()) {
6747       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6748         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6749         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6750             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6751             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6752             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6753           hasDeletedOverridenMethods |= OldMD->isDeleted();
6754           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6755           AddedAny = true;
6756         }
6757       }
6758     }
6759   }
6760 
6761   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6762     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6763   }
6764   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6765     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6766   }
6767 
6768   return AddedAny;
6769 }
6770 
6771 namespace {
6772   // Struct for holding all of the extra arguments needed by
6773   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6774   struct ActOnFDArgs {
6775     Scope *S;
6776     Declarator &D;
6777     MultiTemplateParamsArg TemplateParamLists;
6778     bool AddToScope;
6779   };
6780 }
6781 
6782 namespace {
6783 
6784 // Callback to only accept typo corrections that have a non-zero edit distance.
6785 // Also only accept corrections that have the same parent decl.
6786 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6787  public:
6788   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6789                             CXXRecordDecl *Parent)
6790       : Context(Context), OriginalFD(TypoFD),
6791         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6792 
6793   bool ValidateCandidate(const TypoCorrection &candidate) override {
6794     if (candidate.getEditDistance() == 0)
6795       return false;
6796 
6797     SmallVector<unsigned, 1> MismatchedParams;
6798     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6799                                           CDeclEnd = candidate.end();
6800          CDecl != CDeclEnd; ++CDecl) {
6801       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6802 
6803       if (FD && !FD->hasBody() &&
6804           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6805         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6806           CXXRecordDecl *Parent = MD->getParent();
6807           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6808             return true;
6809         } else if (!ExpectedParent) {
6810           return true;
6811         }
6812       }
6813     }
6814 
6815     return false;
6816   }
6817 
6818  private:
6819   ASTContext &Context;
6820   FunctionDecl *OriginalFD;
6821   CXXRecordDecl *ExpectedParent;
6822 };
6823 
6824 }
6825 
6826 /// \brief Generate diagnostics for an invalid function redeclaration.
6827 ///
6828 /// This routine handles generating the diagnostic messages for an invalid
6829 /// function redeclaration, including finding possible similar declarations
6830 /// or performing typo correction if there are no previous declarations with
6831 /// the same name.
6832 ///
6833 /// Returns a NamedDecl iff typo correction was performed and substituting in
6834 /// the new declaration name does not cause new errors.
6835 static NamedDecl *DiagnoseInvalidRedeclaration(
6836     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6837     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6838   DeclarationName Name = NewFD->getDeclName();
6839   DeclContext *NewDC = NewFD->getDeclContext();
6840   SmallVector<unsigned, 1> MismatchedParams;
6841   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6842   TypoCorrection Correction;
6843   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6844   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6845                                    : diag::err_member_decl_does_not_match;
6846   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6847                     IsLocalFriend ? Sema::LookupLocalFriendName
6848                                   : Sema::LookupOrdinaryName,
6849                     Sema::ForRedeclaration);
6850 
6851   NewFD->setInvalidDecl();
6852   if (IsLocalFriend)
6853     SemaRef.LookupName(Prev, S);
6854   else
6855     SemaRef.LookupQualifiedName(Prev, NewDC);
6856   assert(!Prev.isAmbiguous() &&
6857          "Cannot have an ambiguity in previous-declaration lookup");
6858   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6859   if (!Prev.empty()) {
6860     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6861          Func != FuncEnd; ++Func) {
6862       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6863       if (FD &&
6864           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6865         // Add 1 to the index so that 0 can mean the mismatch didn't
6866         // involve a parameter
6867         unsigned ParamNum =
6868             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6869         NearMatches.push_back(std::make_pair(FD, ParamNum));
6870       }
6871     }
6872   // If the qualified name lookup yielded nothing, try typo correction
6873   } else if ((Correction = SemaRef.CorrectTypo(
6874                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6875                   &ExtraArgs.D.getCXXScopeSpec(),
6876                   llvm::make_unique<DifferentNameValidatorCCC>(
6877                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
6878                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6879     // Set up everything for the call to ActOnFunctionDeclarator
6880     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6881                               ExtraArgs.D.getIdentifierLoc());
6882     Previous.clear();
6883     Previous.setLookupName(Correction.getCorrection());
6884     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6885                                     CDeclEnd = Correction.end();
6886          CDecl != CDeclEnd; ++CDecl) {
6887       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6888       if (FD && !FD->hasBody() &&
6889           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6890         Previous.addDecl(FD);
6891       }
6892     }
6893     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6894 
6895     NamedDecl *Result;
6896     // Retry building the function declaration with the new previous
6897     // declarations, and with errors suppressed.
6898     {
6899       // Trap errors.
6900       Sema::SFINAETrap Trap(SemaRef);
6901 
6902       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6903       // pieces need to verify the typo-corrected C++ declaration and hopefully
6904       // eliminate the need for the parameter pack ExtraArgs.
6905       Result = SemaRef.ActOnFunctionDeclarator(
6906           ExtraArgs.S, ExtraArgs.D,
6907           Correction.getCorrectionDecl()->getDeclContext(),
6908           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6909           ExtraArgs.AddToScope);
6910 
6911       if (Trap.hasErrorOccurred())
6912         Result = nullptr;
6913     }
6914 
6915     if (Result) {
6916       // Determine which correction we picked.
6917       Decl *Canonical = Result->getCanonicalDecl();
6918       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6919            I != E; ++I)
6920         if ((*I)->getCanonicalDecl() == Canonical)
6921           Correction.setCorrectionDecl(*I);
6922 
6923       SemaRef.diagnoseTypo(
6924           Correction,
6925           SemaRef.PDiag(IsLocalFriend
6926                           ? diag::err_no_matching_local_friend_suggest
6927                           : diag::err_member_decl_does_not_match_suggest)
6928             << Name << NewDC << IsDefinition);
6929       return Result;
6930     }
6931 
6932     // Pretend the typo correction never occurred
6933     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6934                               ExtraArgs.D.getIdentifierLoc());
6935     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6936     Previous.clear();
6937     Previous.setLookupName(Name);
6938   }
6939 
6940   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6941       << Name << NewDC << IsDefinition << NewFD->getLocation();
6942 
6943   bool NewFDisConst = false;
6944   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6945     NewFDisConst = NewMD->isConst();
6946 
6947   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6948        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6949        NearMatch != NearMatchEnd; ++NearMatch) {
6950     FunctionDecl *FD = NearMatch->first;
6951     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6952     bool FDisConst = MD && MD->isConst();
6953     bool IsMember = MD || !IsLocalFriend;
6954 
6955     // FIXME: These notes are poorly worded for the local friend case.
6956     if (unsigned Idx = NearMatch->second) {
6957       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6958       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6959       if (Loc.isInvalid()) Loc = FD->getLocation();
6960       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6961                                  : diag::note_local_decl_close_param_match)
6962         << Idx << FDParam->getType()
6963         << NewFD->getParamDecl(Idx - 1)->getType();
6964     } else if (FDisConst != NewFDisConst) {
6965       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6966           << NewFDisConst << FD->getSourceRange().getEnd();
6967     } else
6968       SemaRef.Diag(FD->getLocation(),
6969                    IsMember ? diag::note_member_def_close_match
6970                             : diag::note_local_decl_close_match);
6971   }
6972   return nullptr;
6973 }
6974 
6975 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
6976   switch (D.getDeclSpec().getStorageClassSpec()) {
6977   default: llvm_unreachable("Unknown storage class!");
6978   case DeclSpec::SCS_auto:
6979   case DeclSpec::SCS_register:
6980   case DeclSpec::SCS_mutable:
6981     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6982                  diag::err_typecheck_sclass_func);
6983     D.setInvalidType();
6984     break;
6985   case DeclSpec::SCS_unspecified: break;
6986   case DeclSpec::SCS_extern:
6987     if (D.getDeclSpec().isExternInLinkageSpec())
6988       return SC_None;
6989     return SC_Extern;
6990   case DeclSpec::SCS_static: {
6991     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6992       // C99 6.7.1p5:
6993       //   The declaration of an identifier for a function that has
6994       //   block scope shall have no explicit storage-class specifier
6995       //   other than extern
6996       // See also (C++ [dcl.stc]p4).
6997       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6998                    diag::err_static_block_func);
6999       break;
7000     } else
7001       return SC_Static;
7002   }
7003   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7004   }
7005 
7006   // No explicit storage class has already been returned
7007   return SC_None;
7008 }
7009 
7010 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7011                                            DeclContext *DC, QualType &R,
7012                                            TypeSourceInfo *TInfo,
7013                                            StorageClass SC,
7014                                            bool &IsVirtualOkay) {
7015   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7016   DeclarationName Name = NameInfo.getName();
7017 
7018   FunctionDecl *NewFD = nullptr;
7019   bool isInline = D.getDeclSpec().isInlineSpecified();
7020 
7021   if (!SemaRef.getLangOpts().CPlusPlus) {
7022     // Determine whether the function was written with a
7023     // prototype. This true when:
7024     //   - there is a prototype in the declarator, or
7025     //   - the type R of the function is some kind of typedef or other reference
7026     //     to a type name (which eventually refers to a function type).
7027     bool HasPrototype =
7028       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7029       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7030 
7031     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7032                                  D.getLocStart(), NameInfo, R,
7033                                  TInfo, SC, isInline,
7034                                  HasPrototype, false);
7035     if (D.isInvalidType())
7036       NewFD->setInvalidDecl();
7037 
7038     return NewFD;
7039   }
7040 
7041   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7042   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7043 
7044   // Check that the return type is not an abstract class type.
7045   // For record types, this is done by the AbstractClassUsageDiagnoser once
7046   // the class has been completely parsed.
7047   if (!DC->isRecord() &&
7048       SemaRef.RequireNonAbstractType(
7049           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7050           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7051     D.setInvalidType();
7052 
7053   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7054     // This is a C++ constructor declaration.
7055     assert(DC->isRecord() &&
7056            "Constructors can only be declared in a member context");
7057 
7058     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7059     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7060                                       D.getLocStart(), NameInfo,
7061                                       R, TInfo, isExplicit, isInline,
7062                                       /*isImplicitlyDeclared=*/false,
7063                                       isConstexpr);
7064 
7065   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7066     // This is a C++ destructor declaration.
7067     if (DC->isRecord()) {
7068       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7069       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7070       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7071                                         SemaRef.Context, Record,
7072                                         D.getLocStart(),
7073                                         NameInfo, R, TInfo, isInline,
7074                                         /*isImplicitlyDeclared=*/false);
7075 
7076       // If the class is complete, then we now create the implicit exception
7077       // specification. If the class is incomplete or dependent, we can't do
7078       // it yet.
7079       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7080           Record->getDefinition() && !Record->isBeingDefined() &&
7081           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7082         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7083       }
7084 
7085       IsVirtualOkay = true;
7086       return NewDD;
7087 
7088     } else {
7089       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7090       D.setInvalidType();
7091 
7092       // Create a FunctionDecl to satisfy the function definition parsing
7093       // code path.
7094       return FunctionDecl::Create(SemaRef.Context, DC,
7095                                   D.getLocStart(),
7096                                   D.getIdentifierLoc(), Name, R, TInfo,
7097                                   SC, isInline,
7098                                   /*hasPrototype=*/true, isConstexpr);
7099     }
7100 
7101   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7102     if (!DC->isRecord()) {
7103       SemaRef.Diag(D.getIdentifierLoc(),
7104            diag::err_conv_function_not_member);
7105       return nullptr;
7106     }
7107 
7108     SemaRef.CheckConversionDeclarator(D, R, SC);
7109     IsVirtualOkay = true;
7110     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7111                                      D.getLocStart(), NameInfo,
7112                                      R, TInfo, isInline, isExplicit,
7113                                      isConstexpr, SourceLocation());
7114 
7115   } else if (DC->isRecord()) {
7116     // If the name of the function is the same as the name of the record,
7117     // then this must be an invalid constructor that has a return type.
7118     // (The parser checks for a return type and makes the declarator a
7119     // constructor if it has no return type).
7120     if (Name.getAsIdentifierInfo() &&
7121         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7122       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7123         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7124         << SourceRange(D.getIdentifierLoc());
7125       return nullptr;
7126     }
7127 
7128     // This is a C++ method declaration.
7129     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7130                                                cast<CXXRecordDecl>(DC),
7131                                                D.getLocStart(), NameInfo, R,
7132                                                TInfo, SC, isInline,
7133                                                isConstexpr, SourceLocation());
7134     IsVirtualOkay = !Ret->isStatic();
7135     return Ret;
7136   } else {
7137     bool isFriend =
7138         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7139     if (!isFriend && SemaRef.CurContext->isRecord())
7140       return nullptr;
7141 
7142     // Determine whether the function was written with a
7143     // prototype. This true when:
7144     //   - we're in C++ (where every function has a prototype),
7145     return FunctionDecl::Create(SemaRef.Context, DC,
7146                                 D.getLocStart(),
7147                                 NameInfo, R, TInfo, SC, isInline,
7148                                 true/*HasPrototype*/, isConstexpr);
7149   }
7150 }
7151 
7152 enum OpenCLParamType {
7153   ValidKernelParam,
7154   PtrPtrKernelParam,
7155   PtrKernelParam,
7156   PrivatePtrKernelParam,
7157   InvalidKernelParam,
7158   RecordKernelParam
7159 };
7160 
7161 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7162   if (PT->isPointerType()) {
7163     QualType PointeeType = PT->getPointeeType();
7164     if (PointeeType->isPointerType())
7165       return PtrPtrKernelParam;
7166     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7167                                               : PtrKernelParam;
7168   }
7169 
7170   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7171   // be used as builtin types.
7172 
7173   if (PT->isImageType())
7174     return PtrKernelParam;
7175 
7176   if (PT->isBooleanType())
7177     return InvalidKernelParam;
7178 
7179   if (PT->isEventT())
7180     return InvalidKernelParam;
7181 
7182   if (PT->isHalfType())
7183     return InvalidKernelParam;
7184 
7185   if (PT->isRecordType())
7186     return RecordKernelParam;
7187 
7188   return ValidKernelParam;
7189 }
7190 
7191 static void checkIsValidOpenCLKernelParameter(
7192   Sema &S,
7193   Declarator &D,
7194   ParmVarDecl *Param,
7195   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7196   QualType PT = Param->getType();
7197 
7198   // Cache the valid types we encounter to avoid rechecking structs that are
7199   // used again
7200   if (ValidTypes.count(PT.getTypePtr()))
7201     return;
7202 
7203   switch (getOpenCLKernelParameterType(PT)) {
7204   case PtrPtrKernelParam:
7205     // OpenCL v1.2 s6.9.a:
7206     // A kernel function argument cannot be declared as a
7207     // pointer to a pointer type.
7208     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7209     D.setInvalidType();
7210     return;
7211 
7212   case PrivatePtrKernelParam:
7213     // OpenCL v1.2 s6.9.a:
7214     // A kernel function argument cannot be declared as a
7215     // pointer to the private address space.
7216     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7217     D.setInvalidType();
7218     return;
7219 
7220     // OpenCL v1.2 s6.9.k:
7221     // Arguments to kernel functions in a program cannot be declared with the
7222     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7223     // uintptr_t or a struct and/or union that contain fields declared to be
7224     // one of these built-in scalar types.
7225 
7226   case InvalidKernelParam:
7227     // OpenCL v1.2 s6.8 n:
7228     // A kernel function argument cannot be declared
7229     // of event_t type.
7230     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7231     D.setInvalidType();
7232     return;
7233 
7234   case PtrKernelParam:
7235   case ValidKernelParam:
7236     ValidTypes.insert(PT.getTypePtr());
7237     return;
7238 
7239   case RecordKernelParam:
7240     break;
7241   }
7242 
7243   // Track nested structs we will inspect
7244   SmallVector<const Decl *, 4> VisitStack;
7245 
7246   // Track where we are in the nested structs. Items will migrate from
7247   // VisitStack to HistoryStack as we do the DFS for bad field.
7248   SmallVector<const FieldDecl *, 4> HistoryStack;
7249   HistoryStack.push_back(nullptr);
7250 
7251   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7252   VisitStack.push_back(PD);
7253 
7254   assert(VisitStack.back() && "First decl null?");
7255 
7256   do {
7257     const Decl *Next = VisitStack.pop_back_val();
7258     if (!Next) {
7259       assert(!HistoryStack.empty());
7260       // Found a marker, we have gone up a level
7261       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7262         ValidTypes.insert(Hist->getType().getTypePtr());
7263 
7264       continue;
7265     }
7266 
7267     // Adds everything except the original parameter declaration (which is not a
7268     // field itself) to the history stack.
7269     const RecordDecl *RD;
7270     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7271       HistoryStack.push_back(Field);
7272       RD = Field->getType()->castAs<RecordType>()->getDecl();
7273     } else {
7274       RD = cast<RecordDecl>(Next);
7275     }
7276 
7277     // Add a null marker so we know when we've gone back up a level
7278     VisitStack.push_back(nullptr);
7279 
7280     for (const auto *FD : RD->fields()) {
7281       QualType QT = FD->getType();
7282 
7283       if (ValidTypes.count(QT.getTypePtr()))
7284         continue;
7285 
7286       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7287       if (ParamType == ValidKernelParam)
7288         continue;
7289 
7290       if (ParamType == RecordKernelParam) {
7291         VisitStack.push_back(FD);
7292         continue;
7293       }
7294 
7295       // OpenCL v1.2 s6.9.p:
7296       // Arguments to kernel functions that are declared to be a struct or union
7297       // do not allow OpenCL objects to be passed as elements of the struct or
7298       // union.
7299       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7300           ParamType == PrivatePtrKernelParam) {
7301         S.Diag(Param->getLocation(),
7302                diag::err_record_with_pointers_kernel_param)
7303           << PT->isUnionType()
7304           << PT;
7305       } else {
7306         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7307       }
7308 
7309       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7310         << PD->getDeclName();
7311 
7312       // We have an error, now let's go back up through history and show where
7313       // the offending field came from
7314       for (ArrayRef<const FieldDecl *>::const_iterator
7315                I = HistoryStack.begin() + 1,
7316                E = HistoryStack.end();
7317            I != E; ++I) {
7318         const FieldDecl *OuterField = *I;
7319         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7320           << OuterField->getType();
7321       }
7322 
7323       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7324         << QT->isPointerType()
7325         << QT;
7326       D.setInvalidType();
7327       return;
7328     }
7329   } while (!VisitStack.empty());
7330 }
7331 
7332 NamedDecl*
7333 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7334                               TypeSourceInfo *TInfo, LookupResult &Previous,
7335                               MultiTemplateParamsArg TemplateParamLists,
7336                               bool &AddToScope) {
7337   QualType R = TInfo->getType();
7338 
7339   assert(R.getTypePtr()->isFunctionType());
7340 
7341   // TODO: consider using NameInfo for diagnostic.
7342   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7343   DeclarationName Name = NameInfo.getName();
7344   StorageClass SC = getFunctionStorageClass(*this, D);
7345 
7346   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7347     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7348          diag::err_invalid_thread)
7349       << DeclSpec::getSpecifierName(TSCS);
7350 
7351   if (D.isFirstDeclarationOfMember())
7352     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7353                            D.getIdentifierLoc());
7354 
7355   bool isFriend = false;
7356   FunctionTemplateDecl *FunctionTemplate = nullptr;
7357   bool isExplicitSpecialization = false;
7358   bool isFunctionTemplateSpecialization = false;
7359 
7360   bool isDependentClassScopeExplicitSpecialization = false;
7361   bool HasExplicitTemplateArgs = false;
7362   TemplateArgumentListInfo TemplateArgs;
7363 
7364   bool isVirtualOkay = false;
7365 
7366   DeclContext *OriginalDC = DC;
7367   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7368 
7369   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7370                                               isVirtualOkay);
7371   if (!NewFD) return nullptr;
7372 
7373   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7374     NewFD->setTopLevelDeclInObjCContainer();
7375 
7376   // Set the lexical context. If this is a function-scope declaration, or has a
7377   // C++ scope specifier, or is the object of a friend declaration, the lexical
7378   // context will be different from the semantic context.
7379   NewFD->setLexicalDeclContext(CurContext);
7380 
7381   if (IsLocalExternDecl)
7382     NewFD->setLocalExternDecl();
7383 
7384   if (getLangOpts().CPlusPlus) {
7385     bool isInline = D.getDeclSpec().isInlineSpecified();
7386     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7387     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7388     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7389     bool isConcept = D.getDeclSpec().isConceptSpecified();
7390     isFriend = D.getDeclSpec().isFriendSpecified();
7391     if (isFriend && !isInline && D.isFunctionDefinition()) {
7392       // C++ [class.friend]p5
7393       //   A function can be defined in a friend declaration of a
7394       //   class . . . . Such a function is implicitly inline.
7395       NewFD->setImplicitlyInline();
7396     }
7397 
7398     // If this is a method defined in an __interface, and is not a constructor
7399     // or an overloaded operator, then set the pure flag (isVirtual will already
7400     // return true).
7401     if (const CXXRecordDecl *Parent =
7402           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7403       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7404         NewFD->setPure(true);
7405 
7406       // C++ [class.union]p2
7407       //   A union can have member functions, but not virtual functions.
7408       if (isVirtual && Parent->isUnion())
7409         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7410     }
7411 
7412     SetNestedNameSpecifier(NewFD, D);
7413     isExplicitSpecialization = false;
7414     isFunctionTemplateSpecialization = false;
7415     if (D.isInvalidType())
7416       NewFD->setInvalidDecl();
7417 
7418     // Match up the template parameter lists with the scope specifier, then
7419     // determine whether we have a template or a template specialization.
7420     bool Invalid = false;
7421     if (TemplateParameterList *TemplateParams =
7422             MatchTemplateParametersToScopeSpecifier(
7423                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7424                 D.getCXXScopeSpec(),
7425                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7426                     ? D.getName().TemplateId
7427                     : nullptr,
7428                 TemplateParamLists, isFriend, isExplicitSpecialization,
7429                 Invalid)) {
7430       if (TemplateParams->size() > 0) {
7431         // This is a function template
7432 
7433         // Check that we can declare a template here.
7434         if (CheckTemplateDeclScope(S, TemplateParams))
7435           NewFD->setInvalidDecl();
7436 
7437         // A destructor cannot be a template.
7438         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7439           Diag(NewFD->getLocation(), diag::err_destructor_template);
7440           NewFD->setInvalidDecl();
7441         }
7442 
7443         // If we're adding a template to a dependent context, we may need to
7444         // rebuilding some of the types used within the template parameter list,
7445         // now that we know what the current instantiation is.
7446         if (DC->isDependentContext()) {
7447           ContextRAII SavedContext(*this, DC);
7448           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7449             Invalid = true;
7450         }
7451 
7452 
7453         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7454                                                         NewFD->getLocation(),
7455                                                         Name, TemplateParams,
7456                                                         NewFD);
7457         FunctionTemplate->setLexicalDeclContext(CurContext);
7458         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7459 
7460         // For source fidelity, store the other template param lists.
7461         if (TemplateParamLists.size() > 1) {
7462           NewFD->setTemplateParameterListsInfo(Context,
7463                                                TemplateParamLists.drop_back(1));
7464         }
7465       } else {
7466         // This is a function template specialization.
7467         isFunctionTemplateSpecialization = true;
7468         // For source fidelity, store all the template param lists.
7469         if (TemplateParamLists.size() > 0)
7470           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7471 
7472         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7473         if (isFriend) {
7474           // We want to remove the "template<>", found here.
7475           SourceRange RemoveRange = TemplateParams->getSourceRange();
7476 
7477           // If we remove the template<> and the name is not a
7478           // template-id, we're actually silently creating a problem:
7479           // the friend declaration will refer to an untemplated decl,
7480           // and clearly the user wants a template specialization.  So
7481           // we need to insert '<>' after the name.
7482           SourceLocation InsertLoc;
7483           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7484             InsertLoc = D.getName().getSourceRange().getEnd();
7485             InsertLoc = getLocForEndOfToken(InsertLoc);
7486           }
7487 
7488           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7489             << Name << RemoveRange
7490             << FixItHint::CreateRemoval(RemoveRange)
7491             << FixItHint::CreateInsertion(InsertLoc, "<>");
7492         }
7493       }
7494     }
7495     else {
7496       // All template param lists were matched against the scope specifier:
7497       // this is NOT (an explicit specialization of) a template.
7498       if (TemplateParamLists.size() > 0)
7499         // For source fidelity, store all the template param lists.
7500         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7501     }
7502 
7503     if (Invalid) {
7504       NewFD->setInvalidDecl();
7505       if (FunctionTemplate)
7506         FunctionTemplate->setInvalidDecl();
7507     }
7508 
7509     // C++ [dcl.fct.spec]p5:
7510     //   The virtual specifier shall only be used in declarations of
7511     //   nonstatic class member functions that appear within a
7512     //   member-specification of a class declaration; see 10.3.
7513     //
7514     if (isVirtual && !NewFD->isInvalidDecl()) {
7515       if (!isVirtualOkay) {
7516         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7517              diag::err_virtual_non_function);
7518       } else if (!CurContext->isRecord()) {
7519         // 'virtual' was specified outside of the class.
7520         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7521              diag::err_virtual_out_of_class)
7522           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7523       } else if (NewFD->getDescribedFunctionTemplate()) {
7524         // C++ [temp.mem]p3:
7525         //  A member function template shall not be virtual.
7526         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7527              diag::err_virtual_member_function_template)
7528           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7529       } else {
7530         // Okay: Add virtual to the method.
7531         NewFD->setVirtualAsWritten(true);
7532       }
7533 
7534       if (getLangOpts().CPlusPlus14 &&
7535           NewFD->getReturnType()->isUndeducedType())
7536         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7537     }
7538 
7539     if (getLangOpts().CPlusPlus14 &&
7540         (NewFD->isDependentContext() ||
7541          (isFriend && CurContext->isDependentContext())) &&
7542         NewFD->getReturnType()->isUndeducedType()) {
7543       // If the function template is referenced directly (for instance, as a
7544       // member of the current instantiation), pretend it has a dependent type.
7545       // This is not really justified by the standard, but is the only sane
7546       // thing to do.
7547       // FIXME: For a friend function, we have not marked the function as being
7548       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7549       const FunctionProtoType *FPT =
7550           NewFD->getType()->castAs<FunctionProtoType>();
7551       QualType Result =
7552           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7553       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7554                                              FPT->getExtProtoInfo()));
7555     }
7556 
7557     // C++ [dcl.fct.spec]p3:
7558     //  The inline specifier shall not appear on a block scope function
7559     //  declaration.
7560     if (isInline && !NewFD->isInvalidDecl()) {
7561       if (CurContext->isFunctionOrMethod()) {
7562         // 'inline' is not allowed on block scope function declaration.
7563         Diag(D.getDeclSpec().getInlineSpecLoc(),
7564              diag::err_inline_declaration_block_scope) << Name
7565           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7566       }
7567     }
7568 
7569     // C++ [dcl.fct.spec]p6:
7570     //  The explicit specifier shall be used only in the declaration of a
7571     //  constructor or conversion function within its class definition;
7572     //  see 12.3.1 and 12.3.2.
7573     if (isExplicit && !NewFD->isInvalidDecl()) {
7574       if (!CurContext->isRecord()) {
7575         // 'explicit' was specified outside of the class.
7576         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7577              diag::err_explicit_out_of_class)
7578           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7579       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7580                  !isa<CXXConversionDecl>(NewFD)) {
7581         // 'explicit' was specified on a function that wasn't a constructor
7582         // or conversion function.
7583         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7584              diag::err_explicit_non_ctor_or_conv_function)
7585           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7586       }
7587     }
7588 
7589     if (isConstexpr) {
7590       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7591       // are implicitly inline.
7592       NewFD->setImplicitlyInline();
7593 
7594       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7595       // be either constructors or to return a literal type. Therefore,
7596       // destructors cannot be declared constexpr.
7597       if (isa<CXXDestructorDecl>(NewFD))
7598         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7599     }
7600 
7601     if (isConcept) {
7602       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7603       // applied only to the definition of a function template [...]
7604       if (!D.isFunctionDefinition()) {
7605         Diag(D.getDeclSpec().getConceptSpecLoc(),
7606              diag::err_function_concept_not_defined);
7607         NewFD->setInvalidDecl();
7608       }
7609 
7610       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7611       // have no exception-specification and is treated as if it were specified
7612       // with noexcept(true) (15.4). [...]
7613       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7614         if (FPT->hasExceptionSpec()) {
7615           SourceRange Range;
7616           if (D.isFunctionDeclarator())
7617             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7618           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7619               << FixItHint::CreateRemoval(Range);
7620           NewFD->setInvalidDecl();
7621         } else {
7622           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7623         }
7624 
7625         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7626         // following restrictions:
7627         // - The declaration's parameter list shall be equivalent to an empty
7628         //   parameter list.
7629         if (FPT->getNumParams() > 0 || FPT->isVariadic())
7630           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7631       }
7632 
7633       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7634       // implicity defined to be a constexpr declaration (implicitly inline)
7635       NewFD->setImplicitlyInline();
7636 
7637       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7638       // be declared with the thread_local, inline, friend, or constexpr
7639       // specifiers, [...]
7640       if (isInline) {
7641         Diag(D.getDeclSpec().getInlineSpecLoc(),
7642              diag::err_concept_decl_invalid_specifiers)
7643             << 1 << 1;
7644         NewFD->setInvalidDecl(true);
7645       }
7646 
7647       if (isFriend) {
7648         Diag(D.getDeclSpec().getFriendSpecLoc(),
7649              diag::err_concept_decl_invalid_specifiers)
7650             << 1 << 2;
7651         NewFD->setInvalidDecl(true);
7652       }
7653 
7654       if (isConstexpr) {
7655         Diag(D.getDeclSpec().getConstexprSpecLoc(),
7656              diag::err_concept_decl_invalid_specifiers)
7657             << 1 << 3;
7658         NewFD->setInvalidDecl(true);
7659       }
7660     }
7661 
7662     // If __module_private__ was specified, mark the function accordingly.
7663     if (D.getDeclSpec().isModulePrivateSpecified()) {
7664       if (isFunctionTemplateSpecialization) {
7665         SourceLocation ModulePrivateLoc
7666           = D.getDeclSpec().getModulePrivateSpecLoc();
7667         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7668           << 0
7669           << FixItHint::CreateRemoval(ModulePrivateLoc);
7670       } else {
7671         NewFD->setModulePrivate();
7672         if (FunctionTemplate)
7673           FunctionTemplate->setModulePrivate();
7674       }
7675     }
7676 
7677     if (isFriend) {
7678       if (FunctionTemplate) {
7679         FunctionTemplate->setObjectOfFriendDecl();
7680         FunctionTemplate->setAccess(AS_public);
7681       }
7682       NewFD->setObjectOfFriendDecl();
7683       NewFD->setAccess(AS_public);
7684     }
7685 
7686     // If a function is defined as defaulted or deleted, mark it as such now.
7687     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7688     // definition kind to FDK_Definition.
7689     switch (D.getFunctionDefinitionKind()) {
7690       case FDK_Declaration:
7691       case FDK_Definition:
7692         break;
7693 
7694       case FDK_Defaulted:
7695         NewFD->setDefaulted();
7696         break;
7697 
7698       case FDK_Deleted:
7699         NewFD->setDeletedAsWritten();
7700         break;
7701     }
7702 
7703     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7704         D.isFunctionDefinition()) {
7705       // C++ [class.mfct]p2:
7706       //   A member function may be defined (8.4) in its class definition, in
7707       //   which case it is an inline member function (7.1.2)
7708       NewFD->setImplicitlyInline();
7709     }
7710 
7711     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7712         !CurContext->isRecord()) {
7713       // C++ [class.static]p1:
7714       //   A data or function member of a class may be declared static
7715       //   in a class definition, in which case it is a static member of
7716       //   the class.
7717 
7718       // Complain about the 'static' specifier if it's on an out-of-line
7719       // member function definition.
7720       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7721            diag::err_static_out_of_line)
7722         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7723     }
7724 
7725     // C++11 [except.spec]p15:
7726     //   A deallocation function with no exception-specification is treated
7727     //   as if it were specified with noexcept(true).
7728     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7729     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7730          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7731         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7732       NewFD->setType(Context.getFunctionType(
7733           FPT->getReturnType(), FPT->getParamTypes(),
7734           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7735   }
7736 
7737   // Filter out previous declarations that don't match the scope.
7738   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7739                        D.getCXXScopeSpec().isNotEmpty() ||
7740                        isExplicitSpecialization ||
7741                        isFunctionTemplateSpecialization);
7742 
7743   // Handle GNU asm-label extension (encoded as an attribute).
7744   if (Expr *E = (Expr*) D.getAsmLabel()) {
7745     // The parser guarantees this is a string.
7746     StringLiteral *SE = cast<StringLiteral>(E);
7747     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7748                                                 SE->getString(), 0));
7749   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7750     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7751       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7752     if (I != ExtnameUndeclaredIdentifiers.end()) {
7753       if (isDeclExternC(NewFD)) {
7754         NewFD->addAttr(I->second);
7755         ExtnameUndeclaredIdentifiers.erase(I);
7756       } else
7757         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
7758             << /*Variable*/0 << NewFD;
7759     }
7760   }
7761 
7762   // Copy the parameter declarations from the declarator D to the function
7763   // declaration NewFD, if they are available.  First scavenge them into Params.
7764   SmallVector<ParmVarDecl*, 16> Params;
7765   if (D.isFunctionDeclarator()) {
7766     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7767 
7768     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7769     // function that takes no arguments, not a function that takes a
7770     // single void argument.
7771     // We let through "const void" here because Sema::GetTypeForDeclarator
7772     // already checks for that case.
7773     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7774       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7775         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7776         assert(Param->getDeclContext() != NewFD && "Was set before ?");
7777         Param->setDeclContext(NewFD);
7778         Params.push_back(Param);
7779 
7780         if (Param->isInvalidDecl())
7781           NewFD->setInvalidDecl();
7782       }
7783     }
7784 
7785   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7786     // When we're declaring a function with a typedef, typeof, etc as in the
7787     // following example, we'll need to synthesize (unnamed)
7788     // parameters for use in the declaration.
7789     //
7790     // @code
7791     // typedef void fn(int);
7792     // fn f;
7793     // @endcode
7794 
7795     // Synthesize a parameter for each argument type.
7796     for (const auto &AI : FT->param_types()) {
7797       ParmVarDecl *Param =
7798           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7799       Param->setScopeInfo(0, Params.size());
7800       Params.push_back(Param);
7801     }
7802   } else {
7803     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7804            "Should not need args for typedef of non-prototype fn");
7805   }
7806 
7807   // Finally, we know we have the right number of parameters, install them.
7808   NewFD->setParams(Params);
7809 
7810   // Find all anonymous symbols defined during the declaration of this function
7811   // and add to NewFD. This lets us track decls such 'enum Y' in:
7812   //
7813   //   void f(enum Y {AA} x) {}
7814   //
7815   // which would otherwise incorrectly end up in the translation unit scope.
7816   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7817   DeclsInPrototypeScope.clear();
7818 
7819   if (D.getDeclSpec().isNoreturnSpecified())
7820     NewFD->addAttr(
7821         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7822                                        Context, 0));
7823 
7824   // Functions returning a variably modified type violate C99 6.7.5.2p2
7825   // because all functions have linkage.
7826   if (!NewFD->isInvalidDecl() &&
7827       NewFD->getReturnType()->isVariablyModifiedType()) {
7828     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7829     NewFD->setInvalidDecl();
7830   }
7831 
7832   // Apply an implicit SectionAttr if #pragma code_seg is active.
7833   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
7834       !NewFD->hasAttr<SectionAttr>()) {
7835     NewFD->addAttr(
7836         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7837                                     CodeSegStack.CurrentValue->getString(),
7838                                     CodeSegStack.CurrentPragmaLocation));
7839     if (UnifySection(CodeSegStack.CurrentValue->getString(),
7840                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
7841                          ASTContext::PSF_Read,
7842                      NewFD))
7843       NewFD->dropAttr<SectionAttr>();
7844   }
7845 
7846   // Handle attributes.
7847   ProcessDeclAttributes(S, NewFD, D);
7848 
7849   if (getLangOpts().OpenCL) {
7850     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7851     // type declaration will generate a compilation error.
7852     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
7853     if (AddressSpace == LangAS::opencl_local ||
7854         AddressSpace == LangAS::opencl_global ||
7855         AddressSpace == LangAS::opencl_constant) {
7856       Diag(NewFD->getLocation(),
7857            diag::err_opencl_return_value_with_address_space);
7858       NewFD->setInvalidDecl();
7859     }
7860   }
7861 
7862   if (!getLangOpts().CPlusPlus) {
7863     // Perform semantic checking on the function declaration.
7864     bool isExplicitSpecialization=false;
7865     if (!NewFD->isInvalidDecl() && NewFD->isMain())
7866       CheckMain(NewFD, D.getDeclSpec());
7867 
7868     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7869       CheckMSVCRTEntryPoint(NewFD);
7870 
7871     if (!NewFD->isInvalidDecl())
7872       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7873                                                   isExplicitSpecialization));
7874     else if (!Previous.empty())
7875       // Recover gracefully from an invalid redeclaration.
7876       D.setRedeclaration(true);
7877     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7878             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7879            "previous declaration set still overloaded");
7880 
7881     // Diagnose no-prototype function declarations with calling conventions that
7882     // don't support variadic calls. Only do this in C and do it after merging
7883     // possibly prototyped redeclarations.
7884     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
7885     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
7886       CallingConv CC = FT->getExtInfo().getCC();
7887       if (!supportsVariadicCall(CC)) {
7888         // Windows system headers sometimes accidentally use stdcall without
7889         // (void) parameters, so we relax this to a warning.
7890         int DiagID =
7891             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
7892         Diag(NewFD->getLocation(), DiagID)
7893             << FunctionType::getNameForCallConv(CC);
7894       }
7895     }
7896   } else {
7897     // C++11 [replacement.functions]p3:
7898     //  The program's definitions shall not be specified as inline.
7899     //
7900     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7901     //
7902     // Suppress the diagnostic if the function is __attribute__((used)), since
7903     // that forces an external definition to be emitted.
7904     if (D.getDeclSpec().isInlineSpecified() &&
7905         NewFD->isReplaceableGlobalAllocationFunction() &&
7906         !NewFD->hasAttr<UsedAttr>())
7907       Diag(D.getDeclSpec().getInlineSpecLoc(),
7908            diag::ext_operator_new_delete_declared_inline)
7909         << NewFD->getDeclName();
7910 
7911     // If the declarator is a template-id, translate the parser's template
7912     // argument list into our AST format.
7913     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7914       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7915       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7916       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7917       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7918                                          TemplateId->NumArgs);
7919       translateTemplateArguments(TemplateArgsPtr,
7920                                  TemplateArgs);
7921 
7922       HasExplicitTemplateArgs = true;
7923 
7924       if (NewFD->isInvalidDecl()) {
7925         HasExplicitTemplateArgs = false;
7926       } else if (FunctionTemplate) {
7927         // Function template with explicit template arguments.
7928         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7929           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7930 
7931         HasExplicitTemplateArgs = false;
7932       } else {
7933         assert((isFunctionTemplateSpecialization ||
7934                 D.getDeclSpec().isFriendSpecified()) &&
7935                "should have a 'template<>' for this decl");
7936         // "friend void foo<>(int);" is an implicit specialization decl.
7937         isFunctionTemplateSpecialization = true;
7938       }
7939     } else if (isFriend && isFunctionTemplateSpecialization) {
7940       // This combination is only possible in a recovery case;  the user
7941       // wrote something like:
7942       //   template <> friend void foo(int);
7943       // which we're recovering from as if the user had written:
7944       //   friend void foo<>(int);
7945       // Go ahead and fake up a template id.
7946       HasExplicitTemplateArgs = true;
7947       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7948       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7949     }
7950 
7951     // If it's a friend (and only if it's a friend), it's possible
7952     // that either the specialized function type or the specialized
7953     // template is dependent, and therefore matching will fail.  In
7954     // this case, don't check the specialization yet.
7955     bool InstantiationDependent = false;
7956     if (isFunctionTemplateSpecialization && isFriend &&
7957         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7958          TemplateSpecializationType::anyDependentTemplateArguments(
7959             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7960             InstantiationDependent))) {
7961       assert(HasExplicitTemplateArgs &&
7962              "friend function specialization without template args");
7963       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7964                                                        Previous))
7965         NewFD->setInvalidDecl();
7966     } else if (isFunctionTemplateSpecialization) {
7967       if (CurContext->isDependentContext() && CurContext->isRecord()
7968           && !isFriend) {
7969         isDependentClassScopeExplicitSpecialization = true;
7970         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7971           diag::ext_function_specialization_in_class :
7972           diag::err_function_specialization_in_class)
7973           << NewFD->getDeclName();
7974       } else if (CheckFunctionTemplateSpecialization(NewFD,
7975                                   (HasExplicitTemplateArgs ? &TemplateArgs
7976                                                            : nullptr),
7977                                                      Previous))
7978         NewFD->setInvalidDecl();
7979 
7980       // C++ [dcl.stc]p1:
7981       //   A storage-class-specifier shall not be specified in an explicit
7982       //   specialization (14.7.3)
7983       FunctionTemplateSpecializationInfo *Info =
7984           NewFD->getTemplateSpecializationInfo();
7985       if (Info && SC != SC_None) {
7986         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7987           Diag(NewFD->getLocation(),
7988                diag::err_explicit_specialization_inconsistent_storage_class)
7989             << SC
7990             << FixItHint::CreateRemoval(
7991                                       D.getDeclSpec().getStorageClassSpecLoc());
7992 
7993         else
7994           Diag(NewFD->getLocation(),
7995                diag::ext_explicit_specialization_storage_class)
7996             << FixItHint::CreateRemoval(
7997                                       D.getDeclSpec().getStorageClassSpecLoc());
7998       }
7999 
8000     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8001       if (CheckMemberSpecialization(NewFD, Previous))
8002           NewFD->setInvalidDecl();
8003     }
8004 
8005     // Perform semantic checking on the function declaration.
8006     if (!isDependentClassScopeExplicitSpecialization) {
8007       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8008         CheckMain(NewFD, D.getDeclSpec());
8009 
8010       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8011         CheckMSVCRTEntryPoint(NewFD);
8012 
8013       if (!NewFD->isInvalidDecl())
8014         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8015                                                     isExplicitSpecialization));
8016       else if (!Previous.empty())
8017         // Recover gracefully from an invalid redeclaration.
8018         D.setRedeclaration(true);
8019     }
8020 
8021     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8022             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8023            "previous declaration set still overloaded");
8024 
8025     NamedDecl *PrincipalDecl = (FunctionTemplate
8026                                 ? cast<NamedDecl>(FunctionTemplate)
8027                                 : NewFD);
8028 
8029     if (isFriend && D.isRedeclaration()) {
8030       AccessSpecifier Access = AS_public;
8031       if (!NewFD->isInvalidDecl())
8032         Access = NewFD->getPreviousDecl()->getAccess();
8033 
8034       NewFD->setAccess(Access);
8035       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8036     }
8037 
8038     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8039         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8040       PrincipalDecl->setNonMemberOperator();
8041 
8042     // If we have a function template, check the template parameter
8043     // list. This will check and merge default template arguments.
8044     if (FunctionTemplate) {
8045       FunctionTemplateDecl *PrevTemplate =
8046                                      FunctionTemplate->getPreviousDecl();
8047       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8048                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8049                                     : nullptr,
8050                             D.getDeclSpec().isFriendSpecified()
8051                               ? (D.isFunctionDefinition()
8052                                    ? TPC_FriendFunctionTemplateDefinition
8053                                    : TPC_FriendFunctionTemplate)
8054                               : (D.getCXXScopeSpec().isSet() &&
8055                                  DC && DC->isRecord() &&
8056                                  DC->isDependentContext())
8057                                   ? TPC_ClassTemplateMember
8058                                   : TPC_FunctionTemplate);
8059     }
8060 
8061     if (NewFD->isInvalidDecl()) {
8062       // Ignore all the rest of this.
8063     } else if (!D.isRedeclaration()) {
8064       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8065                                        AddToScope };
8066       // Fake up an access specifier if it's supposed to be a class member.
8067       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8068         NewFD->setAccess(AS_public);
8069 
8070       // Qualified decls generally require a previous declaration.
8071       if (D.getCXXScopeSpec().isSet()) {
8072         // ...with the major exception of templated-scope or
8073         // dependent-scope friend declarations.
8074 
8075         // TODO: we currently also suppress this check in dependent
8076         // contexts because (1) the parameter depth will be off when
8077         // matching friend templates and (2) we might actually be
8078         // selecting a friend based on a dependent factor.  But there
8079         // are situations where these conditions don't apply and we
8080         // can actually do this check immediately.
8081         if (isFriend &&
8082             (TemplateParamLists.size() ||
8083              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8084              CurContext->isDependentContext())) {
8085           // ignore these
8086         } else {
8087           // The user tried to provide an out-of-line definition for a
8088           // function that is a member of a class or namespace, but there
8089           // was no such member function declared (C++ [class.mfct]p2,
8090           // C++ [namespace.memdef]p2). For example:
8091           //
8092           // class X {
8093           //   void f() const;
8094           // };
8095           //
8096           // void X::f() { } // ill-formed
8097           //
8098           // Complain about this problem, and attempt to suggest close
8099           // matches (e.g., those that differ only in cv-qualifiers and
8100           // whether the parameter types are references).
8101 
8102           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8103                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8104             AddToScope = ExtraArgs.AddToScope;
8105             return Result;
8106           }
8107         }
8108 
8109         // Unqualified local friend declarations are required to resolve
8110         // to something.
8111       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8112         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8113                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8114           AddToScope = ExtraArgs.AddToScope;
8115           return Result;
8116         }
8117       }
8118 
8119     } else if (!D.isFunctionDefinition() &&
8120                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8121                !isFriend && !isFunctionTemplateSpecialization &&
8122                !isExplicitSpecialization) {
8123       // An out-of-line member function declaration must also be a
8124       // definition (C++ [class.mfct]p2).
8125       // Note that this is not the case for explicit specializations of
8126       // function templates or member functions of class templates, per
8127       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8128       // extension for compatibility with old SWIG code which likes to
8129       // generate them.
8130       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8131         << D.getCXXScopeSpec().getRange();
8132     }
8133   }
8134 
8135   ProcessPragmaWeak(S, NewFD);
8136   checkAttributesAfterMerging(*this, *NewFD);
8137 
8138   AddKnownFunctionAttributes(NewFD);
8139 
8140   if (NewFD->hasAttr<OverloadableAttr>() &&
8141       !NewFD->getType()->getAs<FunctionProtoType>()) {
8142     Diag(NewFD->getLocation(),
8143          diag::err_attribute_overloadable_no_prototype)
8144       << NewFD;
8145 
8146     // Turn this into a variadic function with no parameters.
8147     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8148     FunctionProtoType::ExtProtoInfo EPI(
8149         Context.getDefaultCallingConvention(true, false));
8150     EPI.Variadic = true;
8151     EPI.ExtInfo = FT->getExtInfo();
8152 
8153     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8154     NewFD->setType(R);
8155   }
8156 
8157   // If there's a #pragma GCC visibility in scope, and this isn't a class
8158   // member, set the visibility of this function.
8159   if (!DC->isRecord() && NewFD->isExternallyVisible())
8160     AddPushedVisibilityAttribute(NewFD);
8161 
8162   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8163   // marking the function.
8164   AddCFAuditedAttribute(NewFD);
8165 
8166   // If this is a function definition, check if we have to apply optnone due to
8167   // a pragma.
8168   if(D.isFunctionDefinition())
8169     AddRangeBasedOptnone(NewFD);
8170 
8171   // If this is the first declaration of an extern C variable, update
8172   // the map of such variables.
8173   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8174       isIncompleteDeclExternC(*this, NewFD))
8175     RegisterLocallyScopedExternCDecl(NewFD, S);
8176 
8177   // Set this FunctionDecl's range up to the right paren.
8178   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8179 
8180   if (D.isRedeclaration() && !Previous.empty()) {
8181     checkDLLAttributeRedeclaration(
8182         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8183         isExplicitSpecialization || isFunctionTemplateSpecialization);
8184   }
8185 
8186   if (getLangOpts().CPlusPlus) {
8187     if (FunctionTemplate) {
8188       if (NewFD->isInvalidDecl())
8189         FunctionTemplate->setInvalidDecl();
8190       return FunctionTemplate;
8191     }
8192   }
8193 
8194   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8195     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8196     if ((getLangOpts().OpenCLVersion >= 120)
8197         && (SC == SC_Static)) {
8198       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8199       D.setInvalidType();
8200     }
8201 
8202     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8203     if (!NewFD->getReturnType()->isVoidType()) {
8204       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8205       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8206           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8207                                 : FixItHint());
8208       D.setInvalidType();
8209     }
8210 
8211     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8212     for (auto Param : NewFD->params())
8213       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8214   }
8215 
8216   MarkUnusedFileScopedDecl(NewFD);
8217 
8218   if (getLangOpts().CUDA)
8219     if (IdentifierInfo *II = NewFD->getIdentifier())
8220       if (!NewFD->isInvalidDecl() &&
8221           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8222         if (II->isStr("cudaConfigureCall")) {
8223           if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8224             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8225 
8226           Context.setcudaConfigureCallDecl(NewFD);
8227         }
8228       }
8229 
8230   // Here we have an function template explicit specialization at class scope.
8231   // The actually specialization will be postponed to template instatiation
8232   // time via the ClassScopeFunctionSpecializationDecl node.
8233   if (isDependentClassScopeExplicitSpecialization) {
8234     ClassScopeFunctionSpecializationDecl *NewSpec =
8235                          ClassScopeFunctionSpecializationDecl::Create(
8236                                 Context, CurContext, SourceLocation(),
8237                                 cast<CXXMethodDecl>(NewFD),
8238                                 HasExplicitTemplateArgs, TemplateArgs);
8239     CurContext->addDecl(NewSpec);
8240     AddToScope = false;
8241   }
8242 
8243   return NewFD;
8244 }
8245 
8246 /// \brief Perform semantic checking of a new function declaration.
8247 ///
8248 /// Performs semantic analysis of the new function declaration
8249 /// NewFD. This routine performs all semantic checking that does not
8250 /// require the actual declarator involved in the declaration, and is
8251 /// used both for the declaration of functions as they are parsed
8252 /// (called via ActOnDeclarator) and for the declaration of functions
8253 /// that have been instantiated via C++ template instantiation (called
8254 /// via InstantiateDecl).
8255 ///
8256 /// \param IsExplicitSpecialization whether this new function declaration is
8257 /// an explicit specialization of the previous declaration.
8258 ///
8259 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8260 ///
8261 /// \returns true if the function declaration is a redeclaration.
8262 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8263                                     LookupResult &Previous,
8264                                     bool IsExplicitSpecialization) {
8265   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8266          "Variably modified return types are not handled here");
8267 
8268   // Determine whether the type of this function should be merged with
8269   // a previous visible declaration. This never happens for functions in C++,
8270   // and always happens in C if the previous declaration was visible.
8271   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8272                                !Previous.isShadowed();
8273 
8274   bool Redeclaration = false;
8275   NamedDecl *OldDecl = nullptr;
8276 
8277   // Merge or overload the declaration with an existing declaration of
8278   // the same name, if appropriate.
8279   if (!Previous.empty()) {
8280     // Determine whether NewFD is an overload of PrevDecl or
8281     // a declaration that requires merging. If it's an overload,
8282     // there's no more work to do here; we'll just add the new
8283     // function to the scope.
8284     if (!AllowOverloadingOfFunction(Previous, Context)) {
8285       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8286       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8287         Redeclaration = true;
8288         OldDecl = Candidate;
8289       }
8290     } else {
8291       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8292                             /*NewIsUsingDecl*/ false)) {
8293       case Ovl_Match:
8294         Redeclaration = true;
8295         break;
8296 
8297       case Ovl_NonFunction:
8298         Redeclaration = true;
8299         break;
8300 
8301       case Ovl_Overload:
8302         Redeclaration = false;
8303         break;
8304       }
8305 
8306       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8307         // If a function name is overloadable in C, then every function
8308         // with that name must be marked "overloadable".
8309         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8310           << Redeclaration << NewFD;
8311         NamedDecl *OverloadedDecl = nullptr;
8312         if (Redeclaration)
8313           OverloadedDecl = OldDecl;
8314         else if (!Previous.empty())
8315           OverloadedDecl = Previous.getRepresentativeDecl();
8316         if (OverloadedDecl)
8317           Diag(OverloadedDecl->getLocation(),
8318                diag::note_attribute_overloadable_prev_overload);
8319         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8320       }
8321     }
8322   }
8323 
8324   // Check for a previous extern "C" declaration with this name.
8325   if (!Redeclaration &&
8326       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8327     if (!Previous.empty()) {
8328       // This is an extern "C" declaration with the same name as a previous
8329       // declaration, and thus redeclares that entity...
8330       Redeclaration = true;
8331       OldDecl = Previous.getFoundDecl();
8332       MergeTypeWithPrevious = false;
8333 
8334       // ... except in the presence of __attribute__((overloadable)).
8335       if (OldDecl->hasAttr<OverloadableAttr>()) {
8336         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8337           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8338             << Redeclaration << NewFD;
8339           Diag(Previous.getFoundDecl()->getLocation(),
8340                diag::note_attribute_overloadable_prev_overload);
8341           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8342         }
8343         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8344           Redeclaration = false;
8345           OldDecl = nullptr;
8346         }
8347       }
8348     }
8349   }
8350 
8351   // C++11 [dcl.constexpr]p8:
8352   //   A constexpr specifier for a non-static member function that is not
8353   //   a constructor declares that member function to be const.
8354   //
8355   // This needs to be delayed until we know whether this is an out-of-line
8356   // definition of a static member function.
8357   //
8358   // This rule is not present in C++1y, so we produce a backwards
8359   // compatibility warning whenever it happens in C++11.
8360   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8361   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8362       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8363       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8364     CXXMethodDecl *OldMD = nullptr;
8365     if (OldDecl)
8366       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8367     if (!OldMD || !OldMD->isStatic()) {
8368       const FunctionProtoType *FPT =
8369         MD->getType()->castAs<FunctionProtoType>();
8370       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8371       EPI.TypeQuals |= Qualifiers::Const;
8372       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8373                                           FPT->getParamTypes(), EPI));
8374 
8375       // Warn that we did this, if we're not performing template instantiation.
8376       // In that case, we'll have warned already when the template was defined.
8377       if (ActiveTemplateInstantiations.empty()) {
8378         SourceLocation AddConstLoc;
8379         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8380                 .IgnoreParens().getAs<FunctionTypeLoc>())
8381           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8382 
8383         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8384           << FixItHint::CreateInsertion(AddConstLoc, " const");
8385       }
8386     }
8387   }
8388 
8389   if (Redeclaration) {
8390     // NewFD and OldDecl represent declarations that need to be
8391     // merged.
8392     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8393       NewFD->setInvalidDecl();
8394       return Redeclaration;
8395     }
8396 
8397     Previous.clear();
8398     Previous.addDecl(OldDecl);
8399 
8400     if (FunctionTemplateDecl *OldTemplateDecl
8401                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8402       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8403       FunctionTemplateDecl *NewTemplateDecl
8404         = NewFD->getDescribedFunctionTemplate();
8405       assert(NewTemplateDecl && "Template/non-template mismatch");
8406       if (CXXMethodDecl *Method
8407             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8408         Method->setAccess(OldTemplateDecl->getAccess());
8409         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8410       }
8411 
8412       // If this is an explicit specialization of a member that is a function
8413       // template, mark it as a member specialization.
8414       if (IsExplicitSpecialization &&
8415           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8416         NewTemplateDecl->setMemberSpecialization();
8417         assert(OldTemplateDecl->isMemberSpecialization());
8418       }
8419 
8420     } else {
8421       // This needs to happen first so that 'inline' propagates.
8422       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8423 
8424       if (isa<CXXMethodDecl>(NewFD))
8425         NewFD->setAccess(OldDecl->getAccess());
8426     }
8427   }
8428 
8429   // Semantic checking for this function declaration (in isolation).
8430 
8431   if (getLangOpts().CPlusPlus) {
8432     // C++-specific checks.
8433     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8434       CheckConstructor(Constructor);
8435     } else if (CXXDestructorDecl *Destructor =
8436                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8437       CXXRecordDecl *Record = Destructor->getParent();
8438       QualType ClassType = Context.getTypeDeclType(Record);
8439 
8440       // FIXME: Shouldn't we be able to perform this check even when the class
8441       // type is dependent? Both gcc and edg can handle that.
8442       if (!ClassType->isDependentType()) {
8443         DeclarationName Name
8444           = Context.DeclarationNames.getCXXDestructorName(
8445                                         Context.getCanonicalType(ClassType));
8446         if (NewFD->getDeclName() != Name) {
8447           Diag(NewFD->getLocation(), diag::err_destructor_name);
8448           NewFD->setInvalidDecl();
8449           return Redeclaration;
8450         }
8451       }
8452     } else if (CXXConversionDecl *Conversion
8453                = dyn_cast<CXXConversionDecl>(NewFD)) {
8454       ActOnConversionDeclarator(Conversion);
8455     }
8456 
8457     // Find any virtual functions that this function overrides.
8458     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8459       if (!Method->isFunctionTemplateSpecialization() &&
8460           !Method->getDescribedFunctionTemplate() &&
8461           Method->isCanonicalDecl()) {
8462         if (AddOverriddenMethods(Method->getParent(), Method)) {
8463           // If the function was marked as "static", we have a problem.
8464           if (NewFD->getStorageClass() == SC_Static) {
8465             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8466           }
8467         }
8468       }
8469 
8470       if (Method->isStatic())
8471         checkThisInStaticMemberFunctionType(Method);
8472     }
8473 
8474     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8475     if (NewFD->isOverloadedOperator() &&
8476         CheckOverloadedOperatorDeclaration(NewFD)) {
8477       NewFD->setInvalidDecl();
8478       return Redeclaration;
8479     }
8480 
8481     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8482     if (NewFD->getLiteralIdentifier() &&
8483         CheckLiteralOperatorDeclaration(NewFD)) {
8484       NewFD->setInvalidDecl();
8485       return Redeclaration;
8486     }
8487 
8488     // In C++, check default arguments now that we have merged decls. Unless
8489     // the lexical context is the class, because in this case this is done
8490     // during delayed parsing anyway.
8491     if (!CurContext->isRecord())
8492       CheckCXXDefaultArguments(NewFD);
8493 
8494     // If this function declares a builtin function, check the type of this
8495     // declaration against the expected type for the builtin.
8496     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8497       ASTContext::GetBuiltinTypeError Error;
8498       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8499       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8500       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8501         // The type of this function differs from the type of the builtin,
8502         // so forget about the builtin entirely.
8503         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8504       }
8505     }
8506 
8507     // If this function is declared as being extern "C", then check to see if
8508     // the function returns a UDT (class, struct, or union type) that is not C
8509     // compatible, and if it does, warn the user.
8510     // But, issue any diagnostic on the first declaration only.
8511     if (Previous.empty() && NewFD->isExternC()) {
8512       QualType R = NewFD->getReturnType();
8513       if (R->isIncompleteType() && !R->isVoidType())
8514         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8515             << NewFD << R;
8516       else if (!R.isPODType(Context) && !R->isVoidType() &&
8517                !R->isObjCObjectPointerType())
8518         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8519     }
8520   }
8521   return Redeclaration;
8522 }
8523 
8524 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8525   // C++11 [basic.start.main]p3:
8526   //   A program that [...] declares main to be inline, static or
8527   //   constexpr is ill-formed.
8528   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8529   //   appear in a declaration of main.
8530   // static main is not an error under C99, but we should warn about it.
8531   // We accept _Noreturn main as an extension.
8532   if (FD->getStorageClass() == SC_Static)
8533     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8534          ? diag::err_static_main : diag::warn_static_main)
8535       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8536   if (FD->isInlineSpecified())
8537     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8538       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8539   if (DS.isNoreturnSpecified()) {
8540     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8541     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8542     Diag(NoreturnLoc, diag::ext_noreturn_main);
8543     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8544       << FixItHint::CreateRemoval(NoreturnRange);
8545   }
8546   if (FD->isConstexpr()) {
8547     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8548       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8549     FD->setConstexpr(false);
8550   }
8551 
8552   if (getLangOpts().OpenCL) {
8553     Diag(FD->getLocation(), diag::err_opencl_no_main)
8554         << FD->hasAttr<OpenCLKernelAttr>();
8555     FD->setInvalidDecl();
8556     return;
8557   }
8558 
8559   QualType T = FD->getType();
8560   assert(T->isFunctionType() && "function decl is not of function type");
8561   const FunctionType* FT = T->castAs<FunctionType>();
8562 
8563   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8564     // In C with GNU extensions we allow main() to have non-integer return
8565     // type, but we should warn about the extension, and we disable the
8566     // implicit-return-zero rule.
8567 
8568     // GCC in C mode accepts qualified 'int'.
8569     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8570       FD->setHasImplicitReturnZero(true);
8571     else {
8572       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8573       SourceRange RTRange = FD->getReturnTypeSourceRange();
8574       if (RTRange.isValid())
8575         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8576             << FixItHint::CreateReplacement(RTRange, "int");
8577     }
8578   } else {
8579     // In C and C++, main magically returns 0 if you fall off the end;
8580     // set the flag which tells us that.
8581     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8582 
8583     // All the standards say that main() should return 'int'.
8584     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8585       FD->setHasImplicitReturnZero(true);
8586     else {
8587       // Otherwise, this is just a flat-out error.
8588       SourceRange RTRange = FD->getReturnTypeSourceRange();
8589       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8590           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8591                                 : FixItHint());
8592       FD->setInvalidDecl(true);
8593     }
8594   }
8595 
8596   // Treat protoless main() as nullary.
8597   if (isa<FunctionNoProtoType>(FT)) return;
8598 
8599   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8600   unsigned nparams = FTP->getNumParams();
8601   assert(FD->getNumParams() == nparams);
8602 
8603   bool HasExtraParameters = (nparams > 3);
8604 
8605   if (FTP->isVariadic()) {
8606     Diag(FD->getLocation(), diag::ext_variadic_main);
8607     // FIXME: if we had information about the location of the ellipsis, we
8608     // could add a FixIt hint to remove it as a parameter.
8609   }
8610 
8611   // Darwin passes an undocumented fourth argument of type char**.  If
8612   // other platforms start sprouting these, the logic below will start
8613   // getting shifty.
8614   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8615     HasExtraParameters = false;
8616 
8617   if (HasExtraParameters) {
8618     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8619     FD->setInvalidDecl(true);
8620     nparams = 3;
8621   }
8622 
8623   // FIXME: a lot of the following diagnostics would be improved
8624   // if we had some location information about types.
8625 
8626   QualType CharPP =
8627     Context.getPointerType(Context.getPointerType(Context.CharTy));
8628   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8629 
8630   for (unsigned i = 0; i < nparams; ++i) {
8631     QualType AT = FTP->getParamType(i);
8632 
8633     bool mismatch = true;
8634 
8635     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8636       mismatch = false;
8637     else if (Expected[i] == CharPP) {
8638       // As an extension, the following forms are okay:
8639       //   char const **
8640       //   char const * const *
8641       //   char * const *
8642 
8643       QualifierCollector qs;
8644       const PointerType* PT;
8645       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8646           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8647           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8648                               Context.CharTy)) {
8649         qs.removeConst();
8650         mismatch = !qs.empty();
8651       }
8652     }
8653 
8654     if (mismatch) {
8655       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8656       // TODO: suggest replacing given type with expected type
8657       FD->setInvalidDecl(true);
8658     }
8659   }
8660 
8661   if (nparams == 1 && !FD->isInvalidDecl()) {
8662     Diag(FD->getLocation(), diag::warn_main_one_arg);
8663   }
8664 
8665   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8666     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8667     FD->setInvalidDecl();
8668   }
8669 }
8670 
8671 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8672   QualType T = FD->getType();
8673   assert(T->isFunctionType() && "function decl is not of function type");
8674   const FunctionType *FT = T->castAs<FunctionType>();
8675 
8676   // Set an implicit return of 'zero' if the function can return some integral,
8677   // enumeration, pointer or nullptr type.
8678   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8679       FT->getReturnType()->isAnyPointerType() ||
8680       FT->getReturnType()->isNullPtrType())
8681     // DllMain is exempt because a return value of zero means it failed.
8682     if (FD->getName() != "DllMain")
8683       FD->setHasImplicitReturnZero(true);
8684 
8685   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8686     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8687     FD->setInvalidDecl();
8688   }
8689 }
8690 
8691 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8692   // FIXME: Need strict checking.  In C89, we need to check for
8693   // any assignment, increment, decrement, function-calls, or
8694   // commas outside of a sizeof.  In C99, it's the same list,
8695   // except that the aforementioned are allowed in unevaluated
8696   // expressions.  Everything else falls under the
8697   // "may accept other forms of constant expressions" exception.
8698   // (We never end up here for C++, so the constant expression
8699   // rules there don't matter.)
8700   const Expr *Culprit;
8701   if (Init->isConstantInitializer(Context, false, &Culprit))
8702     return false;
8703   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8704     << Culprit->getSourceRange();
8705   return true;
8706 }
8707 
8708 namespace {
8709   // Visits an initialization expression to see if OrigDecl is evaluated in
8710   // its own initialization and throws a warning if it does.
8711   class SelfReferenceChecker
8712       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8713     Sema &S;
8714     Decl *OrigDecl;
8715     bool isRecordType;
8716     bool isPODType;
8717     bool isReferenceType;
8718 
8719     bool isInitList;
8720     llvm::SmallVector<unsigned, 4> InitFieldIndex;
8721   public:
8722     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8723 
8724     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8725                                                     S(S), OrigDecl(OrigDecl) {
8726       isPODType = false;
8727       isRecordType = false;
8728       isReferenceType = false;
8729       isInitList = false;
8730       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8731         isPODType = VD->getType().isPODType(S.Context);
8732         isRecordType = VD->getType()->isRecordType();
8733         isReferenceType = VD->getType()->isReferenceType();
8734       }
8735     }
8736 
8737     // For most expressions, just call the visitor.  For initializer lists,
8738     // track the index of the field being initialized since fields are
8739     // initialized in order allowing use of previously initialized fields.
8740     void CheckExpr(Expr *E) {
8741       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8742       if (!InitList) {
8743         Visit(E);
8744         return;
8745       }
8746 
8747       // Track and increment the index here.
8748       isInitList = true;
8749       InitFieldIndex.push_back(0);
8750       for (auto Child : InitList->children()) {
8751         CheckExpr(cast<Expr>(Child));
8752         ++InitFieldIndex.back();
8753       }
8754       InitFieldIndex.pop_back();
8755     }
8756 
8757     // Returns true if MemberExpr is checked and no futher checking is needed.
8758     // Returns false if additional checking is required.
8759     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8760       llvm::SmallVector<FieldDecl*, 4> Fields;
8761       Expr *Base = E;
8762       bool ReferenceField = false;
8763 
8764       // Get the field memebers used.
8765       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8766         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8767         if (!FD)
8768           return false;
8769         Fields.push_back(FD);
8770         if (FD->getType()->isReferenceType())
8771           ReferenceField = true;
8772         Base = ME->getBase()->IgnoreParenImpCasts();
8773       }
8774 
8775       // Keep checking only if the base Decl is the same.
8776       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8777       if (!DRE || DRE->getDecl() != OrigDecl)
8778         return false;
8779 
8780       // A reference field can be bound to an unininitialized field.
8781       if (CheckReference && !ReferenceField)
8782         return true;
8783 
8784       // Convert FieldDecls to their index number.
8785       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8786       for (const FieldDecl *I : llvm::reverse(Fields))
8787         UsedFieldIndex.push_back(I->getFieldIndex());
8788 
8789       // See if a warning is needed by checking the first difference in index
8790       // numbers.  If field being used has index less than the field being
8791       // initialized, then the use is safe.
8792       for (auto UsedIter = UsedFieldIndex.begin(),
8793                 UsedEnd = UsedFieldIndex.end(),
8794                 OrigIter = InitFieldIndex.begin(),
8795                 OrigEnd = InitFieldIndex.end();
8796            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8797         if (*UsedIter < *OrigIter)
8798           return true;
8799         if (*UsedIter > *OrigIter)
8800           break;
8801       }
8802 
8803       // TODO: Add a different warning which will print the field names.
8804       HandleDeclRefExpr(DRE);
8805       return true;
8806     }
8807 
8808     // For most expressions, the cast is directly above the DeclRefExpr.
8809     // For conditional operators, the cast can be outside the conditional
8810     // operator if both expressions are DeclRefExpr's.
8811     void HandleValue(Expr *E) {
8812       E = E->IgnoreParens();
8813       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8814         HandleDeclRefExpr(DRE);
8815         return;
8816       }
8817 
8818       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8819         Visit(CO->getCond());
8820         HandleValue(CO->getTrueExpr());
8821         HandleValue(CO->getFalseExpr());
8822         return;
8823       }
8824 
8825       if (BinaryConditionalOperator *BCO =
8826               dyn_cast<BinaryConditionalOperator>(E)) {
8827         Visit(BCO->getCond());
8828         HandleValue(BCO->getFalseExpr());
8829         return;
8830       }
8831 
8832       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8833         HandleValue(OVE->getSourceExpr());
8834         return;
8835       }
8836 
8837       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8838         if (BO->getOpcode() == BO_Comma) {
8839           Visit(BO->getLHS());
8840           HandleValue(BO->getRHS());
8841           return;
8842         }
8843       }
8844 
8845       if (isa<MemberExpr>(E)) {
8846         if (isInitList) {
8847           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
8848                                       false /*CheckReference*/))
8849             return;
8850         }
8851 
8852         Expr *Base = E->IgnoreParenImpCasts();
8853         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8854           // Check for static member variables and don't warn on them.
8855           if (!isa<FieldDecl>(ME->getMemberDecl()))
8856             return;
8857           Base = ME->getBase()->IgnoreParenImpCasts();
8858         }
8859         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8860           HandleDeclRefExpr(DRE);
8861         return;
8862       }
8863 
8864       Visit(E);
8865     }
8866 
8867     // Reference types not handled in HandleValue are handled here since all
8868     // uses of references are bad, not just r-value uses.
8869     void VisitDeclRefExpr(DeclRefExpr *E) {
8870       if (isReferenceType)
8871         HandleDeclRefExpr(E);
8872     }
8873 
8874     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8875       if (E->getCastKind() == CK_LValueToRValue) {
8876         HandleValue(E->getSubExpr());
8877         return;
8878       }
8879 
8880       Inherited::VisitImplicitCastExpr(E);
8881     }
8882 
8883     void VisitMemberExpr(MemberExpr *E) {
8884       if (isInitList) {
8885         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
8886           return;
8887       }
8888 
8889       // Don't warn on arrays since they can be treated as pointers.
8890       if (E->getType()->canDecayToPointerType()) return;
8891 
8892       // Warn when a non-static method call is followed by non-static member
8893       // field accesses, which is followed by a DeclRefExpr.
8894       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8895       bool Warn = (MD && !MD->isStatic());
8896       Expr *Base = E->getBase()->IgnoreParenImpCasts();
8897       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8898         if (!isa<FieldDecl>(ME->getMemberDecl()))
8899           Warn = false;
8900         Base = ME->getBase()->IgnoreParenImpCasts();
8901       }
8902 
8903       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8904         if (Warn)
8905           HandleDeclRefExpr(DRE);
8906         return;
8907       }
8908 
8909       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8910       // Visit that expression.
8911       Visit(Base);
8912     }
8913 
8914     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8915       Expr *Callee = E->getCallee();
8916 
8917       if (isa<UnresolvedLookupExpr>(Callee))
8918         return Inherited::VisitCXXOperatorCallExpr(E);
8919 
8920       Visit(Callee);
8921       for (auto Arg: E->arguments())
8922         HandleValue(Arg->IgnoreParenImpCasts());
8923     }
8924 
8925     void VisitUnaryOperator(UnaryOperator *E) {
8926       // For POD record types, addresses of its own members are well-defined.
8927       if (E->getOpcode() == UO_AddrOf && isRecordType &&
8928           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8929         if (!isPODType)
8930           HandleValue(E->getSubExpr());
8931         return;
8932       }
8933 
8934       if (E->isIncrementDecrementOp()) {
8935         HandleValue(E->getSubExpr());
8936         return;
8937       }
8938 
8939       Inherited::VisitUnaryOperator(E);
8940     }
8941 
8942     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8943 
8944     void VisitCXXConstructExpr(CXXConstructExpr *E) {
8945       if (E->getConstructor()->isCopyConstructor()) {
8946         Expr *ArgExpr = E->getArg(0);
8947         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
8948           if (ILE->getNumInits() == 1)
8949             ArgExpr = ILE->getInit(0);
8950         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8951           if (ICE->getCastKind() == CK_NoOp)
8952             ArgExpr = ICE->getSubExpr();
8953         HandleValue(ArgExpr);
8954         return;
8955       }
8956       Inherited::VisitCXXConstructExpr(E);
8957     }
8958 
8959     void VisitCallExpr(CallExpr *E) {
8960       // Treat std::move as a use.
8961       if (E->getNumArgs() == 1) {
8962         if (FunctionDecl *FD = E->getDirectCallee()) {
8963           if (FD->isInStdNamespace() && FD->getIdentifier() &&
8964               FD->getIdentifier()->isStr("move")) {
8965             HandleValue(E->getArg(0));
8966             return;
8967           }
8968         }
8969       }
8970 
8971       Inherited::VisitCallExpr(E);
8972     }
8973 
8974     void VisitBinaryOperator(BinaryOperator *E) {
8975       if (E->isCompoundAssignmentOp()) {
8976         HandleValue(E->getLHS());
8977         Visit(E->getRHS());
8978         return;
8979       }
8980 
8981       Inherited::VisitBinaryOperator(E);
8982     }
8983 
8984     // A custom visitor for BinaryConditionalOperator is needed because the
8985     // regular visitor would check the condition and true expression separately
8986     // but both point to the same place giving duplicate diagnostics.
8987     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
8988       Visit(E->getCond());
8989       Visit(E->getFalseExpr());
8990     }
8991 
8992     void HandleDeclRefExpr(DeclRefExpr *DRE) {
8993       Decl* ReferenceDecl = DRE->getDecl();
8994       if (OrigDecl != ReferenceDecl) return;
8995       unsigned diag;
8996       if (isReferenceType) {
8997         diag = diag::warn_uninit_self_reference_in_reference_init;
8998       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8999         diag = diag::warn_static_self_reference_in_init;
9000       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9001                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9002                  DRE->getDecl()->getType()->isRecordType()) {
9003         diag = diag::warn_uninit_self_reference_in_init;
9004       } else {
9005         // Local variables will be handled by the CFG analysis.
9006         return;
9007       }
9008 
9009       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9010                             S.PDiag(diag)
9011                               << DRE->getNameInfo().getName()
9012                               << OrigDecl->getLocation()
9013                               << DRE->getSourceRange());
9014     }
9015   };
9016 
9017   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9018   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9019                                  bool DirectInit) {
9020     // Parameters arguments are occassionially constructed with itself,
9021     // for instance, in recursive functions.  Skip them.
9022     if (isa<ParmVarDecl>(OrigDecl))
9023       return;
9024 
9025     E = E->IgnoreParens();
9026 
9027     // Skip checking T a = a where T is not a record or reference type.
9028     // Doing so is a way to silence uninitialized warnings.
9029     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9030       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9031         if (ICE->getCastKind() == CK_LValueToRValue)
9032           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9033             if (DRE->getDecl() == OrigDecl)
9034               return;
9035 
9036     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9037   }
9038 }
9039 
9040 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9041                                             DeclarationName Name, QualType Type,
9042                                             TypeSourceInfo *TSI,
9043                                             SourceRange Range, bool DirectInit,
9044                                             Expr *Init) {
9045   bool IsInitCapture = !VDecl;
9046   assert((!VDecl || !VDecl->isInitCapture()) &&
9047          "init captures are expected to be deduced prior to initialization");
9048 
9049   ArrayRef<Expr *> DeduceInits = Init;
9050   if (DirectInit) {
9051     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9052       DeduceInits = PL->exprs();
9053     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9054       DeduceInits = IL->inits();
9055   }
9056 
9057   // Deduction only works if we have exactly one source expression.
9058   if (DeduceInits.empty()) {
9059     // It isn't possible to write this directly, but it is possible to
9060     // end up in this situation with "auto x(some_pack...);"
9061     Diag(Init->getLocStart(), IsInitCapture
9062                                   ? diag::err_init_capture_no_expression
9063                                   : diag::err_auto_var_init_no_expression)
9064         << Name << Type << Range;
9065     return QualType();
9066   }
9067 
9068   if (DeduceInits.size() > 1) {
9069     Diag(DeduceInits[1]->getLocStart(),
9070          IsInitCapture ? diag::err_init_capture_multiple_expressions
9071                        : diag::err_auto_var_init_multiple_expressions)
9072         << Name << Type << Range;
9073     return QualType();
9074   }
9075 
9076   Expr *DeduceInit = DeduceInits[0];
9077   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9078     Diag(Init->getLocStart(), IsInitCapture
9079                                   ? diag::err_init_capture_paren_braces
9080                                   : diag::err_auto_var_init_paren_braces)
9081         << isa<InitListExpr>(Init) << Name << Type << Range;
9082     return QualType();
9083   }
9084 
9085   // Expressions default to 'id' when we're in a debugger.
9086   bool DefaultedAnyToId = false;
9087   if (getLangOpts().DebuggerCastResultToId &&
9088       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9089     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9090     if (Result.isInvalid()) {
9091       return QualType();
9092     }
9093     Init = Result.get();
9094     DefaultedAnyToId = true;
9095   }
9096 
9097   QualType DeducedType;
9098   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9099     if (!IsInitCapture)
9100       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9101     else if (isa<InitListExpr>(Init))
9102       Diag(Range.getBegin(),
9103            diag::err_init_capture_deduction_failure_from_init_list)
9104           << Name
9105           << (DeduceInit->getType().isNull() ? TSI->getType()
9106                                              : DeduceInit->getType())
9107           << DeduceInit->getSourceRange();
9108     else
9109       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9110           << Name << TSI->getType()
9111           << (DeduceInit->getType().isNull() ? TSI->getType()
9112                                              : DeduceInit->getType())
9113           << DeduceInit->getSourceRange();
9114   }
9115 
9116   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9117   // 'id' instead of a specific object type prevents most of our usual
9118   // checks.
9119   // We only want to warn outside of template instantiations, though:
9120   // inside a template, the 'id' could have come from a parameter.
9121   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9122       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9123     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9124     Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9125   }
9126 
9127   return DeducedType;
9128 }
9129 
9130 /// AddInitializerToDecl - Adds the initializer Init to the
9131 /// declaration dcl. If DirectInit is true, this is C++ direct
9132 /// initialization rather than copy initialization.
9133 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9134                                 bool DirectInit, bool TypeMayContainAuto) {
9135   // If there is no declaration, there was an error parsing it.  Just ignore
9136   // the initializer.
9137   if (!RealDecl || RealDecl->isInvalidDecl()) {
9138     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9139     return;
9140   }
9141 
9142   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9143     // Pure-specifiers are handled in ActOnPureSpecifier.
9144     Diag(Method->getLocation(), diag::err_member_function_initialization)
9145       << Method->getDeclName() << Init->getSourceRange();
9146     Method->setInvalidDecl();
9147     return;
9148   }
9149 
9150   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9151   if (!VDecl) {
9152     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9153     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9154     RealDecl->setInvalidDecl();
9155     return;
9156   }
9157 
9158   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9159   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9160     // Attempt typo correction early so that the type of the init expression can
9161     // be deduced based on the chosen correction if the original init contains a
9162     // TypoExpr.
9163     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9164     if (!Res.isUsable()) {
9165       RealDecl->setInvalidDecl();
9166       return;
9167     }
9168     Init = Res.get();
9169 
9170     QualType DeducedType = deduceVarTypeFromInitializer(
9171         VDecl, VDecl->getDeclName(), VDecl->getType(),
9172         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9173     if (DeducedType.isNull()) {
9174       RealDecl->setInvalidDecl();
9175       return;
9176     }
9177 
9178     VDecl->setType(DeducedType);
9179     assert(VDecl->isLinkageValid());
9180 
9181     // In ARC, infer lifetime.
9182     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9183       VDecl->setInvalidDecl();
9184 
9185     // If this is a redeclaration, check that the type we just deduced matches
9186     // the previously declared type.
9187     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9188       // We never need to merge the type, because we cannot form an incomplete
9189       // array of auto, nor deduce such a type.
9190       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9191     }
9192 
9193     // Check the deduced type is valid for a variable declaration.
9194     CheckVariableDeclarationType(VDecl);
9195     if (VDecl->isInvalidDecl())
9196       return;
9197   }
9198 
9199   // dllimport cannot be used on variable definitions.
9200   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9201     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9202     VDecl->setInvalidDecl();
9203     return;
9204   }
9205 
9206   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9207     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9208     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9209     VDecl->setInvalidDecl();
9210     return;
9211   }
9212 
9213   if (!VDecl->getType()->isDependentType()) {
9214     // A definition must end up with a complete type, which means it must be
9215     // complete with the restriction that an array type might be completed by
9216     // the initializer; note that later code assumes this restriction.
9217     QualType BaseDeclType = VDecl->getType();
9218     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9219       BaseDeclType = Array->getElementType();
9220     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9221                             diag::err_typecheck_decl_incomplete_type)) {
9222       RealDecl->setInvalidDecl();
9223       return;
9224     }
9225 
9226     // The variable can not have an abstract class type.
9227     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9228                                diag::err_abstract_type_in_decl,
9229                                AbstractVariableType))
9230       VDecl->setInvalidDecl();
9231   }
9232 
9233   VarDecl *Def;
9234   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9235     NamedDecl *Hidden = nullptr;
9236     if (!hasVisibleDefinition(Def, &Hidden) &&
9237         (VDecl->getFormalLinkage() == InternalLinkage ||
9238          VDecl->getDescribedVarTemplate() ||
9239          VDecl->getNumTemplateParameterLists() ||
9240          VDecl->getDeclContext()->isDependentContext())) {
9241       // The previous definition is hidden, and multiple definitions are
9242       // permitted (in separate TUs). Form another definition of it.
9243     } else {
9244       Diag(VDecl->getLocation(), diag::err_redefinition)
9245         << VDecl->getDeclName();
9246       Diag(Def->getLocation(), diag::note_previous_definition);
9247       VDecl->setInvalidDecl();
9248       return;
9249     }
9250   }
9251 
9252   if (getLangOpts().CPlusPlus) {
9253     // C++ [class.static.data]p4
9254     //   If a static data member is of const integral or const
9255     //   enumeration type, its declaration in the class definition can
9256     //   specify a constant-initializer which shall be an integral
9257     //   constant expression (5.19). In that case, the member can appear
9258     //   in integral constant expressions. The member shall still be
9259     //   defined in a namespace scope if it is used in the program and the
9260     //   namespace scope definition shall not contain an initializer.
9261     //
9262     // We already performed a redefinition check above, but for static
9263     // data members we also need to check whether there was an in-class
9264     // declaration with an initializer.
9265     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9266       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9267           << VDecl->getDeclName();
9268       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9269            diag::note_previous_initializer)
9270           << 0;
9271       return;
9272     }
9273 
9274     if (VDecl->hasLocalStorage())
9275       getCurFunction()->setHasBranchProtectedScope();
9276 
9277     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9278       VDecl->setInvalidDecl();
9279       return;
9280     }
9281   }
9282 
9283   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9284   // a kernel function cannot be initialized."
9285   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9286     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9287     VDecl->setInvalidDecl();
9288     return;
9289   }
9290 
9291   // Get the decls type and save a reference for later, since
9292   // CheckInitializerTypes may change it.
9293   QualType DclT = VDecl->getType(), SavT = DclT;
9294 
9295   // Expressions default to 'id' when we're in a debugger
9296   // and we are assigning it to a variable of Objective-C pointer type.
9297   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9298       Init->getType() == Context.UnknownAnyTy) {
9299     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9300     if (Result.isInvalid()) {
9301       VDecl->setInvalidDecl();
9302       return;
9303     }
9304     Init = Result.get();
9305   }
9306 
9307   // Perform the initialization.
9308   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9309   if (!VDecl->isInvalidDecl()) {
9310     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9311     InitializationKind Kind =
9312         DirectInit
9313             ? CXXDirectInit
9314                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9315                                                      Init->getLocStart(),
9316                                                      Init->getLocEnd())
9317                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9318             : InitializationKind::CreateCopy(VDecl->getLocation(),
9319                                              Init->getLocStart());
9320 
9321     MultiExprArg Args = Init;
9322     if (CXXDirectInit)
9323       Args = MultiExprArg(CXXDirectInit->getExprs(),
9324                           CXXDirectInit->getNumExprs());
9325 
9326     // Try to correct any TypoExprs in the initialization arguments.
9327     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9328       ExprResult Res = CorrectDelayedTyposInExpr(
9329           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9330             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9331             return Init.Failed() ? ExprError() : E;
9332           });
9333       if (Res.isInvalid()) {
9334         VDecl->setInvalidDecl();
9335       } else if (Res.get() != Args[Idx]) {
9336         Args[Idx] = Res.get();
9337       }
9338     }
9339     if (VDecl->isInvalidDecl())
9340       return;
9341 
9342     InitializationSequence InitSeq(*this, Entity, Kind, Args);
9343     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9344     if (Result.isInvalid()) {
9345       VDecl->setInvalidDecl();
9346       return;
9347     }
9348 
9349     Init = Result.getAs<Expr>();
9350   }
9351 
9352   // Check for self-references within variable initializers.
9353   // Variables declared within a function/method body (except for references)
9354   // are handled by a dataflow analysis.
9355   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9356       VDecl->getType()->isReferenceType()) {
9357     CheckSelfReference(*this, RealDecl, Init, DirectInit);
9358   }
9359 
9360   // If the type changed, it means we had an incomplete type that was
9361   // completed by the initializer. For example:
9362   //   int ary[] = { 1, 3, 5 };
9363   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9364   if (!VDecl->isInvalidDecl() && (DclT != SavT))
9365     VDecl->setType(DclT);
9366 
9367   if (!VDecl->isInvalidDecl()) {
9368     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9369 
9370     if (VDecl->hasAttr<BlocksAttr>())
9371       checkRetainCycles(VDecl, Init);
9372 
9373     // It is safe to assign a weak reference into a strong variable.
9374     // Although this code can still have problems:
9375     //   id x = self.weakProp;
9376     //   id y = self.weakProp;
9377     // we do not warn to warn spuriously when 'x' and 'y' are on separate
9378     // paths through the function. This should be revisited if
9379     // -Wrepeated-use-of-weak is made flow-sensitive.
9380     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9381         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9382                          Init->getLocStart()))
9383       getCurFunction()->markSafeWeakUse(Init);
9384   }
9385 
9386   // The initialization is usually a full-expression.
9387   //
9388   // FIXME: If this is a braced initialization of an aggregate, it is not
9389   // an expression, and each individual field initializer is a separate
9390   // full-expression. For instance, in:
9391   //
9392   //   struct Temp { ~Temp(); };
9393   //   struct S { S(Temp); };
9394   //   struct T { S a, b; } t = { Temp(), Temp() }
9395   //
9396   // we should destroy the first Temp before constructing the second.
9397   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9398                                           false,
9399                                           VDecl->isConstexpr());
9400   if (Result.isInvalid()) {
9401     VDecl->setInvalidDecl();
9402     return;
9403   }
9404   Init = Result.get();
9405 
9406   // Attach the initializer to the decl.
9407   VDecl->setInit(Init);
9408 
9409   if (VDecl->isLocalVarDecl()) {
9410     // C99 6.7.8p4: All the expressions in an initializer for an object that has
9411     // static storage duration shall be constant expressions or string literals.
9412     // C++ does not have this restriction.
9413     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9414       const Expr *Culprit;
9415       if (VDecl->getStorageClass() == SC_Static)
9416         CheckForConstantInitializer(Init, DclT);
9417       // C89 is stricter than C99 for non-static aggregate types.
9418       // C89 6.5.7p3: All the expressions [...] in an initializer list
9419       // for an object that has aggregate or union type shall be
9420       // constant expressions.
9421       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9422                isa<InitListExpr>(Init) &&
9423                !Init->isConstantInitializer(Context, false, &Culprit))
9424         Diag(Culprit->getExprLoc(),
9425              diag::ext_aggregate_init_not_constant)
9426           << Culprit->getSourceRange();
9427     }
9428   } else if (VDecl->isStaticDataMember() &&
9429              VDecl->getLexicalDeclContext()->isRecord()) {
9430     // This is an in-class initialization for a static data member, e.g.,
9431     //
9432     // struct S {
9433     //   static const int value = 17;
9434     // };
9435 
9436     // C++ [class.mem]p4:
9437     //   A member-declarator can contain a constant-initializer only
9438     //   if it declares a static member (9.4) of const integral or
9439     //   const enumeration type, see 9.4.2.
9440     //
9441     // C++11 [class.static.data]p3:
9442     //   If a non-volatile const static data member is of integral or
9443     //   enumeration type, its declaration in the class definition can
9444     //   specify a brace-or-equal-initializer in which every initalizer-clause
9445     //   that is an assignment-expression is a constant expression. A static
9446     //   data member of literal type can be declared in the class definition
9447     //   with the constexpr specifier; if so, its declaration shall specify a
9448     //   brace-or-equal-initializer in which every initializer-clause that is
9449     //   an assignment-expression is a constant expression.
9450 
9451     // Do nothing on dependent types.
9452     if (DclT->isDependentType()) {
9453 
9454     // Allow any 'static constexpr' members, whether or not they are of literal
9455     // type. We separately check that every constexpr variable is of literal
9456     // type.
9457     } else if (VDecl->isConstexpr()) {
9458 
9459     // Require constness.
9460     } else if (!DclT.isConstQualified()) {
9461       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9462         << Init->getSourceRange();
9463       VDecl->setInvalidDecl();
9464 
9465     // We allow integer constant expressions in all cases.
9466     } else if (DclT->isIntegralOrEnumerationType()) {
9467       // Check whether the expression is a constant expression.
9468       SourceLocation Loc;
9469       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9470         // In C++11, a non-constexpr const static data member with an
9471         // in-class initializer cannot be volatile.
9472         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9473       else if (Init->isValueDependent())
9474         ; // Nothing to check.
9475       else if (Init->isIntegerConstantExpr(Context, &Loc))
9476         ; // Ok, it's an ICE!
9477       else if (Init->isEvaluatable(Context)) {
9478         // If we can constant fold the initializer through heroics, accept it,
9479         // but report this as a use of an extension for -pedantic.
9480         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9481           << Init->getSourceRange();
9482       } else {
9483         // Otherwise, this is some crazy unknown case.  Report the issue at the
9484         // location provided by the isIntegerConstantExpr failed check.
9485         Diag(Loc, diag::err_in_class_initializer_non_constant)
9486           << Init->getSourceRange();
9487         VDecl->setInvalidDecl();
9488       }
9489 
9490     // We allow foldable floating-point constants as an extension.
9491     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9492       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9493       // it anyway and provide a fixit to add the 'constexpr'.
9494       if (getLangOpts().CPlusPlus11) {
9495         Diag(VDecl->getLocation(),
9496              diag::ext_in_class_initializer_float_type_cxx11)
9497             << DclT << Init->getSourceRange();
9498         Diag(VDecl->getLocStart(),
9499              diag::note_in_class_initializer_float_type_cxx11)
9500             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9501       } else {
9502         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9503           << DclT << Init->getSourceRange();
9504 
9505         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9506           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9507             << Init->getSourceRange();
9508           VDecl->setInvalidDecl();
9509         }
9510       }
9511 
9512     // Suggest adding 'constexpr' in C++11 for literal types.
9513     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9514       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9515         << DclT << Init->getSourceRange()
9516         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9517       VDecl->setConstexpr(true);
9518 
9519     } else {
9520       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9521         << DclT << Init->getSourceRange();
9522       VDecl->setInvalidDecl();
9523     }
9524   } else if (VDecl->isFileVarDecl()) {
9525     if (VDecl->getStorageClass() == SC_Extern &&
9526         (!getLangOpts().CPlusPlus ||
9527          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9528            VDecl->isExternC())) &&
9529         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9530       Diag(VDecl->getLocation(), diag::warn_extern_init);
9531 
9532     // C99 6.7.8p4. All file scoped initializers need to be constant.
9533     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9534       CheckForConstantInitializer(Init, DclT);
9535   }
9536 
9537   // We will represent direct-initialization similarly to copy-initialization:
9538   //    int x(1);  -as-> int x = 1;
9539   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9540   //
9541   // Clients that want to distinguish between the two forms, can check for
9542   // direct initializer using VarDecl::getInitStyle().
9543   // A major benefit is that clients that don't particularly care about which
9544   // exactly form was it (like the CodeGen) can handle both cases without
9545   // special case code.
9546 
9547   // C++ 8.5p11:
9548   // The form of initialization (using parentheses or '=') is generally
9549   // insignificant, but does matter when the entity being initialized has a
9550   // class type.
9551   if (CXXDirectInit) {
9552     assert(DirectInit && "Call-style initializer must be direct init.");
9553     VDecl->setInitStyle(VarDecl::CallInit);
9554   } else if (DirectInit) {
9555     // This must be list-initialization. No other way is direct-initialization.
9556     VDecl->setInitStyle(VarDecl::ListInit);
9557   }
9558 
9559   CheckCompleteVariableDeclaration(VDecl);
9560 }
9561 
9562 /// ActOnInitializerError - Given that there was an error parsing an
9563 /// initializer for the given declaration, try to return to some form
9564 /// of sanity.
9565 void Sema::ActOnInitializerError(Decl *D) {
9566   // Our main concern here is re-establishing invariants like "a
9567   // variable's type is either dependent or complete".
9568   if (!D || D->isInvalidDecl()) return;
9569 
9570   VarDecl *VD = dyn_cast<VarDecl>(D);
9571   if (!VD) return;
9572 
9573   // Auto types are meaningless if we can't make sense of the initializer.
9574   if (ParsingInitForAutoVars.count(D)) {
9575     D->setInvalidDecl();
9576     return;
9577   }
9578 
9579   QualType Ty = VD->getType();
9580   if (Ty->isDependentType()) return;
9581 
9582   // Require a complete type.
9583   if (RequireCompleteType(VD->getLocation(),
9584                           Context.getBaseElementType(Ty),
9585                           diag::err_typecheck_decl_incomplete_type)) {
9586     VD->setInvalidDecl();
9587     return;
9588   }
9589 
9590   // Require a non-abstract type.
9591   if (RequireNonAbstractType(VD->getLocation(), Ty,
9592                              diag::err_abstract_type_in_decl,
9593                              AbstractVariableType)) {
9594     VD->setInvalidDecl();
9595     return;
9596   }
9597 
9598   // Don't bother complaining about constructors or destructors,
9599   // though.
9600 }
9601 
9602 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9603                                   bool TypeMayContainAuto) {
9604   // If there is no declaration, there was an error parsing it. Just ignore it.
9605   if (!RealDecl)
9606     return;
9607 
9608   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9609     QualType Type = Var->getType();
9610 
9611     // C++11 [dcl.spec.auto]p3
9612     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9613       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9614         << Var->getDeclName() << Type;
9615       Var->setInvalidDecl();
9616       return;
9617     }
9618 
9619     // C++11 [class.static.data]p3: A static data member can be declared with
9620     // the constexpr specifier; if so, its declaration shall specify
9621     // a brace-or-equal-initializer.
9622     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9623     // the definition of a variable [...] or the declaration of a static data
9624     // member.
9625     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9626       if (Var->isStaticDataMember())
9627         Diag(Var->getLocation(),
9628              diag::err_constexpr_static_mem_var_requires_init)
9629           << Var->getDeclName();
9630       else
9631         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9632       Var->setInvalidDecl();
9633       return;
9634     }
9635 
9636     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
9637     // definition having the concept specifier is called a variable concept. A
9638     // concept definition refers to [...] a variable concept and its initializer.
9639     if (Var->isConcept()) {
9640       Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
9641       Var->setInvalidDecl();
9642       return;
9643     }
9644 
9645     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9646     // be initialized.
9647     if (!Var->isInvalidDecl() &&
9648         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9649         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9650       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9651       Var->setInvalidDecl();
9652       return;
9653     }
9654 
9655     switch (Var->isThisDeclarationADefinition()) {
9656     case VarDecl::Definition:
9657       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9658         break;
9659 
9660       // We have an out-of-line definition of a static data member
9661       // that has an in-class initializer, so we type-check this like
9662       // a declaration.
9663       //
9664       // Fall through
9665 
9666     case VarDecl::DeclarationOnly:
9667       // It's only a declaration.
9668 
9669       // Block scope. C99 6.7p7: If an identifier for an object is
9670       // declared with no linkage (C99 6.2.2p6), the type for the
9671       // object shall be complete.
9672       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9673           !Var->hasLinkage() && !Var->isInvalidDecl() &&
9674           RequireCompleteType(Var->getLocation(), Type,
9675                               diag::err_typecheck_decl_incomplete_type))
9676         Var->setInvalidDecl();
9677 
9678       // Make sure that the type is not abstract.
9679       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9680           RequireNonAbstractType(Var->getLocation(), Type,
9681                                  diag::err_abstract_type_in_decl,
9682                                  AbstractVariableType))
9683         Var->setInvalidDecl();
9684       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9685           Var->getStorageClass() == SC_PrivateExtern) {
9686         Diag(Var->getLocation(), diag::warn_private_extern);
9687         Diag(Var->getLocation(), diag::note_private_extern);
9688       }
9689 
9690       return;
9691 
9692     case VarDecl::TentativeDefinition:
9693       // File scope. C99 6.9.2p2: A declaration of an identifier for an
9694       // object that has file scope without an initializer, and without a
9695       // storage-class specifier or with the storage-class specifier "static",
9696       // constitutes a tentative definition. Note: A tentative definition with
9697       // external linkage is valid (C99 6.2.2p5).
9698       if (!Var->isInvalidDecl()) {
9699         if (const IncompleteArrayType *ArrayT
9700                                     = Context.getAsIncompleteArrayType(Type)) {
9701           if (RequireCompleteType(Var->getLocation(),
9702                                   ArrayT->getElementType(),
9703                                   diag::err_illegal_decl_array_incomplete_type))
9704             Var->setInvalidDecl();
9705         } else if (Var->getStorageClass() == SC_Static) {
9706           // C99 6.9.2p3: If the declaration of an identifier for an object is
9707           // a tentative definition and has internal linkage (C99 6.2.2p3), the
9708           // declared type shall not be an incomplete type.
9709           // NOTE: code such as the following
9710           //     static struct s;
9711           //     struct s { int a; };
9712           // is accepted by gcc. Hence here we issue a warning instead of
9713           // an error and we do not invalidate the static declaration.
9714           // NOTE: to avoid multiple warnings, only check the first declaration.
9715           if (Var->isFirstDecl())
9716             RequireCompleteType(Var->getLocation(), Type,
9717                                 diag::ext_typecheck_decl_incomplete_type);
9718         }
9719       }
9720 
9721       // Record the tentative definition; we're done.
9722       if (!Var->isInvalidDecl())
9723         TentativeDefinitions.push_back(Var);
9724       return;
9725     }
9726 
9727     // Provide a specific diagnostic for uninitialized variable
9728     // definitions with incomplete array type.
9729     if (Type->isIncompleteArrayType()) {
9730       Diag(Var->getLocation(),
9731            diag::err_typecheck_incomplete_array_needs_initializer);
9732       Var->setInvalidDecl();
9733       return;
9734     }
9735 
9736     // Provide a specific diagnostic for uninitialized variable
9737     // definitions with reference type.
9738     if (Type->isReferenceType()) {
9739       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9740         << Var->getDeclName()
9741         << SourceRange(Var->getLocation(), Var->getLocation());
9742       Var->setInvalidDecl();
9743       return;
9744     }
9745 
9746     // Do not attempt to type-check the default initializer for a
9747     // variable with dependent type.
9748     if (Type->isDependentType())
9749       return;
9750 
9751     if (Var->isInvalidDecl())
9752       return;
9753 
9754     if (!Var->hasAttr<AliasAttr>()) {
9755       if (RequireCompleteType(Var->getLocation(),
9756                               Context.getBaseElementType(Type),
9757                               diag::err_typecheck_decl_incomplete_type)) {
9758         Var->setInvalidDecl();
9759         return;
9760       }
9761     } else {
9762       return;
9763     }
9764 
9765     // The variable can not have an abstract class type.
9766     if (RequireNonAbstractType(Var->getLocation(), Type,
9767                                diag::err_abstract_type_in_decl,
9768                                AbstractVariableType)) {
9769       Var->setInvalidDecl();
9770       return;
9771     }
9772 
9773     // Check for jumps past the implicit initializer.  C++0x
9774     // clarifies that this applies to a "variable with automatic
9775     // storage duration", not a "local variable".
9776     // C++11 [stmt.dcl]p3
9777     //   A program that jumps from a point where a variable with automatic
9778     //   storage duration is not in scope to a point where it is in scope is
9779     //   ill-formed unless the variable has scalar type, class type with a
9780     //   trivial default constructor and a trivial destructor, a cv-qualified
9781     //   version of one of these types, or an array of one of the preceding
9782     //   types and is declared without an initializer.
9783     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9784       if (const RecordType *Record
9785             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
9786         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9787         // Mark the function for further checking even if the looser rules of
9788         // C++11 do not require such checks, so that we can diagnose
9789         // incompatibilities with C++98.
9790         if (!CXXRecord->isPOD())
9791           getCurFunction()->setHasBranchProtectedScope();
9792       }
9793     }
9794 
9795     // C++03 [dcl.init]p9:
9796     //   If no initializer is specified for an object, and the
9797     //   object is of (possibly cv-qualified) non-POD class type (or
9798     //   array thereof), the object shall be default-initialized; if
9799     //   the object is of const-qualified type, the underlying class
9800     //   type shall have a user-declared default
9801     //   constructor. Otherwise, if no initializer is specified for
9802     //   a non- static object, the object and its subobjects, if
9803     //   any, have an indeterminate initial value); if the object
9804     //   or any of its subobjects are of const-qualified type, the
9805     //   program is ill-formed.
9806     // C++0x [dcl.init]p11:
9807     //   If no initializer is specified for an object, the object is
9808     //   default-initialized; [...].
9809     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
9810     InitializationKind Kind
9811       = InitializationKind::CreateDefault(Var->getLocation());
9812 
9813     InitializationSequence InitSeq(*this, Entity, Kind, None);
9814     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
9815     if (Init.isInvalid())
9816       Var->setInvalidDecl();
9817     else if (Init.get()) {
9818       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
9819       // This is important for template substitution.
9820       Var->setInitStyle(VarDecl::CallInit);
9821     }
9822 
9823     CheckCompleteVariableDeclaration(Var);
9824   }
9825 }
9826 
9827 void Sema::ActOnCXXForRangeDecl(Decl *D) {
9828   VarDecl *VD = dyn_cast<VarDecl>(D);
9829   if (!VD) {
9830     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9831     D->setInvalidDecl();
9832     return;
9833   }
9834 
9835   VD->setCXXForRangeDecl(true);
9836 
9837   // for-range-declaration cannot be given a storage class specifier.
9838   int Error = -1;
9839   switch (VD->getStorageClass()) {
9840   case SC_None:
9841     break;
9842   case SC_Extern:
9843     Error = 0;
9844     break;
9845   case SC_Static:
9846     Error = 1;
9847     break;
9848   case SC_PrivateExtern:
9849     Error = 2;
9850     break;
9851   case SC_Auto:
9852     Error = 3;
9853     break;
9854   case SC_Register:
9855     Error = 4;
9856     break;
9857   }
9858   if (Error != -1) {
9859     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
9860       << VD->getDeclName() << Error;
9861     D->setInvalidDecl();
9862   }
9863 }
9864 
9865 StmtResult
9866 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
9867                                  IdentifierInfo *Ident,
9868                                  ParsedAttributes &Attrs,
9869                                  SourceLocation AttrEnd) {
9870   // C++1y [stmt.iter]p1:
9871   //   A range-based for statement of the form
9872   //      for ( for-range-identifier : for-range-initializer ) statement
9873   //   is equivalent to
9874   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
9875   DeclSpec DS(Attrs.getPool().getFactory());
9876 
9877   const char *PrevSpec;
9878   unsigned DiagID;
9879   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
9880                      getPrintingPolicy());
9881 
9882   Declarator D(DS, Declarator::ForContext);
9883   D.SetIdentifier(Ident, IdentLoc);
9884   D.takeAttributes(Attrs, AttrEnd);
9885 
9886   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
9887   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
9888                 EmptyAttrs, IdentLoc);
9889   Decl *Var = ActOnDeclarator(S, D);
9890   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
9891   FinalizeDeclaration(Var);
9892   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
9893                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
9894 }
9895 
9896 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
9897   if (var->isInvalidDecl()) return;
9898 
9899   // In Objective-C, don't allow jumps past the implicit initialization of a
9900   // local retaining variable.
9901   if (getLangOpts().ObjC1 &&
9902       var->hasLocalStorage()) {
9903     switch (var->getType().getObjCLifetime()) {
9904     case Qualifiers::OCL_None:
9905     case Qualifiers::OCL_ExplicitNone:
9906     case Qualifiers::OCL_Autoreleasing:
9907       break;
9908 
9909     case Qualifiers::OCL_Weak:
9910     case Qualifiers::OCL_Strong:
9911       getCurFunction()->setHasBranchProtectedScope();
9912       break;
9913     }
9914   }
9915 
9916   // Warn about externally-visible variables being defined without a
9917   // prior declaration.  We only want to do this for global
9918   // declarations, but we also specifically need to avoid doing it for
9919   // class members because the linkage of an anonymous class can
9920   // change if it's later given a typedef name.
9921   if (var->isThisDeclarationADefinition() &&
9922       var->getDeclContext()->getRedeclContext()->isFileContext() &&
9923       var->isExternallyVisible() && var->hasLinkage() &&
9924       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
9925                                   var->getLocation())) {
9926     // Find a previous declaration that's not a definition.
9927     VarDecl *prev = var->getPreviousDecl();
9928     while (prev && prev->isThisDeclarationADefinition())
9929       prev = prev->getPreviousDecl();
9930 
9931     if (!prev)
9932       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
9933   }
9934 
9935   if (var->getTLSKind() == VarDecl::TLS_Static) {
9936     const Expr *Culprit;
9937     if (var->getType().isDestructedType()) {
9938       // GNU C++98 edits for __thread, [basic.start.term]p3:
9939       //   The type of an object with thread storage duration shall not
9940       //   have a non-trivial destructor.
9941       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
9942       if (getLangOpts().CPlusPlus11)
9943         Diag(var->getLocation(), diag::note_use_thread_local);
9944     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
9945                !var->getInit()->isConstantInitializer(
9946                    Context, var->getType()->isReferenceType(), &Culprit)) {
9947       // GNU C++98 edits for __thread, [basic.start.init]p4:
9948       //   An object of thread storage duration shall not require dynamic
9949       //   initialization.
9950       // FIXME: Need strict checking here.
9951       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
9952         << Culprit->getSourceRange();
9953       if (getLangOpts().CPlusPlus11)
9954         Diag(var->getLocation(), diag::note_use_thread_local);
9955     }
9956 
9957   }
9958 
9959   // Apply section attributes and pragmas to global variables.
9960   bool GlobalStorage = var->hasGlobalStorage();
9961   if (GlobalStorage && var->isThisDeclarationADefinition() &&
9962       ActiveTemplateInstantiations.empty()) {
9963     PragmaStack<StringLiteral *> *Stack = nullptr;
9964     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
9965     if (var->getType().isConstQualified())
9966       Stack = &ConstSegStack;
9967     else if (!var->getInit()) {
9968       Stack = &BSSSegStack;
9969       SectionFlags |= ASTContext::PSF_Write;
9970     } else {
9971       Stack = &DataSegStack;
9972       SectionFlags |= ASTContext::PSF_Write;
9973     }
9974     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
9975       var->addAttr(SectionAttr::CreateImplicit(
9976           Context, SectionAttr::Declspec_allocate,
9977           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
9978     }
9979     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
9980       if (UnifySection(SA->getName(), SectionFlags, var))
9981         var->dropAttr<SectionAttr>();
9982 
9983     // Apply the init_seg attribute if this has an initializer.  If the
9984     // initializer turns out to not be dynamic, we'll end up ignoring this
9985     // attribute.
9986     if (CurInitSeg && var->getInit())
9987       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
9988                                                CurInitSegLoc));
9989   }
9990 
9991   // All the following checks are C++ only.
9992   if (!getLangOpts().CPlusPlus) return;
9993 
9994   QualType type = var->getType();
9995   if (type->isDependentType()) return;
9996 
9997   // __block variables might require us to capture a copy-initializer.
9998   if (var->hasAttr<BlocksAttr>()) {
9999     // It's currently invalid to ever have a __block variable with an
10000     // array type; should we diagnose that here?
10001 
10002     // Regardless, we don't want to ignore array nesting when
10003     // constructing this copy.
10004     if (type->isStructureOrClassType()) {
10005       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10006       SourceLocation poi = var->getLocation();
10007       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10008       ExprResult result
10009         = PerformMoveOrCopyInitialization(
10010             InitializedEntity::InitializeBlock(poi, type, false),
10011             var, var->getType(), varRef, /*AllowNRVO=*/true);
10012       if (!result.isInvalid()) {
10013         result = MaybeCreateExprWithCleanups(result);
10014         Expr *init = result.getAs<Expr>();
10015         Context.setBlockVarCopyInits(var, init);
10016       }
10017     }
10018   }
10019 
10020   Expr *Init = var->getInit();
10021   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10022   QualType baseType = Context.getBaseElementType(type);
10023 
10024   if (!var->getDeclContext()->isDependentContext() &&
10025       Init && !Init->isValueDependent()) {
10026     if (IsGlobal && !var->isConstexpr() &&
10027         !getDiagnostics().isIgnored(diag::warn_global_constructor,
10028                                     var->getLocation())) {
10029       // Warn about globals which don't have a constant initializer.  Don't
10030       // warn about globals with a non-trivial destructor because we already
10031       // warned about them.
10032       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10033       if (!(RD && !RD->hasTrivialDestructor()) &&
10034           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10035         Diag(var->getLocation(), diag::warn_global_constructor)
10036           << Init->getSourceRange();
10037     }
10038 
10039     if (var->isConstexpr()) {
10040       SmallVector<PartialDiagnosticAt, 8> Notes;
10041       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10042         SourceLocation DiagLoc = var->getLocation();
10043         // If the note doesn't add any useful information other than a source
10044         // location, fold it into the primary diagnostic.
10045         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10046               diag::note_invalid_subexpr_in_const_expr) {
10047           DiagLoc = Notes[0].first;
10048           Notes.clear();
10049         }
10050         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10051           << var << Init->getSourceRange();
10052         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10053           Diag(Notes[I].first, Notes[I].second);
10054       }
10055     } else if (var->isUsableInConstantExpressions(Context)) {
10056       // Check whether the initializer of a const variable of integral or
10057       // enumeration type is an ICE now, since we can't tell whether it was
10058       // initialized by a constant expression if we check later.
10059       var->checkInitIsICE();
10060     }
10061   }
10062 
10063   // Require the destructor.
10064   if (const RecordType *recordType = baseType->getAs<RecordType>())
10065     FinalizeVarWithDestructor(var, recordType);
10066 }
10067 
10068 /// \brief Determines if a variable's alignment is dependent.
10069 static bool hasDependentAlignment(VarDecl *VD) {
10070   if (VD->getType()->isDependentType())
10071     return true;
10072   for (auto *I : VD->specific_attrs<AlignedAttr>())
10073     if (I->isAlignmentDependent())
10074       return true;
10075   return false;
10076 }
10077 
10078 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10079 /// any semantic actions necessary after any initializer has been attached.
10080 void
10081 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10082   // Note that we are no longer parsing the initializer for this declaration.
10083   ParsingInitForAutoVars.erase(ThisDecl);
10084 
10085   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10086   if (!VD)
10087     return;
10088 
10089   checkAttributesAfterMerging(*this, *VD);
10090 
10091   // Perform TLS alignment check here after attributes attached to the variable
10092   // which may affect the alignment have been processed. Only perform the check
10093   // if the target has a maximum TLS alignment (zero means no constraints).
10094   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10095     // Protect the check so that it's not performed on dependent types and
10096     // dependent alignments (we can't determine the alignment in that case).
10097     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10098       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10099       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10100         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10101           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10102           << (unsigned)MaxAlignChars.getQuantity();
10103       }
10104     }
10105   }
10106 
10107   // Static locals inherit dll attributes from their function.
10108   if (VD->isStaticLocal()) {
10109     if (FunctionDecl *FD =
10110             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10111       if (Attr *A = getDLLAttr(FD)) {
10112         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10113         NewAttr->setInherited(true);
10114         VD->addAttr(NewAttr);
10115       }
10116     }
10117   }
10118 
10119   // Grab the dllimport or dllexport attribute off of the VarDecl.
10120   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10121 
10122   // Imported static data members cannot be defined out-of-line.
10123   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10124     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10125         VD->isThisDeclarationADefinition()) {
10126       // We allow definitions of dllimport class template static data members
10127       // with a warning.
10128       CXXRecordDecl *Context =
10129         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10130       bool IsClassTemplateMember =
10131           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10132           Context->getDescribedClassTemplate();
10133 
10134       Diag(VD->getLocation(),
10135            IsClassTemplateMember
10136                ? diag::warn_attribute_dllimport_static_field_definition
10137                : diag::err_attribute_dllimport_static_field_definition);
10138       Diag(IA->getLocation(), diag::note_attribute);
10139       if (!IsClassTemplateMember)
10140         VD->setInvalidDecl();
10141     }
10142   }
10143 
10144   // dllimport/dllexport variables cannot be thread local, their TLS index
10145   // isn't exported with the variable.
10146   if (DLLAttr && VD->getTLSKind()) {
10147     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10148     if (F && getDLLAttr(F)) {
10149       assert(VD->isStaticLocal());
10150       // But if this is a static local in a dlimport/dllexport function, the
10151       // function will never be inlined, which means the var would never be
10152       // imported, so having it marked import/export is safe.
10153     } else {
10154       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10155                                                                     << DLLAttr;
10156       VD->setInvalidDecl();
10157     }
10158   }
10159 
10160   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10161     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10162       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10163       VD->dropAttr<UsedAttr>();
10164     }
10165   }
10166 
10167   const DeclContext *DC = VD->getDeclContext();
10168   // If there's a #pragma GCC visibility in scope, and this isn't a class
10169   // member, set the visibility of this variable.
10170   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10171     AddPushedVisibilityAttribute(VD);
10172 
10173   // FIXME: Warn on unused templates.
10174   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10175       !isa<VarTemplatePartialSpecializationDecl>(VD))
10176     MarkUnusedFileScopedDecl(VD);
10177 
10178   // Now we have parsed the initializer and can update the table of magic
10179   // tag values.
10180   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10181       !VD->getType()->isIntegralOrEnumerationType())
10182     return;
10183 
10184   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10185     const Expr *MagicValueExpr = VD->getInit();
10186     if (!MagicValueExpr) {
10187       continue;
10188     }
10189     llvm::APSInt MagicValueInt;
10190     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10191       Diag(I->getRange().getBegin(),
10192            diag::err_type_tag_for_datatype_not_ice)
10193         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10194       continue;
10195     }
10196     if (MagicValueInt.getActiveBits() > 64) {
10197       Diag(I->getRange().getBegin(),
10198            diag::err_type_tag_for_datatype_too_large)
10199         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10200       continue;
10201     }
10202     uint64_t MagicValue = MagicValueInt.getZExtValue();
10203     RegisterTypeTagForDatatype(I->getArgumentKind(),
10204                                MagicValue,
10205                                I->getMatchingCType(),
10206                                I->getLayoutCompatible(),
10207                                I->getMustBeNull());
10208   }
10209 }
10210 
10211 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10212                                                    ArrayRef<Decl *> Group) {
10213   SmallVector<Decl*, 8> Decls;
10214 
10215   if (DS.isTypeSpecOwned())
10216     Decls.push_back(DS.getRepAsDecl());
10217 
10218   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10219   for (unsigned i = 0, e = Group.size(); i != e; ++i)
10220     if (Decl *D = Group[i]) {
10221       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10222         if (!FirstDeclaratorInGroup)
10223           FirstDeclaratorInGroup = DD;
10224       Decls.push_back(D);
10225     }
10226 
10227   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10228     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10229       handleTagNumbering(Tag, S);
10230       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10231           getLangOpts().CPlusPlus)
10232         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10233     }
10234   }
10235 
10236   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10237 }
10238 
10239 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10240 /// group, performing any necessary semantic checking.
10241 Sema::DeclGroupPtrTy
10242 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10243                            bool TypeMayContainAuto) {
10244   // C++0x [dcl.spec.auto]p7:
10245   //   If the type deduced for the template parameter U is not the same in each
10246   //   deduction, the program is ill-formed.
10247   // FIXME: When initializer-list support is added, a distinction is needed
10248   // between the deduced type U and the deduced type which 'auto' stands for.
10249   //   auto a = 0, b = { 1, 2, 3 };
10250   // is legal because the deduced type U is 'int' in both cases.
10251   if (TypeMayContainAuto && Group.size() > 1) {
10252     QualType Deduced;
10253     CanQualType DeducedCanon;
10254     VarDecl *DeducedDecl = nullptr;
10255     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10256       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10257         AutoType *AT = D->getType()->getContainedAutoType();
10258         // Don't reissue diagnostics when instantiating a template.
10259         if (AT && D->isInvalidDecl())
10260           break;
10261         QualType U = AT ? AT->getDeducedType() : QualType();
10262         if (!U.isNull()) {
10263           CanQualType UCanon = Context.getCanonicalType(U);
10264           if (Deduced.isNull()) {
10265             Deduced = U;
10266             DeducedCanon = UCanon;
10267             DeducedDecl = D;
10268           } else if (DeducedCanon != UCanon) {
10269             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10270                  diag::err_auto_different_deductions)
10271               << (unsigned)AT->getKeyword()
10272               << Deduced << DeducedDecl->getDeclName()
10273               << U << D->getDeclName()
10274               << DeducedDecl->getInit()->getSourceRange()
10275               << D->getInit()->getSourceRange();
10276             D->setInvalidDecl();
10277             break;
10278           }
10279         }
10280       }
10281     }
10282   }
10283 
10284   ActOnDocumentableDecls(Group);
10285 
10286   return DeclGroupPtrTy::make(
10287       DeclGroupRef::Create(Context, Group.data(), Group.size()));
10288 }
10289 
10290 void Sema::ActOnDocumentableDecl(Decl *D) {
10291   ActOnDocumentableDecls(D);
10292 }
10293 
10294 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10295   // Don't parse the comment if Doxygen diagnostics are ignored.
10296   if (Group.empty() || !Group[0])
10297     return;
10298 
10299   if (Diags.isIgnored(diag::warn_doc_param_not_found,
10300                       Group[0]->getLocation()) &&
10301       Diags.isIgnored(diag::warn_unknown_comment_command_name,
10302                       Group[0]->getLocation()))
10303     return;
10304 
10305   if (Group.size() >= 2) {
10306     // This is a decl group.  Normally it will contain only declarations
10307     // produced from declarator list.  But in case we have any definitions or
10308     // additional declaration references:
10309     //   'typedef struct S {} S;'
10310     //   'typedef struct S *S;'
10311     //   'struct S *pS;'
10312     // FinalizeDeclaratorGroup adds these as separate declarations.
10313     Decl *MaybeTagDecl = Group[0];
10314     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10315       Group = Group.slice(1);
10316     }
10317   }
10318 
10319   // See if there are any new comments that are not attached to a decl.
10320   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10321   if (!Comments.empty() &&
10322       !Comments.back()->isAttached()) {
10323     // There is at least one comment that not attached to a decl.
10324     // Maybe it should be attached to one of these decls?
10325     //
10326     // Note that this way we pick up not only comments that precede the
10327     // declaration, but also comments that *follow* the declaration -- thanks to
10328     // the lookahead in the lexer: we've consumed the semicolon and looked
10329     // ahead through comments.
10330     for (unsigned i = 0, e = Group.size(); i != e; ++i)
10331       Context.getCommentForDecl(Group[i], &PP);
10332   }
10333 }
10334 
10335 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10336 /// to introduce parameters into function prototype scope.
10337 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10338   const DeclSpec &DS = D.getDeclSpec();
10339 
10340   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10341 
10342   // C++03 [dcl.stc]p2 also permits 'auto'.
10343   StorageClass SC = SC_None;
10344   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10345     SC = SC_Register;
10346   } else if (getLangOpts().CPlusPlus &&
10347              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10348     SC = SC_Auto;
10349   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10350     Diag(DS.getStorageClassSpecLoc(),
10351          diag::err_invalid_storage_class_in_func_decl);
10352     D.getMutableDeclSpec().ClearStorageClassSpecs();
10353   }
10354 
10355   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10356     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10357       << DeclSpec::getSpecifierName(TSCS);
10358   if (DS.isConstexprSpecified())
10359     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10360       << 0;
10361   if (DS.isConceptSpecified())
10362     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10363 
10364   DiagnoseFunctionSpecifiers(DS);
10365 
10366   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10367   QualType parmDeclType = TInfo->getType();
10368 
10369   if (getLangOpts().CPlusPlus) {
10370     // Check that there are no default arguments inside the type of this
10371     // parameter.
10372     CheckExtraCXXDefaultArguments(D);
10373 
10374     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10375     if (D.getCXXScopeSpec().isSet()) {
10376       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10377         << D.getCXXScopeSpec().getRange();
10378       D.getCXXScopeSpec().clear();
10379     }
10380   }
10381 
10382   // Ensure we have a valid name
10383   IdentifierInfo *II = nullptr;
10384   if (D.hasName()) {
10385     II = D.getIdentifier();
10386     if (!II) {
10387       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10388         << GetNameForDeclarator(D).getName();
10389       D.setInvalidType(true);
10390     }
10391   }
10392 
10393   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10394   if (II) {
10395     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10396                    ForRedeclaration);
10397     LookupName(R, S);
10398     if (R.isSingleResult()) {
10399       NamedDecl *PrevDecl = R.getFoundDecl();
10400       if (PrevDecl->isTemplateParameter()) {
10401         // Maybe we will complain about the shadowed template parameter.
10402         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10403         // Just pretend that we didn't see the previous declaration.
10404         PrevDecl = nullptr;
10405       } else if (S->isDeclScope(PrevDecl)) {
10406         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10407         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10408 
10409         // Recover by removing the name
10410         II = nullptr;
10411         D.SetIdentifier(nullptr, D.getIdentifierLoc());
10412         D.setInvalidType(true);
10413       }
10414     }
10415   }
10416 
10417   // Temporarily put parameter variables in the translation unit, not
10418   // the enclosing context.  This prevents them from accidentally
10419   // looking like class members in C++.
10420   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10421                                     D.getLocStart(),
10422                                     D.getIdentifierLoc(), II,
10423                                     parmDeclType, TInfo,
10424                                     SC);
10425 
10426   if (D.isInvalidType())
10427     New->setInvalidDecl();
10428 
10429   assert(S->isFunctionPrototypeScope());
10430   assert(S->getFunctionPrototypeDepth() >= 1);
10431   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10432                     S->getNextFunctionPrototypeIndex());
10433 
10434   // Add the parameter declaration into this scope.
10435   S->AddDecl(New);
10436   if (II)
10437     IdResolver.AddDecl(New);
10438 
10439   ProcessDeclAttributes(S, New, D);
10440 
10441   if (D.getDeclSpec().isModulePrivateSpecified())
10442     Diag(New->getLocation(), diag::err_module_private_local)
10443       << 1 << New->getDeclName()
10444       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10445       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10446 
10447   if (New->hasAttr<BlocksAttr>()) {
10448     Diag(New->getLocation(), diag::err_block_on_nonlocal);
10449   }
10450   return New;
10451 }
10452 
10453 /// \brief Synthesizes a variable for a parameter arising from a
10454 /// typedef.
10455 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10456                                               SourceLocation Loc,
10457                                               QualType T) {
10458   /* FIXME: setting StartLoc == Loc.
10459      Would it be worth to modify callers so as to provide proper source
10460      location for the unnamed parameters, embedding the parameter's type? */
10461   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10462                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
10463                                            SC_None, nullptr);
10464   Param->setImplicit();
10465   return Param;
10466 }
10467 
10468 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
10469                                     ParmVarDecl * const *ParamEnd) {
10470   // Don't diagnose unused-parameter errors in template instantiations; we
10471   // will already have done so in the template itself.
10472   if (!ActiveTemplateInstantiations.empty())
10473     return;
10474 
10475   for (; Param != ParamEnd; ++Param) {
10476     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10477         !(*Param)->hasAttr<UnusedAttr>()) {
10478       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10479         << (*Param)->getDeclName();
10480     }
10481   }
10482 }
10483 
10484 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
10485                                                   ParmVarDecl * const *ParamEnd,
10486                                                   QualType ReturnTy,
10487                                                   NamedDecl *D) {
10488   if (LangOpts.NumLargeByValueCopy == 0) // No check.
10489     return;
10490 
10491   // Warn if the return value is pass-by-value and larger than the specified
10492   // threshold.
10493   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10494     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10495     if (Size > LangOpts.NumLargeByValueCopy)
10496       Diag(D->getLocation(), diag::warn_return_value_size)
10497           << D->getDeclName() << Size;
10498   }
10499 
10500   // Warn if any parameter is pass-by-value and larger than the specified
10501   // threshold.
10502   for (; Param != ParamEnd; ++Param) {
10503     QualType T = (*Param)->getType();
10504     if (T->isDependentType() || !T.isPODType(Context))
10505       continue;
10506     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10507     if (Size > LangOpts.NumLargeByValueCopy)
10508       Diag((*Param)->getLocation(), diag::warn_parameter_size)
10509           << (*Param)->getDeclName() << Size;
10510   }
10511 }
10512 
10513 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10514                                   SourceLocation NameLoc, IdentifierInfo *Name,
10515                                   QualType T, TypeSourceInfo *TSInfo,
10516                                   StorageClass SC) {
10517   // In ARC, infer a lifetime qualifier for appropriate parameter types.
10518   if (getLangOpts().ObjCAutoRefCount &&
10519       T.getObjCLifetime() == Qualifiers::OCL_None &&
10520       T->isObjCLifetimeType()) {
10521 
10522     Qualifiers::ObjCLifetime lifetime;
10523 
10524     // Special cases for arrays:
10525     //   - if it's const, use __unsafe_unretained
10526     //   - otherwise, it's an error
10527     if (T->isArrayType()) {
10528       if (!T.isConstQualified()) {
10529         DelayedDiagnostics.add(
10530             sema::DelayedDiagnostic::makeForbiddenType(
10531             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10532       }
10533       lifetime = Qualifiers::OCL_ExplicitNone;
10534     } else {
10535       lifetime = T->getObjCARCImplicitLifetime();
10536     }
10537     T = Context.getLifetimeQualifiedType(T, lifetime);
10538   }
10539 
10540   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10541                                          Context.getAdjustedParameterType(T),
10542                                          TSInfo, SC, nullptr);
10543 
10544   // Parameters can not be abstract class types.
10545   // For record types, this is done by the AbstractClassUsageDiagnoser once
10546   // the class has been completely parsed.
10547   if (!CurContext->isRecord() &&
10548       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10549                              AbstractParamType))
10550     New->setInvalidDecl();
10551 
10552   // Parameter declarators cannot be interface types. All ObjC objects are
10553   // passed by reference.
10554   if (T->isObjCObjectType()) {
10555     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10556     Diag(NameLoc,
10557          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10558       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10559     T = Context.getObjCObjectPointerType(T);
10560     New->setType(T);
10561   }
10562 
10563   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10564   // duration shall not be qualified by an address-space qualifier."
10565   // Since all parameters have automatic store duration, they can not have
10566   // an address space.
10567   if (T.getAddressSpace() != 0) {
10568     // OpenCL allows function arguments declared to be an array of a type
10569     // to be qualified with an address space.
10570     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10571       Diag(NameLoc, diag::err_arg_with_address_space);
10572       New->setInvalidDecl();
10573     }
10574   }
10575 
10576   return New;
10577 }
10578 
10579 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10580                                            SourceLocation LocAfterDecls) {
10581   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10582 
10583   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10584   // for a K&R function.
10585   if (!FTI.hasPrototype) {
10586     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10587       --i;
10588       if (FTI.Params[i].Param == nullptr) {
10589         SmallString<256> Code;
10590         llvm::raw_svector_ostream(Code)
10591             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10592         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10593             << FTI.Params[i].Ident
10594             << FixItHint::CreateInsertion(LocAfterDecls, Code);
10595 
10596         // Implicitly declare the argument as type 'int' for lack of a better
10597         // type.
10598         AttributeFactory attrs;
10599         DeclSpec DS(attrs);
10600         const char* PrevSpec; // unused
10601         unsigned DiagID; // unused
10602         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10603                            DiagID, Context.getPrintingPolicy());
10604         // Use the identifier location for the type source range.
10605         DS.SetRangeStart(FTI.Params[i].IdentLoc);
10606         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10607         Declarator ParamD(DS, Declarator::KNRTypeListContext);
10608         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10609         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10610       }
10611     }
10612   }
10613 }
10614 
10615 Decl *
10616 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
10617                               MultiTemplateParamsArg TemplateParameterLists,
10618                               SkipBodyInfo *SkipBody) {
10619   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10620   assert(D.isFunctionDeclarator() && "Not a function declarator!");
10621   Scope *ParentScope = FnBodyScope->getParent();
10622 
10623   D.setFunctionDefinitionKind(FDK_Definition);
10624   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
10625   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
10626 }
10627 
10628 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10629   Consumer.HandleInlineMethodDefinition(D);
10630 }
10631 
10632 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10633                              const FunctionDecl*& PossibleZeroParamPrototype) {
10634   // Don't warn about invalid declarations.
10635   if (FD->isInvalidDecl())
10636     return false;
10637 
10638   // Or declarations that aren't global.
10639   if (!FD->isGlobal())
10640     return false;
10641 
10642   // Don't warn about C++ member functions.
10643   if (isa<CXXMethodDecl>(FD))
10644     return false;
10645 
10646   // Don't warn about 'main'.
10647   if (FD->isMain())
10648     return false;
10649 
10650   // Don't warn about inline functions.
10651   if (FD->isInlined())
10652     return false;
10653 
10654   // Don't warn about function templates.
10655   if (FD->getDescribedFunctionTemplate())
10656     return false;
10657 
10658   // Don't warn about function template specializations.
10659   if (FD->isFunctionTemplateSpecialization())
10660     return false;
10661 
10662   // Don't warn for OpenCL kernels.
10663   if (FD->hasAttr<OpenCLKernelAttr>())
10664     return false;
10665 
10666   // Don't warn on explicitly deleted functions.
10667   if (FD->isDeleted())
10668     return false;
10669 
10670   bool MissingPrototype = true;
10671   for (const FunctionDecl *Prev = FD->getPreviousDecl();
10672        Prev; Prev = Prev->getPreviousDecl()) {
10673     // Ignore any declarations that occur in function or method
10674     // scope, because they aren't visible from the header.
10675     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10676       continue;
10677 
10678     MissingPrototype = !Prev->getType()->isFunctionProtoType();
10679     if (FD->getNumParams() == 0)
10680       PossibleZeroParamPrototype = Prev;
10681     break;
10682   }
10683 
10684   return MissingPrototype;
10685 }
10686 
10687 void
10688 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10689                                    const FunctionDecl *EffectiveDefinition,
10690                                    SkipBodyInfo *SkipBody) {
10691   // Don't complain if we're in GNU89 mode and the previous definition
10692   // was an extern inline function.
10693   const FunctionDecl *Definition = EffectiveDefinition;
10694   if (!Definition)
10695     if (!FD->isDefined(Definition))
10696       return;
10697 
10698   if (canRedefineFunction(Definition, getLangOpts()))
10699     return;
10700 
10701   // If we don't have a visible definition of the function, and it's inline or
10702   // a template, skip the new definition.
10703   if (SkipBody && !hasVisibleDefinition(Definition) &&
10704       (Definition->getFormalLinkage() == InternalLinkage ||
10705        Definition->isInlined() ||
10706        Definition->getDescribedFunctionTemplate() ||
10707        Definition->getNumTemplateParameterLists())) {
10708     SkipBody->ShouldSkip = true;
10709     if (auto *TD = Definition->getDescribedFunctionTemplate())
10710       makeMergedDefinitionVisible(TD, FD->getLocation());
10711     else
10712       makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
10713                                   FD->getLocation());
10714     return;
10715   }
10716 
10717   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10718       Definition->getStorageClass() == SC_Extern)
10719     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10720         << FD->getDeclName() << getLangOpts().CPlusPlus;
10721   else
10722     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10723 
10724   Diag(Definition->getLocation(), diag::note_previous_definition);
10725   FD->setInvalidDecl();
10726 }
10727 
10728 
10729 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10730                                    Sema &S) {
10731   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10732 
10733   LambdaScopeInfo *LSI = S.PushLambdaScope();
10734   LSI->CallOperator = CallOperator;
10735   LSI->Lambda = LambdaClass;
10736   LSI->ReturnType = CallOperator->getReturnType();
10737   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10738 
10739   if (LCD == LCD_None)
10740     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10741   else if (LCD == LCD_ByCopy)
10742     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10743   else if (LCD == LCD_ByRef)
10744     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10745   DeclarationNameInfo DNI = CallOperator->getNameInfo();
10746 
10747   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
10748   LSI->Mutable = !CallOperator->isConst();
10749 
10750   // Add the captures to the LSI so they can be noted as already
10751   // captured within tryCaptureVar.
10752   auto I = LambdaClass->field_begin();
10753   for (const auto &C : LambdaClass->captures()) {
10754     if (C.capturesVariable()) {
10755       VarDecl *VD = C.getCapturedVar();
10756       if (VD->isInitCapture())
10757         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10758       QualType CaptureType = VD->getType();
10759       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10760       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
10761           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
10762           /*EllipsisLoc*/C.isPackExpansion()
10763                          ? C.getEllipsisLoc() : SourceLocation(),
10764           CaptureType, /*Expr*/ nullptr);
10765 
10766     } else if (C.capturesThis()) {
10767       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
10768                               S.getCurrentThisType(), /*Expr*/ nullptr);
10769     } else {
10770       LSI->addVLATypeCapture(C.getLocation(), I->getType());
10771     }
10772     ++I;
10773   }
10774 }
10775 
10776 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
10777                                     SkipBodyInfo *SkipBody) {
10778   // Clear the last template instantiation error context.
10779   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10780 
10781   if (!D)
10782     return D;
10783   FunctionDecl *FD = nullptr;
10784 
10785   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10786     FD = FunTmpl->getTemplatedDecl();
10787   else
10788     FD = cast<FunctionDecl>(D);
10789 
10790   // See if this is a redefinition.
10791   if (!FD->isLateTemplateParsed()) {
10792     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
10793 
10794     // If we're skipping the body, we're done. Don't enter the scope.
10795     if (SkipBody && SkipBody->ShouldSkip)
10796       return D;
10797   }
10798 
10799   // If we are instantiating a generic lambda call operator, push
10800   // a LambdaScopeInfo onto the function stack.  But use the information
10801   // that's already been calculated (ActOnLambdaExpr) to prime the current
10802   // LambdaScopeInfo.
10803   // When the template operator is being specialized, the LambdaScopeInfo,
10804   // has to be properly restored so that tryCaptureVariable doesn't try
10805   // and capture any new variables. In addition when calculating potential
10806   // captures during transformation of nested lambdas, it is necessary to
10807   // have the LSI properly restored.
10808   if (isGenericLambdaCallOperatorSpecialization(FD)) {
10809     assert(ActiveTemplateInstantiations.size() &&
10810       "There should be an active template instantiation on the stack "
10811       "when instantiating a generic lambda!");
10812     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
10813   }
10814   else
10815     // Enter a new function scope
10816     PushFunctionScope();
10817 
10818   // Builtin functions cannot be defined.
10819   if (unsigned BuiltinID = FD->getBuiltinID()) {
10820     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10821         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
10822       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
10823       FD->setInvalidDecl();
10824     }
10825   }
10826 
10827   // The return type of a function definition must be complete
10828   // (C99 6.9.1p3, C++ [dcl.fct]p6).
10829   QualType ResultType = FD->getReturnType();
10830   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
10831       !FD->isInvalidDecl() &&
10832       RequireCompleteType(FD->getLocation(), ResultType,
10833                           diag::err_func_def_incomplete_result))
10834     FD->setInvalidDecl();
10835 
10836   if (FnBodyScope)
10837     PushDeclContext(FnBodyScope, FD);
10838 
10839   // Check the validity of our function parameters
10840   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10841                            /*CheckParameterNames=*/true);
10842 
10843   // Introduce our parameters into the function scope
10844   for (auto Param : FD->params()) {
10845     Param->setOwningFunction(FD);
10846 
10847     // If this has an identifier, add it to the scope stack.
10848     if (Param->getIdentifier() && FnBodyScope) {
10849       CheckShadow(FnBodyScope, Param);
10850 
10851       PushOnScopeChains(Param, FnBodyScope);
10852     }
10853   }
10854 
10855   // If we had any tags defined in the function prototype,
10856   // introduce them into the function scope.
10857   if (FnBodyScope) {
10858     for (ArrayRef<NamedDecl *>::iterator
10859              I = FD->getDeclsInPrototypeScope().begin(),
10860              E = FD->getDeclsInPrototypeScope().end();
10861          I != E; ++I) {
10862       NamedDecl *D = *I;
10863 
10864       // Some of these decls (like enums) may have been pinned to the
10865       // translation unit for lack of a real context earlier. If so, remove
10866       // from the translation unit and reattach to the current context.
10867       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
10868         // Is the decl actually in the context?
10869         for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
10870           if (DI == D) {
10871             Context.getTranslationUnitDecl()->removeDecl(D);
10872             break;
10873           }
10874         }
10875         // Either way, reassign the lexical decl context to our FunctionDecl.
10876         D->setLexicalDeclContext(CurContext);
10877       }
10878 
10879       // If the decl has a non-null name, make accessible in the current scope.
10880       if (!D->getName().empty())
10881         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10882 
10883       // Similarly, dive into enums and fish their constants out, making them
10884       // accessible in this scope.
10885       if (auto *ED = dyn_cast<EnumDecl>(D)) {
10886         for (auto *EI : ED->enumerators())
10887           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
10888       }
10889     }
10890   }
10891 
10892   // Ensure that the function's exception specification is instantiated.
10893   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10894     ResolveExceptionSpec(D->getLocation(), FPT);
10895 
10896   // dllimport cannot be applied to non-inline function definitions.
10897   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10898       !FD->isTemplateInstantiation()) {
10899     assert(!FD->hasAttr<DLLExportAttr>());
10900     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10901     FD->setInvalidDecl();
10902     return D;
10903   }
10904   // We want to attach documentation to original Decl (which might be
10905   // a function template).
10906   ActOnDocumentableDecl(D);
10907   if (getCurLexicalContext()->isObjCContainer() &&
10908       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10909       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10910     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10911 
10912   return D;
10913 }
10914 
10915 /// \brief Given the set of return statements within a function body,
10916 /// compute the variables that are subject to the named return value
10917 /// optimization.
10918 ///
10919 /// Each of the variables that is subject to the named return value
10920 /// optimization will be marked as NRVO variables in the AST, and any
10921 /// return statement that has a marked NRVO variable as its NRVO candidate can
10922 /// use the named return value optimization.
10923 ///
10924 /// This function applies a very simplistic algorithm for NRVO: if every return
10925 /// statement in the scope of a variable has the same NRVO candidate, that
10926 /// candidate is an NRVO variable.
10927 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
10928   ReturnStmt **Returns = Scope->Returns.data();
10929 
10930   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
10931     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
10932       if (!NRVOCandidate->isNRVOVariable())
10933         Returns[I]->setNRVOCandidate(nullptr);
10934     }
10935   }
10936 }
10937 
10938 bool Sema::canDelayFunctionBody(const Declarator &D) {
10939   // We can't delay parsing the body of a constexpr function template (yet).
10940   if (D.getDeclSpec().isConstexprSpecified())
10941     return false;
10942 
10943   // We can't delay parsing the body of a function template with a deduced
10944   // return type (yet).
10945   if (D.getDeclSpec().containsPlaceholderType()) {
10946     // If the placeholder introduces a non-deduced trailing return type,
10947     // we can still delay parsing it.
10948     if (D.getNumTypeObjects()) {
10949       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
10950       if (Outer.Kind == DeclaratorChunk::Function &&
10951           Outer.Fun.hasTrailingReturnType()) {
10952         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
10953         return Ty.isNull() || !Ty->isUndeducedType();
10954       }
10955     }
10956     return false;
10957   }
10958 
10959   return true;
10960 }
10961 
10962 bool Sema::canSkipFunctionBody(Decl *D) {
10963   // We cannot skip the body of a function (or function template) which is
10964   // constexpr, since we may need to evaluate its body in order to parse the
10965   // rest of the file.
10966   // We cannot skip the body of a function with an undeduced return type,
10967   // because any callers of that function need to know the type.
10968   if (const FunctionDecl *FD = D->getAsFunction())
10969     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
10970       return false;
10971   return Consumer.shouldSkipFunctionBody(D);
10972 }
10973 
10974 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
10975   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
10976     FD->setHasSkippedBody();
10977   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
10978     MD->setHasSkippedBody();
10979   return ActOnFinishFunctionBody(Decl, nullptr);
10980 }
10981 
10982 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
10983   return ActOnFinishFunctionBody(D, BodyArg, false);
10984 }
10985 
10986 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
10987                                     bool IsInstantiation) {
10988   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
10989 
10990   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10991   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
10992 
10993   if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
10994     CheckCompletedCoroutineBody(FD, Body);
10995 
10996   if (FD) {
10997     FD->setBody(Body);
10998 
10999     if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
11000         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
11001       // If the function has a deduced result type but contains no 'return'
11002       // statements, the result type as written must be exactly 'auto', and
11003       // the deduced result type is 'void'.
11004       if (!FD->getReturnType()->getAs<AutoType>()) {
11005         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11006             << FD->getReturnType();
11007         FD->setInvalidDecl();
11008       } else {
11009         // Substitute 'void' for the 'auto' in the type.
11010         TypeLoc ResultType = getReturnTypeLoc(FD);
11011         Context.adjustDeducedFunctionResultType(
11012             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11013       }
11014     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11015       auto *LSI = getCurLambda();
11016       if (LSI->HasImplicitReturnType) {
11017         deduceClosureReturnType(*LSI);
11018 
11019         // C++11 [expr.prim.lambda]p4:
11020         //   [...] if there are no return statements in the compound-statement
11021         //   [the deduced type is] the type void
11022         QualType RetType =
11023             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11024 
11025         // Update the return type to the deduced type.
11026         const FunctionProtoType *Proto =
11027             FD->getType()->getAs<FunctionProtoType>();
11028         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11029                                             Proto->getExtProtoInfo()));
11030       }
11031     }
11032 
11033     // The only way to be included in UndefinedButUsed is if there is an
11034     // ODR use before the definition. Avoid the expensive map lookup if this
11035     // is the first declaration.
11036     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11037       if (!FD->isExternallyVisible())
11038         UndefinedButUsed.erase(FD);
11039       else if (FD->isInlined() &&
11040                !LangOpts.GNUInline &&
11041                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11042         UndefinedButUsed.erase(FD);
11043     }
11044 
11045     // If the function implicitly returns zero (like 'main') or is naked,
11046     // don't complain about missing return statements.
11047     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11048       WP.disableCheckFallThrough();
11049 
11050     // MSVC permits the use of pure specifier (=0) on function definition,
11051     // defined at class scope, warn about this non-standard construct.
11052     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11053       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11054 
11055     if (!FD->isInvalidDecl()) {
11056       // Don't diagnose unused parameters of defaulted or deleted functions.
11057       if (!FD->isDeleted() && !FD->isDefaulted())
11058         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
11059       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
11060                                              FD->getReturnType(), FD);
11061 
11062       // If this is a structor, we need a vtable.
11063       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11064         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11065       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11066         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11067 
11068       // Try to apply the named return value optimization. We have to check
11069       // if we can do this here because lambdas keep return statements around
11070       // to deduce an implicit return type.
11071       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11072           !FD->isDependentContext())
11073         computeNRVO(Body, getCurFunction());
11074     }
11075 
11076     // GNU warning -Wmissing-prototypes:
11077     //   Warn if a global function is defined without a previous
11078     //   prototype declaration. This warning is issued even if the
11079     //   definition itself provides a prototype. The aim is to detect
11080     //   global functions that fail to be declared in header files.
11081     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11082     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11083       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11084 
11085       if (PossibleZeroParamPrototype) {
11086         // We found a declaration that is not a prototype,
11087         // but that could be a zero-parameter prototype
11088         if (TypeSourceInfo *TI =
11089                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11090           TypeLoc TL = TI->getTypeLoc();
11091           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11092             Diag(PossibleZeroParamPrototype->getLocation(),
11093                  diag::note_declaration_not_a_prototype)
11094                 << PossibleZeroParamPrototype
11095                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11096         }
11097       }
11098     }
11099 
11100     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11101       const CXXMethodDecl *KeyFunction;
11102       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11103           MD->isVirtual() &&
11104           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11105           MD == KeyFunction->getCanonicalDecl()) {
11106         // Update the key-function state if necessary for this ABI.
11107         if (FD->isInlined() &&
11108             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11109           Context.setNonKeyFunction(MD);
11110 
11111           // If the newly-chosen key function is already defined, then we
11112           // need to mark the vtable as used retroactively.
11113           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11114           const FunctionDecl *Definition;
11115           if (KeyFunction && KeyFunction->isDefined(Definition))
11116             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11117         } else {
11118           // We just defined they key function; mark the vtable as used.
11119           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11120         }
11121       }
11122     }
11123 
11124     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11125            "Function parsing confused");
11126   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11127     assert(MD == getCurMethodDecl() && "Method parsing confused");
11128     MD->setBody(Body);
11129     if (!MD->isInvalidDecl()) {
11130       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
11131       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
11132                                              MD->getReturnType(), MD);
11133 
11134       if (Body)
11135         computeNRVO(Body, getCurFunction());
11136     }
11137     if (getCurFunction()->ObjCShouldCallSuper) {
11138       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11139         << MD->getSelector().getAsString();
11140       getCurFunction()->ObjCShouldCallSuper = false;
11141     }
11142     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11143       const ObjCMethodDecl *InitMethod = nullptr;
11144       bool isDesignated =
11145           MD->isDesignatedInitializerForTheInterface(&InitMethod);
11146       assert(isDesignated && InitMethod);
11147       (void)isDesignated;
11148 
11149       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11150         auto IFace = MD->getClassInterface();
11151         if (!IFace)
11152           return false;
11153         auto SuperD = IFace->getSuperClass();
11154         if (!SuperD)
11155           return false;
11156         return SuperD->getIdentifier() ==
11157             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11158       };
11159       // Don't issue this warning for unavailable inits or direct subclasses
11160       // of NSObject.
11161       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11162         Diag(MD->getLocation(),
11163              diag::warn_objc_designated_init_missing_super_call);
11164         Diag(InitMethod->getLocation(),
11165              diag::note_objc_designated_init_marked_here);
11166       }
11167       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11168     }
11169     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11170       // Don't issue this warning for unavaialable inits.
11171       if (!MD->isUnavailable())
11172         Diag(MD->getLocation(),
11173              diag::warn_objc_secondary_init_missing_init_call);
11174       getCurFunction()->ObjCWarnForNoInitDelegation = false;
11175     }
11176   } else {
11177     return nullptr;
11178   }
11179 
11180   assert(!getCurFunction()->ObjCShouldCallSuper &&
11181          "This should only be set for ObjC methods, which should have been "
11182          "handled in the block above.");
11183 
11184   // Verify and clean out per-function state.
11185   if (Body && (!FD || !FD->isDefaulted())) {
11186     // C++ constructors that have function-try-blocks can't have return
11187     // statements in the handlers of that block. (C++ [except.handle]p14)
11188     // Verify this.
11189     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11190       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11191 
11192     // Verify that gotos and switch cases don't jump into scopes illegally.
11193     if (getCurFunction()->NeedsScopeChecking() &&
11194         !PP.isCodeCompletionEnabled())
11195       DiagnoseInvalidJumps(Body);
11196 
11197     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11198       if (!Destructor->getParent()->isDependentType())
11199         CheckDestructor(Destructor);
11200 
11201       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11202                                              Destructor->getParent());
11203     }
11204 
11205     // If any errors have occurred, clear out any temporaries that may have
11206     // been leftover. This ensures that these temporaries won't be picked up for
11207     // deletion in some later function.
11208     if (getDiagnostics().hasErrorOccurred() ||
11209         getDiagnostics().getSuppressAllDiagnostics()) {
11210       DiscardCleanupsInEvaluationContext();
11211     }
11212     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11213         !isa<FunctionTemplateDecl>(dcl)) {
11214       // Since the body is valid, issue any analysis-based warnings that are
11215       // enabled.
11216       ActivePolicy = &WP;
11217     }
11218 
11219     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11220         (!CheckConstexprFunctionDecl(FD) ||
11221          !CheckConstexprFunctionBody(FD, Body)))
11222       FD->setInvalidDecl();
11223 
11224     if (FD && FD->hasAttr<NakedAttr>()) {
11225       for (const Stmt *S : Body->children()) {
11226         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11227           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11228           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11229           FD->setInvalidDecl();
11230           break;
11231         }
11232       }
11233     }
11234 
11235     assert(ExprCleanupObjects.size() ==
11236                ExprEvalContexts.back().NumCleanupObjects &&
11237            "Leftover temporaries in function");
11238     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
11239     assert(MaybeODRUseExprs.empty() &&
11240            "Leftover expressions for odr-use checking");
11241   }
11242 
11243   if (!IsInstantiation)
11244     PopDeclContext();
11245 
11246   PopFunctionScopeInfo(ActivePolicy, dcl);
11247   // If any errors have occurred, clear out any temporaries that may have
11248   // been leftover. This ensures that these temporaries won't be picked up for
11249   // deletion in some later function.
11250   if (getDiagnostics().hasErrorOccurred()) {
11251     DiscardCleanupsInEvaluationContext();
11252   }
11253 
11254   return dcl;
11255 }
11256 
11257 
11258 /// When we finish delayed parsing of an attribute, we must attach it to the
11259 /// relevant Decl.
11260 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11261                                        ParsedAttributes &Attrs) {
11262   // Always attach attributes to the underlying decl.
11263   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11264     D = TD->getTemplatedDecl();
11265   ProcessDeclAttributeList(S, D, Attrs.getList());
11266 
11267   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11268     if (Method->isStatic())
11269       checkThisInStaticMemberFunctionAttributes(Method);
11270 }
11271 
11272 
11273 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11274 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11275 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11276                                           IdentifierInfo &II, Scope *S) {
11277   // Before we produce a declaration for an implicitly defined
11278   // function, see whether there was a locally-scoped declaration of
11279   // this name as a function or variable. If so, use that
11280   // (non-visible) declaration, and complain about it.
11281   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11282     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11283     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11284     return ExternCPrev;
11285   }
11286 
11287   // Extension in C99.  Legal in C90, but warn about it.
11288   unsigned diag_id;
11289   if (II.getName().startswith("__builtin_"))
11290     diag_id = diag::warn_builtin_unknown;
11291   else if (getLangOpts().C99)
11292     diag_id = diag::ext_implicit_function_decl;
11293   else
11294     diag_id = diag::warn_implicit_function_decl;
11295   Diag(Loc, diag_id) << &II;
11296 
11297   // Because typo correction is expensive, only do it if the implicit
11298   // function declaration is going to be treated as an error.
11299   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11300     TypoCorrection Corrected;
11301     if (S &&
11302         (Corrected = CorrectTypo(
11303              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11304              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11305       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11306                    /*ErrorRecovery*/false);
11307   }
11308 
11309   // Set a Declarator for the implicit definition: int foo();
11310   const char *Dummy;
11311   AttributeFactory attrFactory;
11312   DeclSpec DS(attrFactory);
11313   unsigned DiagID;
11314   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11315                                   Context.getPrintingPolicy());
11316   (void)Error; // Silence warning.
11317   assert(!Error && "Error setting up implicit decl!");
11318   SourceLocation NoLoc;
11319   Declarator D(DS, Declarator::BlockContext);
11320   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11321                                              /*IsAmbiguous=*/false,
11322                                              /*LParenLoc=*/NoLoc,
11323                                              /*Params=*/nullptr,
11324                                              /*NumParams=*/0,
11325                                              /*EllipsisLoc=*/NoLoc,
11326                                              /*RParenLoc=*/NoLoc,
11327                                              /*TypeQuals=*/0,
11328                                              /*RefQualifierIsLvalueRef=*/true,
11329                                              /*RefQualifierLoc=*/NoLoc,
11330                                              /*ConstQualifierLoc=*/NoLoc,
11331                                              /*VolatileQualifierLoc=*/NoLoc,
11332                                              /*RestrictQualifierLoc=*/NoLoc,
11333                                              /*MutableLoc=*/NoLoc,
11334                                              EST_None,
11335                                              /*ESpecRange=*/SourceRange(),
11336                                              /*Exceptions=*/nullptr,
11337                                              /*ExceptionRanges=*/nullptr,
11338                                              /*NumExceptions=*/0,
11339                                              /*NoexceptExpr=*/nullptr,
11340                                              /*ExceptionSpecTokens=*/nullptr,
11341                                              Loc, Loc, D),
11342                 DS.getAttributes(),
11343                 SourceLocation());
11344   D.SetIdentifier(&II, Loc);
11345 
11346   // Insert this function into translation-unit scope.
11347 
11348   DeclContext *PrevDC = CurContext;
11349   CurContext = Context.getTranslationUnitDecl();
11350 
11351   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11352   FD->setImplicit();
11353 
11354   CurContext = PrevDC;
11355 
11356   AddKnownFunctionAttributes(FD);
11357 
11358   return FD;
11359 }
11360 
11361 /// \brief Adds any function attributes that we know a priori based on
11362 /// the declaration of this function.
11363 ///
11364 /// These attributes can apply both to implicitly-declared builtins
11365 /// (like __builtin___printf_chk) or to library-declared functions
11366 /// like NSLog or printf.
11367 ///
11368 /// We need to check for duplicate attributes both here and where user-written
11369 /// attributes are applied to declarations.
11370 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11371   if (FD->isInvalidDecl())
11372     return;
11373 
11374   // If this is a built-in function, map its builtin attributes to
11375   // actual attributes.
11376   if (unsigned BuiltinID = FD->getBuiltinID()) {
11377     // Handle printf-formatting attributes.
11378     unsigned FormatIdx;
11379     bool HasVAListArg;
11380     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11381       if (!FD->hasAttr<FormatAttr>()) {
11382         const char *fmt = "printf";
11383         unsigned int NumParams = FD->getNumParams();
11384         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11385             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11386           fmt = "NSString";
11387         FD->addAttr(FormatAttr::CreateImplicit(Context,
11388                                                &Context.Idents.get(fmt),
11389                                                FormatIdx+1,
11390                                                HasVAListArg ? 0 : FormatIdx+2,
11391                                                FD->getLocation()));
11392       }
11393     }
11394     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11395                                              HasVAListArg)) {
11396      if (!FD->hasAttr<FormatAttr>())
11397        FD->addAttr(FormatAttr::CreateImplicit(Context,
11398                                               &Context.Idents.get("scanf"),
11399                                               FormatIdx+1,
11400                                               HasVAListArg ? 0 : FormatIdx+2,
11401                                               FD->getLocation()));
11402     }
11403 
11404     // Mark const if we don't care about errno and that is the only
11405     // thing preventing the function from being const. This allows
11406     // IRgen to use LLVM intrinsics for such functions.
11407     if (!getLangOpts().MathErrno &&
11408         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11409       if (!FD->hasAttr<ConstAttr>())
11410         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11411     }
11412 
11413     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11414         !FD->hasAttr<ReturnsTwiceAttr>())
11415       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11416                                          FD->getLocation()));
11417     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11418       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11419     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11420       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11421     if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads &&
11422         Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11423         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11424       // Assign appropriate attribute depending on CUDA compilation
11425       // mode and the target builtin belongs to. E.g. during host
11426       // compilation, aux builtins are __device__, the rest are __host__.
11427       if (getLangOpts().CUDAIsDevice !=
11428           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11429         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11430       else
11431         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11432     }
11433   }
11434 
11435   IdentifierInfo *Name = FD->getIdentifier();
11436   if (!Name)
11437     return;
11438   if ((!getLangOpts().CPlusPlus &&
11439        FD->getDeclContext()->isTranslationUnit()) ||
11440       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11441        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11442        LinkageSpecDecl::lang_c)) {
11443     // Okay: this could be a libc/libm/Objective-C function we know
11444     // about.
11445   } else
11446     return;
11447 
11448   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11449     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11450     // target-specific builtins, perhaps?
11451     if (!FD->hasAttr<FormatAttr>())
11452       FD->addAttr(FormatAttr::CreateImplicit(Context,
11453                                              &Context.Idents.get("printf"), 2,
11454                                              Name->isStr("vasprintf") ? 0 : 3,
11455                                              FD->getLocation()));
11456   }
11457 
11458   if (Name->isStr("__CFStringMakeConstantString")) {
11459     // We already have a __builtin___CFStringMakeConstantString,
11460     // but builds that use -fno-constant-cfstrings don't go through that.
11461     if (!FD->hasAttr<FormatArgAttr>())
11462       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11463                                                 FD->getLocation()));
11464   }
11465 }
11466 
11467 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11468                                     TypeSourceInfo *TInfo) {
11469   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11470   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11471 
11472   if (!TInfo) {
11473     assert(D.isInvalidType() && "no declarator info for valid type");
11474     TInfo = Context.getTrivialTypeSourceInfo(T);
11475   }
11476 
11477   // Scope manipulation handled by caller.
11478   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11479                                            D.getLocStart(),
11480                                            D.getIdentifierLoc(),
11481                                            D.getIdentifier(),
11482                                            TInfo);
11483 
11484   // Bail out immediately if we have an invalid declaration.
11485   if (D.isInvalidType()) {
11486     NewTD->setInvalidDecl();
11487     return NewTD;
11488   }
11489 
11490   if (D.getDeclSpec().isModulePrivateSpecified()) {
11491     if (CurContext->isFunctionOrMethod())
11492       Diag(NewTD->getLocation(), diag::err_module_private_local)
11493         << 2 << NewTD->getDeclName()
11494         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11495         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11496     else
11497       NewTD->setModulePrivate();
11498   }
11499 
11500   // C++ [dcl.typedef]p8:
11501   //   If the typedef declaration defines an unnamed class (or
11502   //   enum), the first typedef-name declared by the declaration
11503   //   to be that class type (or enum type) is used to denote the
11504   //   class type (or enum type) for linkage purposes only.
11505   // We need to check whether the type was declared in the declaration.
11506   switch (D.getDeclSpec().getTypeSpecType()) {
11507   case TST_enum:
11508   case TST_struct:
11509   case TST_interface:
11510   case TST_union:
11511   case TST_class: {
11512     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11513     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11514     break;
11515   }
11516 
11517   default:
11518     break;
11519   }
11520 
11521   return NewTD;
11522 }
11523 
11524 
11525 /// \brief Check that this is a valid underlying type for an enum declaration.
11526 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11527   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11528   QualType T = TI->getType();
11529 
11530   if (T->isDependentType())
11531     return false;
11532 
11533   if (const BuiltinType *BT = T->getAs<BuiltinType>())
11534     if (BT->isInteger())
11535       return false;
11536 
11537   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11538   return true;
11539 }
11540 
11541 /// Check whether this is a valid redeclaration of a previous enumeration.
11542 /// \return true if the redeclaration was invalid.
11543 bool Sema::CheckEnumRedeclaration(
11544     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
11545     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
11546   bool IsFixed = !EnumUnderlyingTy.isNull();
11547 
11548   if (IsScoped != Prev->isScoped()) {
11549     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11550       << Prev->isScoped();
11551     Diag(Prev->getLocation(), diag::note_previous_declaration);
11552     return true;
11553   }
11554 
11555   if (IsFixed && Prev->isFixed()) {
11556     if (!EnumUnderlyingTy->isDependentType() &&
11557         !Prev->getIntegerType()->isDependentType() &&
11558         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11559                                         Prev->getIntegerType())) {
11560       // TODO: Highlight the underlying type of the redeclaration.
11561       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11562         << EnumUnderlyingTy << Prev->getIntegerType();
11563       Diag(Prev->getLocation(), diag::note_previous_declaration)
11564           << Prev->getIntegerTypeRange();
11565       return true;
11566     }
11567   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
11568     ;
11569   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
11570     ;
11571   } else if (IsFixed != Prev->isFixed()) {
11572     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11573       << Prev->isFixed();
11574     Diag(Prev->getLocation(), diag::note_previous_declaration);
11575     return true;
11576   }
11577 
11578   return false;
11579 }
11580 
11581 /// \brief Get diagnostic %select index for tag kind for
11582 /// redeclaration diagnostic message.
11583 /// WARNING: Indexes apply to particular diagnostics only!
11584 ///
11585 /// \returns diagnostic %select index.
11586 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
11587   switch (Tag) {
11588   case TTK_Struct: return 0;
11589   case TTK_Interface: return 1;
11590   case TTK_Class:  return 2;
11591   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11592   }
11593 }
11594 
11595 /// \brief Determine if tag kind is a class-key compatible with
11596 /// class for redeclaration (class, struct, or __interface).
11597 ///
11598 /// \returns true iff the tag kind is compatible.
11599 static bool isClassCompatTagKind(TagTypeKind Tag)
11600 {
11601   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11602 }
11603 
11604 /// \brief Determine whether a tag with a given kind is acceptable
11605 /// as a redeclaration of the given tag declaration.
11606 ///
11607 /// \returns true if the new tag kind is acceptable, false otherwise.
11608 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11609                                         TagTypeKind NewTag, bool isDefinition,
11610                                         SourceLocation NewTagLoc,
11611                                         const IdentifierInfo *Name) {
11612   // C++ [dcl.type.elab]p3:
11613   //   The class-key or enum keyword present in the
11614   //   elaborated-type-specifier shall agree in kind with the
11615   //   declaration to which the name in the elaborated-type-specifier
11616   //   refers. This rule also applies to the form of
11617   //   elaborated-type-specifier that declares a class-name or
11618   //   friend class since it can be construed as referring to the
11619   //   definition of the class. Thus, in any
11620   //   elaborated-type-specifier, the enum keyword shall be used to
11621   //   refer to an enumeration (7.2), the union class-key shall be
11622   //   used to refer to a union (clause 9), and either the class or
11623   //   struct class-key shall be used to refer to a class (clause 9)
11624   //   declared using the class or struct class-key.
11625   TagTypeKind OldTag = Previous->getTagKind();
11626   if (!isDefinition || !isClassCompatTagKind(NewTag))
11627     if (OldTag == NewTag)
11628       return true;
11629 
11630   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11631     // Warn about the struct/class tag mismatch.
11632     bool isTemplate = false;
11633     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11634       isTemplate = Record->getDescribedClassTemplate();
11635 
11636     if (!ActiveTemplateInstantiations.empty()) {
11637       // In a template instantiation, do not offer fix-its for tag mismatches
11638       // since they usually mess up the template instead of fixing the problem.
11639       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11640         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11641         << getRedeclDiagFromTagKind(OldTag);
11642       return true;
11643     }
11644 
11645     if (isDefinition) {
11646       // On definitions, check previous tags and issue a fix-it for each
11647       // one that doesn't match the current tag.
11648       if (Previous->getDefinition()) {
11649         // Don't suggest fix-its for redefinitions.
11650         return true;
11651       }
11652 
11653       bool previousMismatch = false;
11654       for (auto I : Previous->redecls()) {
11655         if (I->getTagKind() != NewTag) {
11656           if (!previousMismatch) {
11657             previousMismatch = true;
11658             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11659               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11660               << getRedeclDiagFromTagKind(I->getTagKind());
11661           }
11662           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11663             << getRedeclDiagFromTagKind(NewTag)
11664             << FixItHint::CreateReplacement(I->getInnerLocStart(),
11665                  TypeWithKeyword::getTagTypeKindName(NewTag));
11666         }
11667       }
11668       return true;
11669     }
11670 
11671     // Check for a previous definition.  If current tag and definition
11672     // are same type, do nothing.  If no definition, but disagree with
11673     // with previous tag type, give a warning, but no fix-it.
11674     const TagDecl *Redecl = Previous->getDefinition() ?
11675                             Previous->getDefinition() : Previous;
11676     if (Redecl->getTagKind() == NewTag) {
11677       return true;
11678     }
11679 
11680     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11681       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11682       << getRedeclDiagFromTagKind(OldTag);
11683     Diag(Redecl->getLocation(), diag::note_previous_use);
11684 
11685     // If there is a previous definition, suggest a fix-it.
11686     if (Previous->getDefinition()) {
11687         Diag(NewTagLoc, diag::note_struct_class_suggestion)
11688           << getRedeclDiagFromTagKind(Redecl->getTagKind())
11689           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11690                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11691     }
11692 
11693     return true;
11694   }
11695   return false;
11696 }
11697 
11698 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11699 /// from an outer enclosing namespace or file scope inside a friend declaration.
11700 /// This should provide the commented out code in the following snippet:
11701 ///   namespace N {
11702 ///     struct X;
11703 ///     namespace M {
11704 ///       struct Y { friend struct /*N::*/ X; };
11705 ///     }
11706 ///   }
11707 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11708                                          SourceLocation NameLoc) {
11709   // While the decl is in a namespace, do repeated lookup of that name and see
11710   // if we get the same namespace back.  If we do not, continue until
11711   // translation unit scope, at which point we have a fully qualified NNS.
11712   SmallVector<IdentifierInfo *, 4> Namespaces;
11713   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11714   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11715     // This tag should be declared in a namespace, which can only be enclosed by
11716     // other namespaces.  Bail if there's an anonymous namespace in the chain.
11717     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11718     if (!Namespace || Namespace->isAnonymousNamespace())
11719       return FixItHint();
11720     IdentifierInfo *II = Namespace->getIdentifier();
11721     Namespaces.push_back(II);
11722     NamedDecl *Lookup = SemaRef.LookupSingleName(
11723         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11724     if (Lookup == Namespace)
11725       break;
11726   }
11727 
11728   // Once we have all the namespaces, reverse them to go outermost first, and
11729   // build an NNS.
11730   SmallString<64> Insertion;
11731   llvm::raw_svector_ostream OS(Insertion);
11732   if (DC->isTranslationUnit())
11733     OS << "::";
11734   std::reverse(Namespaces.begin(), Namespaces.end());
11735   for (auto *II : Namespaces)
11736     OS << II->getName() << "::";
11737   return FixItHint::CreateInsertion(NameLoc, Insertion);
11738 }
11739 
11740 /// \brief Determine whether a tag originally declared in context \p OldDC can
11741 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
11742 /// found a declaration in \p OldDC as a previous decl, perhaps through a
11743 /// using-declaration).
11744 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
11745                                          DeclContext *NewDC) {
11746   OldDC = OldDC->getRedeclContext();
11747   NewDC = NewDC->getRedeclContext();
11748 
11749   if (OldDC->Equals(NewDC))
11750     return true;
11751 
11752   // In MSVC mode, we allow a redeclaration if the contexts are related (either
11753   // encloses the other).
11754   if (S.getLangOpts().MSVCCompat &&
11755       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
11756     return true;
11757 
11758   return false;
11759 }
11760 
11761 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
11762 /// former case, Name will be non-null.  In the later case, Name will be null.
11763 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
11764 /// reference/declaration/definition of a tag.
11765 ///
11766 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
11767 /// trailing-type-specifier) other than one in an alias-declaration.
11768 ///
11769 /// \param SkipBody If non-null, will be set to indicate if the caller should
11770 /// skip the definition of this tag and treat it as if it were a declaration.
11771 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11772                      SourceLocation KWLoc, CXXScopeSpec &SS,
11773                      IdentifierInfo *Name, SourceLocation NameLoc,
11774                      AttributeList *Attr, AccessSpecifier AS,
11775                      SourceLocation ModulePrivateLoc,
11776                      MultiTemplateParamsArg TemplateParameterLists,
11777                      bool &OwnedDecl, bool &IsDependent,
11778                      SourceLocation ScopedEnumKWLoc,
11779                      bool ScopedEnumUsesClassTag,
11780                      TypeResult UnderlyingType,
11781                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
11782   // If this is not a definition, it must have a name.
11783   IdentifierInfo *OrigName = Name;
11784   assert((Name != nullptr || TUK == TUK_Definition) &&
11785          "Nameless record must be a definition!");
11786   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
11787 
11788   OwnedDecl = false;
11789   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11790   bool ScopedEnum = ScopedEnumKWLoc.isValid();
11791 
11792   // FIXME: Check explicit specializations more carefully.
11793   bool isExplicitSpecialization = false;
11794   bool Invalid = false;
11795 
11796   // We only need to do this matching if we have template parameters
11797   // or a scope specifier, which also conveniently avoids this work
11798   // for non-C++ cases.
11799   if (TemplateParameterLists.size() > 0 ||
11800       (SS.isNotEmpty() && TUK != TUK_Reference)) {
11801     if (TemplateParameterList *TemplateParams =
11802             MatchTemplateParametersToScopeSpecifier(
11803                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
11804                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
11805       if (Kind == TTK_Enum) {
11806         Diag(KWLoc, diag::err_enum_template);
11807         return nullptr;
11808       }
11809 
11810       if (TemplateParams->size() > 0) {
11811         // This is a declaration or definition of a class template (which may
11812         // be a member of another template).
11813 
11814         if (Invalid)
11815           return nullptr;
11816 
11817         OwnedDecl = false;
11818         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
11819                                                SS, Name, NameLoc, Attr,
11820                                                TemplateParams, AS,
11821                                                ModulePrivateLoc,
11822                                                /*FriendLoc*/SourceLocation(),
11823                                                TemplateParameterLists.size()-1,
11824                                                TemplateParameterLists.data(),
11825                                                SkipBody);
11826         return Result.get();
11827       } else {
11828         // The "template<>" header is extraneous.
11829         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11830           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11831         isExplicitSpecialization = true;
11832       }
11833     }
11834   }
11835 
11836   // Figure out the underlying type if this a enum declaration. We need to do
11837   // this early, because it's needed to detect if this is an incompatible
11838   // redeclaration.
11839   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11840   bool EnumUnderlyingIsImplicit = false;
11841 
11842   if (Kind == TTK_Enum) {
11843     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11844       // No underlying type explicitly specified, or we failed to parse the
11845       // type, default to int.
11846       EnumUnderlying = Context.IntTy.getTypePtr();
11847     else if (UnderlyingType.get()) {
11848       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11849       // integral type; any cv-qualification is ignored.
11850       TypeSourceInfo *TI = nullptr;
11851       GetTypeFromParser(UnderlyingType.get(), &TI);
11852       EnumUnderlying = TI;
11853 
11854       if (CheckEnumUnderlyingType(TI))
11855         // Recover by falling back to int.
11856         EnumUnderlying = Context.IntTy.getTypePtr();
11857 
11858       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
11859                                           UPPC_FixedUnderlyingType))
11860         EnumUnderlying = Context.IntTy.getTypePtr();
11861 
11862     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
11863       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
11864         // Microsoft enums are always of int type.
11865         EnumUnderlying = Context.IntTy.getTypePtr();
11866         EnumUnderlyingIsImplicit = true;
11867       }
11868     }
11869   }
11870 
11871   DeclContext *SearchDC = CurContext;
11872   DeclContext *DC = CurContext;
11873   bool isStdBadAlloc = false;
11874 
11875   RedeclarationKind Redecl = ForRedeclaration;
11876   if (TUK == TUK_Friend || TUK == TUK_Reference)
11877     Redecl = NotForRedeclaration;
11878 
11879   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
11880   if (Name && SS.isNotEmpty()) {
11881     // We have a nested-name tag ('struct foo::bar').
11882 
11883     // Check for invalid 'foo::'.
11884     if (SS.isInvalid()) {
11885       Name = nullptr;
11886       goto CreateNewDecl;
11887     }
11888 
11889     // If this is a friend or a reference to a class in a dependent
11890     // context, don't try to make a decl for it.
11891     if (TUK == TUK_Friend || TUK == TUK_Reference) {
11892       DC = computeDeclContext(SS, false);
11893       if (!DC) {
11894         IsDependent = true;
11895         return nullptr;
11896       }
11897     } else {
11898       DC = computeDeclContext(SS, true);
11899       if (!DC) {
11900         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11901           << SS.getRange();
11902         return nullptr;
11903       }
11904     }
11905 
11906     if (RequireCompleteDeclContext(SS, DC))
11907       return nullptr;
11908 
11909     SearchDC = DC;
11910     // Look-up name inside 'foo::'.
11911     LookupQualifiedName(Previous, DC);
11912 
11913     if (Previous.isAmbiguous())
11914       return nullptr;
11915 
11916     if (Previous.empty()) {
11917       // Name lookup did not find anything. However, if the
11918       // nested-name-specifier refers to the current instantiation,
11919       // and that current instantiation has any dependent base
11920       // classes, we might find something at instantiation time: treat
11921       // this as a dependent elaborated-type-specifier.
11922       // But this only makes any sense for reference-like lookups.
11923       if (Previous.wasNotFoundInCurrentInstantiation() &&
11924           (TUK == TUK_Reference || TUK == TUK_Friend)) {
11925         IsDependent = true;
11926         return nullptr;
11927       }
11928 
11929       // A tag 'foo::bar' must already exist.
11930       Diag(NameLoc, diag::err_not_tag_in_scope)
11931         << Kind << Name << DC << SS.getRange();
11932       Name = nullptr;
11933       Invalid = true;
11934       goto CreateNewDecl;
11935     }
11936   } else if (Name) {
11937     // C++14 [class.mem]p14:
11938     //   If T is the name of a class, then each of the following shall have a
11939     //   name different from T:
11940     //    -- every member of class T that is itself a type
11941     if (TUK != TUK_Reference && TUK != TUK_Friend &&
11942         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
11943       return nullptr;
11944 
11945     // If this is a named struct, check to see if there was a previous forward
11946     // declaration or definition.
11947     // FIXME: We're looking into outer scopes here, even when we
11948     // shouldn't be. Doing so can result in ambiguities that we
11949     // shouldn't be diagnosing.
11950     LookupName(Previous, S);
11951 
11952     // When declaring or defining a tag, ignore ambiguities introduced
11953     // by types using'ed into this scope.
11954     if (Previous.isAmbiguous() &&
11955         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
11956       LookupResult::Filter F = Previous.makeFilter();
11957       while (F.hasNext()) {
11958         NamedDecl *ND = F.next();
11959         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
11960           F.erase();
11961       }
11962       F.done();
11963     }
11964 
11965     // C++11 [namespace.memdef]p3:
11966     //   If the name in a friend declaration is neither qualified nor
11967     //   a template-id and the declaration is a function or an
11968     //   elaborated-type-specifier, the lookup to determine whether
11969     //   the entity has been previously declared shall not consider
11970     //   any scopes outside the innermost enclosing namespace.
11971     //
11972     // MSVC doesn't implement the above rule for types, so a friend tag
11973     // declaration may be a redeclaration of a type declared in an enclosing
11974     // scope.  They do implement this rule for friend functions.
11975     //
11976     // Does it matter that this should be by scope instead of by
11977     // semantic context?
11978     if (!Previous.empty() && TUK == TUK_Friend) {
11979       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
11980       LookupResult::Filter F = Previous.makeFilter();
11981       bool FriendSawTagOutsideEnclosingNamespace = false;
11982       while (F.hasNext()) {
11983         NamedDecl *ND = F.next();
11984         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11985         if (DC->isFileContext() &&
11986             !EnclosingNS->Encloses(ND->getDeclContext())) {
11987           if (getLangOpts().MSVCCompat)
11988             FriendSawTagOutsideEnclosingNamespace = true;
11989           else
11990             F.erase();
11991         }
11992       }
11993       F.done();
11994 
11995       // Diagnose this MSVC extension in the easy case where lookup would have
11996       // unambiguously found something outside the enclosing namespace.
11997       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
11998         NamedDecl *ND = Previous.getFoundDecl();
11999         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12000             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12001       }
12002     }
12003 
12004     // Note:  there used to be some attempt at recovery here.
12005     if (Previous.isAmbiguous())
12006       return nullptr;
12007 
12008     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12009       // FIXME: This makes sure that we ignore the contexts associated
12010       // with C structs, unions, and enums when looking for a matching
12011       // tag declaration or definition. See the similar lookup tweak
12012       // in Sema::LookupName; is there a better way to deal with this?
12013       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12014         SearchDC = SearchDC->getParent();
12015     }
12016   }
12017 
12018   if (Previous.isSingleResult() &&
12019       Previous.getFoundDecl()->isTemplateParameter()) {
12020     // Maybe we will complain about the shadowed template parameter.
12021     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12022     // Just pretend that we didn't see the previous declaration.
12023     Previous.clear();
12024   }
12025 
12026   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12027       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12028     // This is a declaration of or a reference to "std::bad_alloc".
12029     isStdBadAlloc = true;
12030 
12031     if (Previous.empty() && StdBadAlloc) {
12032       // std::bad_alloc has been implicitly declared (but made invisible to
12033       // name lookup). Fill in this implicit declaration as the previous
12034       // declaration, so that the declarations get chained appropriately.
12035       Previous.addDecl(getStdBadAlloc());
12036     }
12037   }
12038 
12039   // If we didn't find a previous declaration, and this is a reference
12040   // (or friend reference), move to the correct scope.  In C++, we
12041   // also need to do a redeclaration lookup there, just in case
12042   // there's a shadow friend decl.
12043   if (Name && Previous.empty() &&
12044       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12045     if (Invalid) goto CreateNewDecl;
12046     assert(SS.isEmpty());
12047 
12048     if (TUK == TUK_Reference) {
12049       // C++ [basic.scope.pdecl]p5:
12050       //   -- for an elaborated-type-specifier of the form
12051       //
12052       //          class-key identifier
12053       //
12054       //      if the elaborated-type-specifier is used in the
12055       //      decl-specifier-seq or parameter-declaration-clause of a
12056       //      function defined in namespace scope, the identifier is
12057       //      declared as a class-name in the namespace that contains
12058       //      the declaration; otherwise, except as a friend
12059       //      declaration, the identifier is declared in the smallest
12060       //      non-class, non-function-prototype scope that contains the
12061       //      declaration.
12062       //
12063       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12064       // C structs and unions.
12065       //
12066       // It is an error in C++ to declare (rather than define) an enum
12067       // type, including via an elaborated type specifier.  We'll
12068       // diagnose that later; for now, declare the enum in the same
12069       // scope as we would have picked for any other tag type.
12070       //
12071       // GNU C also supports this behavior as part of its incomplete
12072       // enum types extension, while GNU C++ does not.
12073       //
12074       // Find the context where we'll be declaring the tag.
12075       // FIXME: We would like to maintain the current DeclContext as the
12076       // lexical context,
12077       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
12078         SearchDC = SearchDC->getParent();
12079 
12080       // Find the scope where we'll be declaring the tag.
12081       while (S->isClassScope() ||
12082              (getLangOpts().CPlusPlus &&
12083               S->isFunctionPrototypeScope()) ||
12084              ((S->getFlags() & Scope::DeclScope) == 0) ||
12085              (S->getEntity() && S->getEntity()->isTransparentContext()))
12086         S = S->getParent();
12087     } else {
12088       assert(TUK == TUK_Friend);
12089       // C++ [namespace.memdef]p3:
12090       //   If a friend declaration in a non-local class first declares a
12091       //   class or function, the friend class or function is a member of
12092       //   the innermost enclosing namespace.
12093       SearchDC = SearchDC->getEnclosingNamespaceContext();
12094     }
12095 
12096     // In C++, we need to do a redeclaration lookup to properly
12097     // diagnose some problems.
12098     if (getLangOpts().CPlusPlus) {
12099       Previous.setRedeclarationKind(ForRedeclaration);
12100       LookupQualifiedName(Previous, SearchDC);
12101     }
12102   }
12103 
12104   // If we have a known previous declaration to use, then use it.
12105   if (Previous.empty() && SkipBody && SkipBody->Previous)
12106     Previous.addDecl(SkipBody->Previous);
12107 
12108   if (!Previous.empty()) {
12109     NamedDecl *PrevDecl = Previous.getFoundDecl();
12110     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12111 
12112     // It's okay to have a tag decl in the same scope as a typedef
12113     // which hides a tag decl in the same scope.  Finding this
12114     // insanity with a redeclaration lookup can only actually happen
12115     // in C++.
12116     //
12117     // This is also okay for elaborated-type-specifiers, which is
12118     // technically forbidden by the current standard but which is
12119     // okay according to the likely resolution of an open issue;
12120     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12121     if (getLangOpts().CPlusPlus) {
12122       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12123         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12124           TagDecl *Tag = TT->getDecl();
12125           if (Tag->getDeclName() == Name &&
12126               Tag->getDeclContext()->getRedeclContext()
12127                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
12128             PrevDecl = Tag;
12129             Previous.clear();
12130             Previous.addDecl(Tag);
12131             Previous.resolveKind();
12132           }
12133         }
12134       }
12135     }
12136 
12137     // If this is a redeclaration of a using shadow declaration, it must
12138     // declare a tag in the same context. In MSVC mode, we allow a
12139     // redefinition if either context is within the other.
12140     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12141       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12142       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12143           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12144           !(OldTag && isAcceptableTagRedeclContext(
12145                           *this, OldTag->getDeclContext(), SearchDC))) {
12146         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12147         Diag(Shadow->getTargetDecl()->getLocation(),
12148              diag::note_using_decl_target);
12149         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12150             << 0;
12151         // Recover by ignoring the old declaration.
12152         Previous.clear();
12153         goto CreateNewDecl;
12154       }
12155     }
12156 
12157     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12158       // If this is a use of a previous tag, or if the tag is already declared
12159       // in the same scope (so that the definition/declaration completes or
12160       // rementions the tag), reuse the decl.
12161       if (TUK == TUK_Reference || TUK == TUK_Friend ||
12162           isDeclInScope(DirectPrevDecl, SearchDC, S,
12163                         SS.isNotEmpty() || isExplicitSpecialization)) {
12164         // Make sure that this wasn't declared as an enum and now used as a
12165         // struct or something similar.
12166         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12167                                           TUK == TUK_Definition, KWLoc,
12168                                           Name)) {
12169           bool SafeToContinue
12170             = (PrevTagDecl->getTagKind() != TTK_Enum &&
12171                Kind != TTK_Enum);
12172           if (SafeToContinue)
12173             Diag(KWLoc, diag::err_use_with_wrong_tag)
12174               << Name
12175               << FixItHint::CreateReplacement(SourceRange(KWLoc),
12176                                               PrevTagDecl->getKindName());
12177           else
12178             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12179           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12180 
12181           if (SafeToContinue)
12182             Kind = PrevTagDecl->getTagKind();
12183           else {
12184             // Recover by making this an anonymous redefinition.
12185             Name = nullptr;
12186             Previous.clear();
12187             Invalid = true;
12188           }
12189         }
12190 
12191         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12192           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12193 
12194           // If this is an elaborated-type-specifier for a scoped enumeration,
12195           // the 'class' keyword is not necessary and not permitted.
12196           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12197             if (ScopedEnum)
12198               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12199                 << PrevEnum->isScoped()
12200                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12201             return PrevTagDecl;
12202           }
12203 
12204           QualType EnumUnderlyingTy;
12205           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12206             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12207           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12208             EnumUnderlyingTy = QualType(T, 0);
12209 
12210           // All conflicts with previous declarations are recovered by
12211           // returning the previous declaration, unless this is a definition,
12212           // in which case we want the caller to bail out.
12213           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12214                                      ScopedEnum, EnumUnderlyingTy,
12215                                      EnumUnderlyingIsImplicit, PrevEnum))
12216             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12217         }
12218 
12219         // C++11 [class.mem]p1:
12220         //   A member shall not be declared twice in the member-specification,
12221         //   except that a nested class or member class template can be declared
12222         //   and then later defined.
12223         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12224             S->isDeclScope(PrevDecl)) {
12225           Diag(NameLoc, diag::ext_member_redeclared);
12226           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12227         }
12228 
12229         if (!Invalid) {
12230           // If this is a use, just return the declaration we found, unless
12231           // we have attributes.
12232 
12233           // FIXME: In the future, return a variant or some other clue
12234           // for the consumer of this Decl to know it doesn't own it.
12235           // For our current ASTs this shouldn't be a problem, but will
12236           // need to be changed with DeclGroups.
12237           if (!Attr &&
12238               ((TUK == TUK_Reference &&
12239                 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
12240                || TUK == TUK_Friend))
12241             return PrevTagDecl;
12242 
12243           // Diagnose attempts to redefine a tag.
12244           if (TUK == TUK_Definition) {
12245             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12246               // If we're defining a specialization and the previous definition
12247               // is from an implicit instantiation, don't emit an error
12248               // here; we'll catch this in the general case below.
12249               bool IsExplicitSpecializationAfterInstantiation = false;
12250               if (isExplicitSpecialization) {
12251                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12252                   IsExplicitSpecializationAfterInstantiation =
12253                     RD->getTemplateSpecializationKind() !=
12254                     TSK_ExplicitSpecialization;
12255                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12256                   IsExplicitSpecializationAfterInstantiation =
12257                     ED->getTemplateSpecializationKind() !=
12258                     TSK_ExplicitSpecialization;
12259               }
12260 
12261               NamedDecl *Hidden = nullptr;
12262               if (SkipBody && getLangOpts().CPlusPlus &&
12263                   !hasVisibleDefinition(Def, &Hidden)) {
12264                 // There is a definition of this tag, but it is not visible. We
12265                 // explicitly make use of C++'s one definition rule here, and
12266                 // assume that this definition is identical to the hidden one
12267                 // we already have. Make the existing definition visible and
12268                 // use it in place of this one.
12269                 SkipBody->ShouldSkip = true;
12270                 makeMergedDefinitionVisible(Hidden, KWLoc);
12271                 return Def;
12272               } else if (!IsExplicitSpecializationAfterInstantiation) {
12273                 // A redeclaration in function prototype scope in C isn't
12274                 // visible elsewhere, so merely issue a warning.
12275                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12276                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12277                 else
12278                   Diag(NameLoc, diag::err_redefinition) << Name;
12279                 Diag(Def->getLocation(), diag::note_previous_definition);
12280                 // If this is a redefinition, recover by making this
12281                 // struct be anonymous, which will make any later
12282                 // references get the previous definition.
12283                 Name = nullptr;
12284                 Previous.clear();
12285                 Invalid = true;
12286               }
12287             } else {
12288               // If the type is currently being defined, complain
12289               // about a nested redefinition.
12290               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12291               if (TD->isBeingDefined()) {
12292                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12293                 Diag(PrevTagDecl->getLocation(),
12294                      diag::note_previous_definition);
12295                 Name = nullptr;
12296                 Previous.clear();
12297                 Invalid = true;
12298               }
12299             }
12300 
12301             // Okay, this is definition of a previously declared or referenced
12302             // tag. We're going to create a new Decl for it.
12303           }
12304 
12305           // Okay, we're going to make a redeclaration.  If this is some kind
12306           // of reference, make sure we build the redeclaration in the same DC
12307           // as the original, and ignore the current access specifier.
12308           if (TUK == TUK_Friend || TUK == TUK_Reference) {
12309             SearchDC = PrevTagDecl->getDeclContext();
12310             AS = AS_none;
12311           }
12312         }
12313         // If we get here we have (another) forward declaration or we
12314         // have a definition.  Just create a new decl.
12315 
12316       } else {
12317         // If we get here, this is a definition of a new tag type in a nested
12318         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12319         // new decl/type.  We set PrevDecl to NULL so that the entities
12320         // have distinct types.
12321         Previous.clear();
12322       }
12323       // If we get here, we're going to create a new Decl. If PrevDecl
12324       // is non-NULL, it's a definition of the tag declared by
12325       // PrevDecl. If it's NULL, we have a new definition.
12326 
12327 
12328     // Otherwise, PrevDecl is not a tag, but was found with tag
12329     // lookup.  This is only actually possible in C++, where a few
12330     // things like templates still live in the tag namespace.
12331     } else {
12332       // Use a better diagnostic if an elaborated-type-specifier
12333       // found the wrong kind of type on the first
12334       // (non-redeclaration) lookup.
12335       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12336           !Previous.isForRedeclaration()) {
12337         unsigned Kind = 0;
12338         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12339         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12340         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12341         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12342         Diag(PrevDecl->getLocation(), diag::note_declared_at);
12343         Invalid = true;
12344 
12345       // Otherwise, only diagnose if the declaration is in scope.
12346       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12347                                 SS.isNotEmpty() || isExplicitSpecialization)) {
12348         // do nothing
12349 
12350       // Diagnose implicit declarations introduced by elaborated types.
12351       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12352         unsigned Kind = 0;
12353         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12354         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12355         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12356         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12357         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12358         Invalid = true;
12359 
12360       // Otherwise it's a declaration.  Call out a particularly common
12361       // case here.
12362       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12363         unsigned Kind = 0;
12364         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12365         Diag(NameLoc, diag::err_tag_definition_of_typedef)
12366           << Name << Kind << TND->getUnderlyingType();
12367         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12368         Invalid = true;
12369 
12370       // Otherwise, diagnose.
12371       } else {
12372         // The tag name clashes with something else in the target scope,
12373         // issue an error and recover by making this tag be anonymous.
12374         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12375         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12376         Name = nullptr;
12377         Invalid = true;
12378       }
12379 
12380       // The existing declaration isn't relevant to us; we're in a
12381       // new scope, so clear out the previous declaration.
12382       Previous.clear();
12383     }
12384   }
12385 
12386 CreateNewDecl:
12387 
12388   TagDecl *PrevDecl = nullptr;
12389   if (Previous.isSingleResult())
12390     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12391 
12392   // If there is an identifier, use the location of the identifier as the
12393   // location of the decl, otherwise use the location of the struct/union
12394   // keyword.
12395   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12396 
12397   // Otherwise, create a new declaration. If there is a previous
12398   // declaration of the same entity, the two will be linked via
12399   // PrevDecl.
12400   TagDecl *New;
12401 
12402   bool IsForwardReference = false;
12403   if (Kind == TTK_Enum) {
12404     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12405     // enum X { A, B, C } D;    D should chain to X.
12406     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12407                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12408                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12409     // If this is an undefined enum, warn.
12410     if (TUK != TUK_Definition && !Invalid) {
12411       TagDecl *Def;
12412       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12413           cast<EnumDecl>(New)->isFixed()) {
12414         // C++0x: 7.2p2: opaque-enum-declaration.
12415         // Conflicts are diagnosed above. Do nothing.
12416       }
12417       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12418         Diag(Loc, diag::ext_forward_ref_enum_def)
12419           << New;
12420         Diag(Def->getLocation(), diag::note_previous_definition);
12421       } else {
12422         unsigned DiagID = diag::ext_forward_ref_enum;
12423         if (getLangOpts().MSVCCompat)
12424           DiagID = diag::ext_ms_forward_ref_enum;
12425         else if (getLangOpts().CPlusPlus)
12426           DiagID = diag::err_forward_ref_enum;
12427         Diag(Loc, DiagID);
12428 
12429         // If this is a forward-declared reference to an enumeration, make a
12430         // note of it; we won't actually be introducing the declaration into
12431         // the declaration context.
12432         if (TUK == TUK_Reference)
12433           IsForwardReference = true;
12434       }
12435     }
12436 
12437     if (EnumUnderlying) {
12438       EnumDecl *ED = cast<EnumDecl>(New);
12439       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12440         ED->setIntegerTypeSourceInfo(TI);
12441       else
12442         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12443       ED->setPromotionType(ED->getIntegerType());
12444     }
12445 
12446   } else {
12447     // struct/union/class
12448 
12449     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12450     // struct X { int A; } D;    D should chain to X.
12451     if (getLangOpts().CPlusPlus) {
12452       // FIXME: Look for a way to use RecordDecl for simple structs.
12453       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12454                                   cast_or_null<CXXRecordDecl>(PrevDecl));
12455 
12456       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12457         StdBadAlloc = cast<CXXRecordDecl>(New);
12458     } else
12459       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12460                                cast_or_null<RecordDecl>(PrevDecl));
12461   }
12462 
12463   // C++11 [dcl.type]p3:
12464   //   A type-specifier-seq shall not define a class or enumeration [...].
12465   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12466     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12467       << Context.getTagDeclType(New);
12468     Invalid = true;
12469   }
12470 
12471   // Maybe add qualifier info.
12472   if (SS.isNotEmpty()) {
12473     if (SS.isSet()) {
12474       // If this is either a declaration or a definition, check the
12475       // nested-name-specifier against the current context. We don't do this
12476       // for explicit specializations, because they have similar checking
12477       // (with more specific diagnostics) in the call to
12478       // CheckMemberSpecialization, below.
12479       if (!isExplicitSpecialization &&
12480           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12481           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12482         Invalid = true;
12483 
12484       New->setQualifierInfo(SS.getWithLocInContext(Context));
12485       if (TemplateParameterLists.size() > 0) {
12486         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12487       }
12488     }
12489     else
12490       Invalid = true;
12491   }
12492 
12493   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12494     // Add alignment attributes if necessary; these attributes are checked when
12495     // the ASTContext lays out the structure.
12496     //
12497     // It is important for implementing the correct semantics that this
12498     // happen here (in act on tag decl). The #pragma pack stack is
12499     // maintained as a result of parser callbacks which can occur at
12500     // many points during the parsing of a struct declaration (because
12501     // the #pragma tokens are effectively skipped over during the
12502     // parsing of the struct).
12503     if (TUK == TUK_Definition) {
12504       AddAlignmentAttributesForRecord(RD);
12505       AddMsStructLayoutForRecord(RD);
12506     }
12507   }
12508 
12509   if (ModulePrivateLoc.isValid()) {
12510     if (isExplicitSpecialization)
12511       Diag(New->getLocation(), diag::err_module_private_specialization)
12512         << 2
12513         << FixItHint::CreateRemoval(ModulePrivateLoc);
12514     // __module_private__ does not apply to local classes. However, we only
12515     // diagnose this as an error when the declaration specifiers are
12516     // freestanding. Here, we just ignore the __module_private__.
12517     else if (!SearchDC->isFunctionOrMethod())
12518       New->setModulePrivate();
12519   }
12520 
12521   // If this is a specialization of a member class (of a class template),
12522   // check the specialization.
12523   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12524     Invalid = true;
12525 
12526   // If we're declaring or defining a tag in function prototype scope in C,
12527   // note that this type can only be used within the function and add it to
12528   // the list of decls to inject into the function definition scope.
12529   if ((Name || Kind == TTK_Enum) &&
12530       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12531     if (getLangOpts().CPlusPlus) {
12532       // C++ [dcl.fct]p6:
12533       //   Types shall not be defined in return or parameter types.
12534       if (TUK == TUK_Definition && !IsTypeSpecifier) {
12535         Diag(Loc, diag::err_type_defined_in_param_type)
12536             << Name;
12537         Invalid = true;
12538       }
12539     } else {
12540       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
12541     }
12542     DeclsInPrototypeScope.push_back(New);
12543   }
12544 
12545   if (Invalid)
12546     New->setInvalidDecl();
12547 
12548   if (Attr)
12549     ProcessDeclAttributeList(S, New, Attr);
12550 
12551   // Set the lexical context. If the tag has a C++ scope specifier, the
12552   // lexical context will be different from the semantic context.
12553   New->setLexicalDeclContext(CurContext);
12554 
12555   // Mark this as a friend decl if applicable.
12556   // In Microsoft mode, a friend declaration also acts as a forward
12557   // declaration so we always pass true to setObjectOfFriendDecl to make
12558   // the tag name visible.
12559   if (TUK == TUK_Friend)
12560     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
12561 
12562   // Set the access specifier.
12563   if (!Invalid && SearchDC->isRecord())
12564     SetMemberAccessSpecifier(New, PrevDecl, AS);
12565 
12566   if (TUK == TUK_Definition)
12567     New->startDefinition();
12568 
12569   // If this has an identifier, add it to the scope stack.
12570   if (TUK == TUK_Friend) {
12571     // We might be replacing an existing declaration in the lookup tables;
12572     // if so, borrow its access specifier.
12573     if (PrevDecl)
12574       New->setAccess(PrevDecl->getAccess());
12575 
12576     DeclContext *DC = New->getDeclContext()->getRedeclContext();
12577     DC->makeDeclVisibleInContext(New);
12578     if (Name) // can be null along some error paths
12579       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12580         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
12581   } else if (Name) {
12582     S = getNonFieldDeclScope(S);
12583     PushOnScopeChains(New, S, !IsForwardReference);
12584     if (IsForwardReference)
12585       SearchDC->makeDeclVisibleInContext(New);
12586 
12587   } else {
12588     CurContext->addDecl(New);
12589   }
12590 
12591   // If this is the C FILE type, notify the AST context.
12592   if (IdentifierInfo *II = New->getIdentifier())
12593     if (!New->isInvalidDecl() &&
12594         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
12595         II->isStr("FILE"))
12596       Context.setFILEDecl(New);
12597 
12598   if (PrevDecl)
12599     mergeDeclAttributes(New, PrevDecl);
12600 
12601   // If there's a #pragma GCC visibility in scope, set the visibility of this
12602   // record.
12603   AddPushedVisibilityAttribute(New);
12604 
12605   OwnedDecl = true;
12606   // In C++, don't return an invalid declaration. We can't recover well from
12607   // the cases where we make the type anonymous.
12608   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
12609 }
12610 
12611 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
12612   AdjustDeclIfTemplate(TagD);
12613   TagDecl *Tag = cast<TagDecl>(TagD);
12614 
12615   // Enter the tag context.
12616   PushDeclContext(S, Tag);
12617 
12618   ActOnDocumentableDecl(TagD);
12619 
12620   // If there's a #pragma GCC visibility in scope, set the visibility of this
12621   // record.
12622   AddPushedVisibilityAttribute(Tag);
12623 }
12624 
12625 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
12626   assert(isa<ObjCContainerDecl>(IDecl) &&
12627          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
12628   DeclContext *OCD = cast<DeclContext>(IDecl);
12629   assert(getContainingDC(OCD) == CurContext &&
12630       "The next DeclContext should be lexically contained in the current one.");
12631   CurContext = OCD;
12632   return IDecl;
12633 }
12634 
12635 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
12636                                            SourceLocation FinalLoc,
12637                                            bool IsFinalSpelledSealed,
12638                                            SourceLocation LBraceLoc) {
12639   AdjustDeclIfTemplate(TagD);
12640   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
12641 
12642   FieldCollector->StartClass();
12643 
12644   if (!Record->getIdentifier())
12645     return;
12646 
12647   if (FinalLoc.isValid())
12648     Record->addAttr(new (Context)
12649                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
12650 
12651   // C++ [class]p2:
12652   //   [...] The class-name is also inserted into the scope of the
12653   //   class itself; this is known as the injected-class-name. For
12654   //   purposes of access checking, the injected-class-name is treated
12655   //   as if it were a public member name.
12656   CXXRecordDecl *InjectedClassName
12657     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
12658                             Record->getLocStart(), Record->getLocation(),
12659                             Record->getIdentifier(),
12660                             /*PrevDecl=*/nullptr,
12661                             /*DelayTypeCreation=*/true);
12662   Context.getTypeDeclType(InjectedClassName, Record);
12663   InjectedClassName->setImplicit();
12664   InjectedClassName->setAccess(AS_public);
12665   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
12666       InjectedClassName->setDescribedClassTemplate(Template);
12667   PushOnScopeChains(InjectedClassName, S);
12668   assert(InjectedClassName->isInjectedClassName() &&
12669          "Broken injected-class-name");
12670 }
12671 
12672 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
12673                                     SourceLocation RBraceLoc) {
12674   AdjustDeclIfTemplate(TagD);
12675   TagDecl *Tag = cast<TagDecl>(TagD);
12676   Tag->setRBraceLoc(RBraceLoc);
12677 
12678   // Make sure we "complete" the definition even it is invalid.
12679   if (Tag->isBeingDefined()) {
12680     assert(Tag->isInvalidDecl() && "We should already have completed it");
12681     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12682       RD->completeDefinition();
12683   }
12684 
12685   if (isa<CXXRecordDecl>(Tag))
12686     FieldCollector->FinishClass();
12687 
12688   // Exit this scope of this tag's definition.
12689   PopDeclContext();
12690 
12691   if (getCurLexicalContext()->isObjCContainer() &&
12692       Tag->getDeclContext()->isFileContext())
12693     Tag->setTopLevelDeclInObjCContainer();
12694 
12695   // Notify the consumer that we've defined a tag.
12696   if (!Tag->isInvalidDecl())
12697     Consumer.HandleTagDeclDefinition(Tag);
12698 }
12699 
12700 void Sema::ActOnObjCContainerFinishDefinition() {
12701   // Exit this scope of this interface definition.
12702   PopDeclContext();
12703 }
12704 
12705 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
12706   assert(DC == CurContext && "Mismatch of container contexts");
12707   OriginalLexicalContext = DC;
12708   ActOnObjCContainerFinishDefinition();
12709 }
12710 
12711 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
12712   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
12713   OriginalLexicalContext = nullptr;
12714 }
12715 
12716 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
12717   AdjustDeclIfTemplate(TagD);
12718   TagDecl *Tag = cast<TagDecl>(TagD);
12719   Tag->setInvalidDecl();
12720 
12721   // Make sure we "complete" the definition even it is invalid.
12722   if (Tag->isBeingDefined()) {
12723     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12724       RD->completeDefinition();
12725   }
12726 
12727   // We're undoing ActOnTagStartDefinition here, not
12728   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
12729   // the FieldCollector.
12730 
12731   PopDeclContext();
12732 }
12733 
12734 // Note that FieldName may be null for anonymous bitfields.
12735 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
12736                                 IdentifierInfo *FieldName,
12737                                 QualType FieldTy, bool IsMsStruct,
12738                                 Expr *BitWidth, bool *ZeroWidth) {
12739   // Default to true; that shouldn't confuse checks for emptiness
12740   if (ZeroWidth)
12741     *ZeroWidth = true;
12742 
12743   // C99 6.7.2.1p4 - verify the field type.
12744   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
12745   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
12746     // Handle incomplete types with specific error.
12747     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
12748       return ExprError();
12749     if (FieldName)
12750       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12751         << FieldName << FieldTy << BitWidth->getSourceRange();
12752     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12753       << FieldTy << BitWidth->getSourceRange();
12754   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12755                                              UPPC_BitFieldWidth))
12756     return ExprError();
12757 
12758   // If the bit-width is type- or value-dependent, don't try to check
12759   // it now.
12760   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
12761     return BitWidth;
12762 
12763   llvm::APSInt Value;
12764   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
12765   if (ICE.isInvalid())
12766     return ICE;
12767   BitWidth = ICE.get();
12768 
12769   if (Value != 0 && ZeroWidth)
12770     *ZeroWidth = false;
12771 
12772   // Zero-width bitfield is ok for anonymous field.
12773   if (Value == 0 && FieldName)
12774     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
12775 
12776   if (Value.isSigned() && Value.isNegative()) {
12777     if (FieldName)
12778       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
12779                << FieldName << Value.toString(10);
12780     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
12781       << Value.toString(10);
12782   }
12783 
12784   if (!FieldTy->isDependentType()) {
12785     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
12786     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
12787     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
12788 
12789     // Over-wide bitfields are an error in C or when using the MSVC bitfield
12790     // ABI.
12791     bool CStdConstraintViolation =
12792         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
12793     bool MSBitfieldViolation =
12794         Value.ugt(TypeStorageSize) &&
12795         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
12796     if (CStdConstraintViolation || MSBitfieldViolation) {
12797       unsigned DiagWidth =
12798           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
12799       if (FieldName)
12800         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
12801                << FieldName << (unsigned)Value.getZExtValue()
12802                << !CStdConstraintViolation << DiagWidth;
12803 
12804       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
12805              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
12806              << DiagWidth;
12807     }
12808 
12809     // Warn on types where the user might conceivably expect to get all
12810     // specified bits as value bits: that's all integral types other than
12811     // 'bool'.
12812     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
12813       if (FieldName)
12814         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
12815             << FieldName << (unsigned)Value.getZExtValue()
12816             << (unsigned)TypeWidth;
12817       else
12818         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
12819             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
12820     }
12821   }
12822 
12823   return BitWidth;
12824 }
12825 
12826 /// ActOnField - Each field of a C struct/union is passed into this in order
12827 /// to create a FieldDecl object for it.
12828 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
12829                        Declarator &D, Expr *BitfieldWidth) {
12830   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
12831                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
12832                                /*InitStyle=*/ICIS_NoInit, AS_public);
12833   return Res;
12834 }
12835 
12836 /// HandleField - Analyze a field of a C struct or a C++ data member.
12837 ///
12838 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
12839                              SourceLocation DeclStart,
12840                              Declarator &D, Expr *BitWidth,
12841                              InClassInitStyle InitStyle,
12842                              AccessSpecifier AS) {
12843   IdentifierInfo *II = D.getIdentifier();
12844   SourceLocation Loc = DeclStart;
12845   if (II) Loc = D.getIdentifierLoc();
12846 
12847   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12848   QualType T = TInfo->getType();
12849   if (getLangOpts().CPlusPlus) {
12850     CheckExtraCXXDefaultArguments(D);
12851 
12852     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12853                                         UPPC_DataMemberType)) {
12854       D.setInvalidType();
12855       T = Context.IntTy;
12856       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12857     }
12858   }
12859 
12860   // TR 18037 does not allow fields to be declared with address spaces.
12861   if (T.getQualifiers().hasAddressSpace()) {
12862     Diag(Loc, diag::err_field_with_address_space);
12863     D.setInvalidType();
12864   }
12865 
12866   // OpenCL 1.2 spec, s6.9 r:
12867   // The event type cannot be used to declare a structure or union field.
12868   if (LangOpts.OpenCL && T->isEventT()) {
12869     Diag(Loc, diag::err_event_t_struct_field);
12870     D.setInvalidType();
12871   }
12872 
12873   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12874 
12875   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12876     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12877          diag::err_invalid_thread)
12878       << DeclSpec::getSpecifierName(TSCS);
12879 
12880   // Check to see if this name was declared as a member previously
12881   NamedDecl *PrevDecl = nullptr;
12882   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12883   LookupName(Previous, S);
12884   switch (Previous.getResultKind()) {
12885     case LookupResult::Found:
12886     case LookupResult::FoundUnresolvedValue:
12887       PrevDecl = Previous.getAsSingle<NamedDecl>();
12888       break;
12889 
12890     case LookupResult::FoundOverloaded:
12891       PrevDecl = Previous.getRepresentativeDecl();
12892       break;
12893 
12894     case LookupResult::NotFound:
12895     case LookupResult::NotFoundInCurrentInstantiation:
12896     case LookupResult::Ambiguous:
12897       break;
12898   }
12899   Previous.suppressDiagnostics();
12900 
12901   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12902     // Maybe we will complain about the shadowed template parameter.
12903     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12904     // Just pretend that we didn't see the previous declaration.
12905     PrevDecl = nullptr;
12906   }
12907 
12908   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12909     PrevDecl = nullptr;
12910 
12911   bool Mutable
12912     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
12913   SourceLocation TSSL = D.getLocStart();
12914   FieldDecl *NewFD
12915     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
12916                      TSSL, AS, PrevDecl, &D);
12917 
12918   if (NewFD->isInvalidDecl())
12919     Record->setInvalidDecl();
12920 
12921   if (D.getDeclSpec().isModulePrivateSpecified())
12922     NewFD->setModulePrivate();
12923 
12924   if (NewFD->isInvalidDecl() && PrevDecl) {
12925     // Don't introduce NewFD into scope; there's already something
12926     // with the same name in the same scope.
12927   } else if (II) {
12928     PushOnScopeChains(NewFD, S);
12929   } else
12930     Record->addDecl(NewFD);
12931 
12932   return NewFD;
12933 }
12934 
12935 /// \brief Build a new FieldDecl and check its well-formedness.
12936 ///
12937 /// This routine builds a new FieldDecl given the fields name, type,
12938 /// record, etc. \p PrevDecl should refer to any previous declaration
12939 /// with the same name and in the same scope as the field to be
12940 /// created.
12941 ///
12942 /// \returns a new FieldDecl.
12943 ///
12944 /// \todo The Declarator argument is a hack. It will be removed once
12945 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
12946                                 TypeSourceInfo *TInfo,
12947                                 RecordDecl *Record, SourceLocation Loc,
12948                                 bool Mutable, Expr *BitWidth,
12949                                 InClassInitStyle InitStyle,
12950                                 SourceLocation TSSL,
12951                                 AccessSpecifier AS, NamedDecl *PrevDecl,
12952                                 Declarator *D) {
12953   IdentifierInfo *II = Name.getAsIdentifierInfo();
12954   bool InvalidDecl = false;
12955   if (D) InvalidDecl = D->isInvalidType();
12956 
12957   // If we receive a broken type, recover by assuming 'int' and
12958   // marking this declaration as invalid.
12959   if (T.isNull()) {
12960     InvalidDecl = true;
12961     T = Context.IntTy;
12962   }
12963 
12964   QualType EltTy = Context.getBaseElementType(T);
12965   if (!EltTy->isDependentType()) {
12966     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
12967       // Fields of incomplete type force their record to be invalid.
12968       Record->setInvalidDecl();
12969       InvalidDecl = true;
12970     } else {
12971       NamedDecl *Def;
12972       EltTy->isIncompleteType(&Def);
12973       if (Def && Def->isInvalidDecl()) {
12974         Record->setInvalidDecl();
12975         InvalidDecl = true;
12976       }
12977     }
12978   }
12979 
12980   // OpenCL v1.2 s6.9.c: bitfields are not supported.
12981   if (BitWidth && getLangOpts().OpenCL) {
12982     Diag(Loc, diag::err_opencl_bitfields);
12983     InvalidDecl = true;
12984   }
12985 
12986   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12987   // than a variably modified type.
12988   if (!InvalidDecl && T->isVariablyModifiedType()) {
12989     bool SizeIsNegative;
12990     llvm::APSInt Oversized;
12991 
12992     TypeSourceInfo *FixedTInfo =
12993       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
12994                                                     SizeIsNegative,
12995                                                     Oversized);
12996     if (FixedTInfo) {
12997       Diag(Loc, diag::warn_illegal_constant_array_size);
12998       TInfo = FixedTInfo;
12999       T = FixedTInfo->getType();
13000     } else {
13001       if (SizeIsNegative)
13002         Diag(Loc, diag::err_typecheck_negative_array_size);
13003       else if (Oversized.getBoolValue())
13004         Diag(Loc, diag::err_array_too_large)
13005           << Oversized.toString(10);
13006       else
13007         Diag(Loc, diag::err_typecheck_field_variable_size);
13008       InvalidDecl = true;
13009     }
13010   }
13011 
13012   // Fields can not have abstract class types
13013   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13014                                              diag::err_abstract_type_in_decl,
13015                                              AbstractFieldType))
13016     InvalidDecl = true;
13017 
13018   bool ZeroWidth = false;
13019   if (InvalidDecl)
13020     BitWidth = nullptr;
13021   // If this is declared as a bit-field, check the bit-field.
13022   if (BitWidth) {
13023     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13024                               &ZeroWidth).get();
13025     if (!BitWidth) {
13026       InvalidDecl = true;
13027       BitWidth = nullptr;
13028       ZeroWidth = false;
13029     }
13030   }
13031 
13032   // Check that 'mutable' is consistent with the type of the declaration.
13033   if (!InvalidDecl && Mutable) {
13034     unsigned DiagID = 0;
13035     if (T->isReferenceType())
13036       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13037                                         : diag::err_mutable_reference;
13038     else if (T.isConstQualified())
13039       DiagID = diag::err_mutable_const;
13040 
13041     if (DiagID) {
13042       SourceLocation ErrLoc = Loc;
13043       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13044         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13045       Diag(ErrLoc, DiagID);
13046       if (DiagID != diag::ext_mutable_reference) {
13047         Mutable = false;
13048         InvalidDecl = true;
13049       }
13050     }
13051   }
13052 
13053   // C++11 [class.union]p8 (DR1460):
13054   //   At most one variant member of a union may have a
13055   //   brace-or-equal-initializer.
13056   if (InitStyle != ICIS_NoInit)
13057     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13058 
13059   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13060                                        BitWidth, Mutable, InitStyle);
13061   if (InvalidDecl)
13062     NewFD->setInvalidDecl();
13063 
13064   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13065     Diag(Loc, diag::err_duplicate_member) << II;
13066     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13067     NewFD->setInvalidDecl();
13068   }
13069 
13070   if (!InvalidDecl && getLangOpts().CPlusPlus) {
13071     if (Record->isUnion()) {
13072       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13073         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13074         if (RDecl->getDefinition()) {
13075           // C++ [class.union]p1: An object of a class with a non-trivial
13076           // constructor, a non-trivial copy constructor, a non-trivial
13077           // destructor, or a non-trivial copy assignment operator
13078           // cannot be a member of a union, nor can an array of such
13079           // objects.
13080           if (CheckNontrivialField(NewFD))
13081             NewFD->setInvalidDecl();
13082         }
13083       }
13084 
13085       // C++ [class.union]p1: If a union contains a member of reference type,
13086       // the program is ill-formed, except when compiling with MSVC extensions
13087       // enabled.
13088       if (EltTy->isReferenceType()) {
13089         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13090                                     diag::ext_union_member_of_reference_type :
13091                                     diag::err_union_member_of_reference_type)
13092           << NewFD->getDeclName() << EltTy;
13093         if (!getLangOpts().MicrosoftExt)
13094           NewFD->setInvalidDecl();
13095       }
13096     }
13097   }
13098 
13099   // FIXME: We need to pass in the attributes given an AST
13100   // representation, not a parser representation.
13101   if (D) {
13102     // FIXME: The current scope is almost... but not entirely... correct here.
13103     ProcessDeclAttributes(getCurScope(), NewFD, *D);
13104 
13105     if (NewFD->hasAttrs())
13106       CheckAlignasUnderalignment(NewFD);
13107   }
13108 
13109   // In auto-retain/release, infer strong retension for fields of
13110   // retainable type.
13111   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13112     NewFD->setInvalidDecl();
13113 
13114   if (T.isObjCGCWeak())
13115     Diag(Loc, diag::warn_attribute_weak_on_field);
13116 
13117   NewFD->setAccess(AS);
13118   return NewFD;
13119 }
13120 
13121 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13122   assert(FD);
13123   assert(getLangOpts().CPlusPlus && "valid check only for C++");
13124 
13125   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13126     return false;
13127 
13128   QualType EltTy = Context.getBaseElementType(FD->getType());
13129   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13130     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13131     if (RDecl->getDefinition()) {
13132       // We check for copy constructors before constructors
13133       // because otherwise we'll never get complaints about
13134       // copy constructors.
13135 
13136       CXXSpecialMember member = CXXInvalid;
13137       // We're required to check for any non-trivial constructors. Since the
13138       // implicit default constructor is suppressed if there are any
13139       // user-declared constructors, we just need to check that there is a
13140       // trivial default constructor and a trivial copy constructor. (We don't
13141       // worry about move constructors here, since this is a C++98 check.)
13142       if (RDecl->hasNonTrivialCopyConstructor())
13143         member = CXXCopyConstructor;
13144       else if (!RDecl->hasTrivialDefaultConstructor())
13145         member = CXXDefaultConstructor;
13146       else if (RDecl->hasNonTrivialCopyAssignment())
13147         member = CXXCopyAssignment;
13148       else if (RDecl->hasNonTrivialDestructor())
13149         member = CXXDestructor;
13150 
13151       if (member != CXXInvalid) {
13152         if (!getLangOpts().CPlusPlus11 &&
13153             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13154           // Objective-C++ ARC: it is an error to have a non-trivial field of
13155           // a union. However, system headers in Objective-C programs
13156           // occasionally have Objective-C lifetime objects within unions,
13157           // and rather than cause the program to fail, we make those
13158           // members unavailable.
13159           SourceLocation Loc = FD->getLocation();
13160           if (getSourceManager().isInSystemHeader(Loc)) {
13161             if (!FD->hasAttr<UnavailableAttr>())
13162               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13163                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13164             return false;
13165           }
13166         }
13167 
13168         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13169                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13170                diag::err_illegal_union_or_anon_struct_member)
13171           << FD->getParent()->isUnion() << FD->getDeclName() << member;
13172         DiagnoseNontrivial(RDecl, member);
13173         return !getLangOpts().CPlusPlus11;
13174       }
13175     }
13176   }
13177 
13178   return false;
13179 }
13180 
13181 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13182 ///  AST enum value.
13183 static ObjCIvarDecl::AccessControl
13184 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13185   switch (ivarVisibility) {
13186   default: llvm_unreachable("Unknown visitibility kind");
13187   case tok::objc_private: return ObjCIvarDecl::Private;
13188   case tok::objc_public: return ObjCIvarDecl::Public;
13189   case tok::objc_protected: return ObjCIvarDecl::Protected;
13190   case tok::objc_package: return ObjCIvarDecl::Package;
13191   }
13192 }
13193 
13194 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13195 /// in order to create an IvarDecl object for it.
13196 Decl *Sema::ActOnIvar(Scope *S,
13197                                 SourceLocation DeclStart,
13198                                 Declarator &D, Expr *BitfieldWidth,
13199                                 tok::ObjCKeywordKind Visibility) {
13200 
13201   IdentifierInfo *II = D.getIdentifier();
13202   Expr *BitWidth = (Expr*)BitfieldWidth;
13203   SourceLocation Loc = DeclStart;
13204   if (II) Loc = D.getIdentifierLoc();
13205 
13206   // FIXME: Unnamed fields can be handled in various different ways, for
13207   // example, unnamed unions inject all members into the struct namespace!
13208 
13209   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13210   QualType T = TInfo->getType();
13211 
13212   if (BitWidth) {
13213     // 6.7.2.1p3, 6.7.2.1p4
13214     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13215     if (!BitWidth)
13216       D.setInvalidType();
13217   } else {
13218     // Not a bitfield.
13219 
13220     // validate II.
13221 
13222   }
13223   if (T->isReferenceType()) {
13224     Diag(Loc, diag::err_ivar_reference_type);
13225     D.setInvalidType();
13226   }
13227   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13228   // than a variably modified type.
13229   else if (T->isVariablyModifiedType()) {
13230     Diag(Loc, diag::err_typecheck_ivar_variable_size);
13231     D.setInvalidType();
13232   }
13233 
13234   // Get the visibility (access control) for this ivar.
13235   ObjCIvarDecl::AccessControl ac =
13236     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13237                                         : ObjCIvarDecl::None;
13238   // Must set ivar's DeclContext to its enclosing interface.
13239   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13240   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13241     return nullptr;
13242   ObjCContainerDecl *EnclosingContext;
13243   if (ObjCImplementationDecl *IMPDecl =
13244       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13245     if (LangOpts.ObjCRuntime.isFragile()) {
13246     // Case of ivar declared in an implementation. Context is that of its class.
13247       EnclosingContext = IMPDecl->getClassInterface();
13248       assert(EnclosingContext && "Implementation has no class interface!");
13249     }
13250     else
13251       EnclosingContext = EnclosingDecl;
13252   } else {
13253     if (ObjCCategoryDecl *CDecl =
13254         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13255       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13256         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13257         return nullptr;
13258       }
13259     }
13260     EnclosingContext = EnclosingDecl;
13261   }
13262 
13263   // Construct the decl.
13264   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13265                                              DeclStart, Loc, II, T,
13266                                              TInfo, ac, (Expr *)BitfieldWidth);
13267 
13268   if (II) {
13269     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13270                                            ForRedeclaration);
13271     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13272         && !isa<TagDecl>(PrevDecl)) {
13273       Diag(Loc, diag::err_duplicate_member) << II;
13274       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13275       NewID->setInvalidDecl();
13276     }
13277   }
13278 
13279   // Process attributes attached to the ivar.
13280   ProcessDeclAttributes(S, NewID, D);
13281 
13282   if (D.isInvalidType())
13283     NewID->setInvalidDecl();
13284 
13285   // In ARC, infer 'retaining' for ivars of retainable type.
13286   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13287     NewID->setInvalidDecl();
13288 
13289   if (D.getDeclSpec().isModulePrivateSpecified())
13290     NewID->setModulePrivate();
13291 
13292   if (II) {
13293     // FIXME: When interfaces are DeclContexts, we'll need to add
13294     // these to the interface.
13295     S->AddDecl(NewID);
13296     IdResolver.AddDecl(NewID);
13297   }
13298 
13299   if (LangOpts.ObjCRuntime.isNonFragile() &&
13300       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13301     Diag(Loc, diag::warn_ivars_in_interface);
13302 
13303   return NewID;
13304 }
13305 
13306 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13307 /// class and class extensions. For every class \@interface and class
13308 /// extension \@interface, if the last ivar is a bitfield of any type,
13309 /// then add an implicit `char :0` ivar to the end of that interface.
13310 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13311                              SmallVectorImpl<Decl *> &AllIvarDecls) {
13312   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13313     return;
13314 
13315   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13316   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13317 
13318   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13319     return;
13320   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13321   if (!ID) {
13322     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13323       if (!CD->IsClassExtension())
13324         return;
13325     }
13326     // No need to add this to end of @implementation.
13327     else
13328       return;
13329   }
13330   // All conditions are met. Add a new bitfield to the tail end of ivars.
13331   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13332   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13333 
13334   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13335                               DeclLoc, DeclLoc, nullptr,
13336                               Context.CharTy,
13337                               Context.getTrivialTypeSourceInfo(Context.CharTy,
13338                                                                DeclLoc),
13339                               ObjCIvarDecl::Private, BW,
13340                               true);
13341   AllIvarDecls.push_back(Ivar);
13342 }
13343 
13344 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13345                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
13346                        SourceLocation RBrac, AttributeList *Attr) {
13347   assert(EnclosingDecl && "missing record or interface decl");
13348 
13349   // If this is an Objective-C @implementation or category and we have
13350   // new fields here we should reset the layout of the interface since
13351   // it will now change.
13352   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13353     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13354     switch (DC->getKind()) {
13355     default: break;
13356     case Decl::ObjCCategory:
13357       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13358       break;
13359     case Decl::ObjCImplementation:
13360       Context.
13361         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13362       break;
13363     }
13364   }
13365 
13366   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13367 
13368   // Start counting up the number of named members; make sure to include
13369   // members of anonymous structs and unions in the total.
13370   unsigned NumNamedMembers = 0;
13371   if (Record) {
13372     for (const auto *I : Record->decls()) {
13373       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13374         if (IFD->getDeclName())
13375           ++NumNamedMembers;
13376     }
13377   }
13378 
13379   // Verify that all the fields are okay.
13380   SmallVector<FieldDecl*, 32> RecFields;
13381 
13382   bool ARCErrReported = false;
13383   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13384        i != end; ++i) {
13385     FieldDecl *FD = cast<FieldDecl>(*i);
13386 
13387     // Get the type for the field.
13388     const Type *FDTy = FD->getType().getTypePtr();
13389 
13390     if (!FD->isAnonymousStructOrUnion()) {
13391       // Remember all fields written by the user.
13392       RecFields.push_back(FD);
13393     }
13394 
13395     // If the field is already invalid for some reason, don't emit more
13396     // diagnostics about it.
13397     if (FD->isInvalidDecl()) {
13398       EnclosingDecl->setInvalidDecl();
13399       continue;
13400     }
13401 
13402     // C99 6.7.2.1p2:
13403     //   A structure or union shall not contain a member with
13404     //   incomplete or function type (hence, a structure shall not
13405     //   contain an instance of itself, but may contain a pointer to
13406     //   an instance of itself), except that the last member of a
13407     //   structure with more than one named member may have incomplete
13408     //   array type; such a structure (and any union containing,
13409     //   possibly recursively, a member that is such a structure)
13410     //   shall not be a member of a structure or an element of an
13411     //   array.
13412     if (FDTy->isFunctionType()) {
13413       // Field declared as a function.
13414       Diag(FD->getLocation(), diag::err_field_declared_as_function)
13415         << FD->getDeclName();
13416       FD->setInvalidDecl();
13417       EnclosingDecl->setInvalidDecl();
13418       continue;
13419     } else if (FDTy->isIncompleteArrayType() && Record &&
13420                ((i + 1 == Fields.end() && !Record->isUnion()) ||
13421                 ((getLangOpts().MicrosoftExt ||
13422                   getLangOpts().CPlusPlus) &&
13423                  (i + 1 == Fields.end() || Record->isUnion())))) {
13424       // Flexible array member.
13425       // Microsoft and g++ is more permissive regarding flexible array.
13426       // It will accept flexible array in union and also
13427       // as the sole element of a struct/class.
13428       unsigned DiagID = 0;
13429       if (Record->isUnion())
13430         DiagID = getLangOpts().MicrosoftExt
13431                      ? diag::ext_flexible_array_union_ms
13432                      : getLangOpts().CPlusPlus
13433                            ? diag::ext_flexible_array_union_gnu
13434                            : diag::err_flexible_array_union;
13435       else if (Fields.size() == 1)
13436         DiagID = getLangOpts().MicrosoftExt
13437                      ? diag::ext_flexible_array_empty_aggregate_ms
13438                      : getLangOpts().CPlusPlus
13439                            ? diag::ext_flexible_array_empty_aggregate_gnu
13440                            : NumNamedMembers < 1
13441                                  ? diag::err_flexible_array_empty_aggregate
13442                                  : 0;
13443 
13444       if (DiagID)
13445         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13446                                         << Record->getTagKind();
13447       // While the layout of types that contain virtual bases is not specified
13448       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13449       // virtual bases after the derived members.  This would make a flexible
13450       // array member declared at the end of an object not adjacent to the end
13451       // of the type.
13452       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13453         if (RD->getNumVBases() != 0)
13454           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13455             << FD->getDeclName() << Record->getTagKind();
13456       if (!getLangOpts().C99)
13457         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13458           << FD->getDeclName() << Record->getTagKind();
13459 
13460       // If the element type has a non-trivial destructor, we would not
13461       // implicitly destroy the elements, so disallow it for now.
13462       //
13463       // FIXME: GCC allows this. We should probably either implicitly delete
13464       // the destructor of the containing class, or just allow this.
13465       QualType BaseElem = Context.getBaseElementType(FD->getType());
13466       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13467         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13468           << FD->getDeclName() << FD->getType();
13469         FD->setInvalidDecl();
13470         EnclosingDecl->setInvalidDecl();
13471         continue;
13472       }
13473       // Okay, we have a legal flexible array member at the end of the struct.
13474       Record->setHasFlexibleArrayMember(true);
13475     } else if (!FDTy->isDependentType() &&
13476                RequireCompleteType(FD->getLocation(), FD->getType(),
13477                                    diag::err_field_incomplete)) {
13478       // Incomplete type
13479       FD->setInvalidDecl();
13480       EnclosingDecl->setInvalidDecl();
13481       continue;
13482     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13483       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13484         // A type which contains a flexible array member is considered to be a
13485         // flexible array member.
13486         Record->setHasFlexibleArrayMember(true);
13487         if (!Record->isUnion()) {
13488           // If this is a struct/class and this is not the last element, reject
13489           // it.  Note that GCC supports variable sized arrays in the middle of
13490           // structures.
13491           if (i + 1 != Fields.end())
13492             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13493               << FD->getDeclName() << FD->getType();
13494           else {
13495             // We support flexible arrays at the end of structs in
13496             // other structs as an extension.
13497             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13498               << FD->getDeclName();
13499           }
13500         }
13501       }
13502       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13503           RequireNonAbstractType(FD->getLocation(), FD->getType(),
13504                                  diag::err_abstract_type_in_decl,
13505                                  AbstractIvarType)) {
13506         // Ivars can not have abstract class types
13507         FD->setInvalidDecl();
13508       }
13509       if (Record && FDTTy->getDecl()->hasObjectMember())
13510         Record->setHasObjectMember(true);
13511       if (Record && FDTTy->getDecl()->hasVolatileMember())
13512         Record->setHasVolatileMember(true);
13513     } else if (FDTy->isObjCObjectType()) {
13514       /// A field cannot be an Objective-c object
13515       Diag(FD->getLocation(), diag::err_statically_allocated_object)
13516         << FixItHint::CreateInsertion(FD->getLocation(), "*");
13517       QualType T = Context.getObjCObjectPointerType(FD->getType());
13518       FD->setType(T);
13519     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13520                (!getLangOpts().CPlusPlus || Record->isUnion())) {
13521       // It's an error in ARC if a field has lifetime.
13522       // We don't want to report this in a system header, though,
13523       // so we just make the field unavailable.
13524       // FIXME: that's really not sufficient; we need to make the type
13525       // itself invalid to, say, initialize or copy.
13526       QualType T = FD->getType();
13527       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
13528       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13529         SourceLocation loc = FD->getLocation();
13530         if (getSourceManager().isInSystemHeader(loc)) {
13531           if (!FD->hasAttr<UnavailableAttr>()) {
13532             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13533                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
13534           }
13535         } else {
13536           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
13537             << T->isBlockPointerType() << Record->getTagKind();
13538         }
13539         ARCErrReported = true;
13540       }
13541     } else if (getLangOpts().ObjC1 &&
13542                getLangOpts().getGC() != LangOptions::NonGC &&
13543                Record && !Record->hasObjectMember()) {
13544       if (FD->getType()->isObjCObjectPointerType() ||
13545           FD->getType().isObjCGCStrong())
13546         Record->setHasObjectMember(true);
13547       else if (Context.getAsArrayType(FD->getType())) {
13548         QualType BaseType = Context.getBaseElementType(FD->getType());
13549         if (BaseType->isRecordType() &&
13550             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
13551           Record->setHasObjectMember(true);
13552         else if (BaseType->isObjCObjectPointerType() ||
13553                  BaseType.isObjCGCStrong())
13554                Record->setHasObjectMember(true);
13555       }
13556     }
13557     if (Record && FD->getType().isVolatileQualified())
13558       Record->setHasVolatileMember(true);
13559     // Keep track of the number of named members.
13560     if (FD->getIdentifier())
13561       ++NumNamedMembers;
13562   }
13563 
13564   // Okay, we successfully defined 'Record'.
13565   if (Record) {
13566     bool Completed = false;
13567     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
13568       if (!CXXRecord->isInvalidDecl()) {
13569         // Set access bits correctly on the directly-declared conversions.
13570         for (CXXRecordDecl::conversion_iterator
13571                I = CXXRecord->conversion_begin(),
13572                E = CXXRecord->conversion_end(); I != E; ++I)
13573           I.setAccess((*I)->getAccess());
13574 
13575         if (!CXXRecord->isDependentType()) {
13576           if (CXXRecord->hasUserDeclaredDestructor()) {
13577             // Adjust user-defined destructor exception spec.
13578             if (getLangOpts().CPlusPlus11)
13579               AdjustDestructorExceptionSpec(CXXRecord,
13580                                             CXXRecord->getDestructor());
13581           }
13582 
13583           // Add any implicitly-declared members to this class.
13584           AddImplicitlyDeclaredMembersToClass(CXXRecord);
13585 
13586           // If we have virtual base classes, we may end up finding multiple
13587           // final overriders for a given virtual function. Check for this
13588           // problem now.
13589           if (CXXRecord->getNumVBases()) {
13590             CXXFinalOverriderMap FinalOverriders;
13591             CXXRecord->getFinalOverriders(FinalOverriders);
13592 
13593             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
13594                                              MEnd = FinalOverriders.end();
13595                  M != MEnd; ++M) {
13596               for (OverridingMethods::iterator SO = M->second.begin(),
13597                                             SOEnd = M->second.end();
13598                    SO != SOEnd; ++SO) {
13599                 assert(SO->second.size() > 0 &&
13600                        "Virtual function without overridding functions?");
13601                 if (SO->second.size() == 1)
13602                   continue;
13603 
13604                 // C++ [class.virtual]p2:
13605                 //   In a derived class, if a virtual member function of a base
13606                 //   class subobject has more than one final overrider the
13607                 //   program is ill-formed.
13608                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
13609                   << (const NamedDecl *)M->first << Record;
13610                 Diag(M->first->getLocation(),
13611                      diag::note_overridden_virtual_function);
13612                 for (OverridingMethods::overriding_iterator
13613                           OM = SO->second.begin(),
13614                        OMEnd = SO->second.end();
13615                      OM != OMEnd; ++OM)
13616                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
13617                     << (const NamedDecl *)M->first << OM->Method->getParent();
13618 
13619                 Record->setInvalidDecl();
13620               }
13621             }
13622             CXXRecord->completeDefinition(&FinalOverriders);
13623             Completed = true;
13624           }
13625         }
13626       }
13627     }
13628 
13629     if (!Completed)
13630       Record->completeDefinition();
13631 
13632     if (Record->hasAttrs()) {
13633       CheckAlignasUnderalignment(Record);
13634 
13635       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
13636         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
13637                                            IA->getRange(), IA->getBestCase(),
13638                                            IA->getSemanticSpelling());
13639     }
13640 
13641     // Check if the structure/union declaration is a type that can have zero
13642     // size in C. For C this is a language extension, for C++ it may cause
13643     // compatibility problems.
13644     bool CheckForZeroSize;
13645     if (!getLangOpts().CPlusPlus) {
13646       CheckForZeroSize = true;
13647     } else {
13648       // For C++ filter out types that cannot be referenced in C code.
13649       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
13650       CheckForZeroSize =
13651           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
13652           !CXXRecord->isDependentType() &&
13653           CXXRecord->isCLike();
13654     }
13655     if (CheckForZeroSize) {
13656       bool ZeroSize = true;
13657       bool IsEmpty = true;
13658       unsigned NonBitFields = 0;
13659       for (RecordDecl::field_iterator I = Record->field_begin(),
13660                                       E = Record->field_end();
13661            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
13662         IsEmpty = false;
13663         if (I->isUnnamedBitfield()) {
13664           if (I->getBitWidthValue(Context) > 0)
13665             ZeroSize = false;
13666         } else {
13667           ++NonBitFields;
13668           QualType FieldType = I->getType();
13669           if (FieldType->isIncompleteType() ||
13670               !Context.getTypeSizeInChars(FieldType).isZero())
13671             ZeroSize = false;
13672         }
13673       }
13674 
13675       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
13676       // allowed in C++, but warn if its declaration is inside
13677       // extern "C" block.
13678       if (ZeroSize) {
13679         Diag(RecLoc, getLangOpts().CPlusPlus ?
13680                          diag::warn_zero_size_struct_union_in_extern_c :
13681                          diag::warn_zero_size_struct_union_compat)
13682           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
13683       }
13684 
13685       // Structs without named members are extension in C (C99 6.7.2.1p7),
13686       // but are accepted by GCC.
13687       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
13688         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
13689                                diag::ext_no_named_members_in_struct_union)
13690           << Record->isUnion();
13691       }
13692     }
13693   } else {
13694     ObjCIvarDecl **ClsFields =
13695       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
13696     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
13697       ID->setEndOfDefinitionLoc(RBrac);
13698       // Add ivar's to class's DeclContext.
13699       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13700         ClsFields[i]->setLexicalDeclContext(ID);
13701         ID->addDecl(ClsFields[i]);
13702       }
13703       // Must enforce the rule that ivars in the base classes may not be
13704       // duplicates.
13705       if (ID->getSuperClass())
13706         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
13707     } else if (ObjCImplementationDecl *IMPDecl =
13708                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13709       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
13710       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
13711         // Ivar declared in @implementation never belongs to the implementation.
13712         // Only it is in implementation's lexical context.
13713         ClsFields[I]->setLexicalDeclContext(IMPDecl);
13714       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
13715       IMPDecl->setIvarLBraceLoc(LBrac);
13716       IMPDecl->setIvarRBraceLoc(RBrac);
13717     } else if (ObjCCategoryDecl *CDecl =
13718                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13719       // case of ivars in class extension; all other cases have been
13720       // reported as errors elsewhere.
13721       // FIXME. Class extension does not have a LocEnd field.
13722       // CDecl->setLocEnd(RBrac);
13723       // Add ivar's to class extension's DeclContext.
13724       // Diagnose redeclaration of private ivars.
13725       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
13726       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13727         if (IDecl) {
13728           if (const ObjCIvarDecl *ClsIvar =
13729               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
13730             Diag(ClsFields[i]->getLocation(),
13731                  diag::err_duplicate_ivar_declaration);
13732             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
13733             continue;
13734           }
13735           for (const auto *Ext : IDecl->known_extensions()) {
13736             if (const ObjCIvarDecl *ClsExtIvar
13737                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
13738               Diag(ClsFields[i]->getLocation(),
13739                    diag::err_duplicate_ivar_declaration);
13740               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
13741               continue;
13742             }
13743           }
13744         }
13745         ClsFields[i]->setLexicalDeclContext(CDecl);
13746         CDecl->addDecl(ClsFields[i]);
13747       }
13748       CDecl->setIvarLBraceLoc(LBrac);
13749       CDecl->setIvarRBraceLoc(RBrac);
13750     }
13751   }
13752 
13753   if (Attr)
13754     ProcessDeclAttributeList(S, Record, Attr);
13755 }
13756 
13757 /// \brief Determine whether the given integral value is representable within
13758 /// the given type T.
13759 static bool isRepresentableIntegerValue(ASTContext &Context,
13760                                         llvm::APSInt &Value,
13761                                         QualType T) {
13762   assert(T->isIntegralType(Context) && "Integral type required!");
13763   unsigned BitWidth = Context.getIntWidth(T);
13764 
13765   if (Value.isUnsigned() || Value.isNonNegative()) {
13766     if (T->isSignedIntegerOrEnumerationType())
13767       --BitWidth;
13768     return Value.getActiveBits() <= BitWidth;
13769   }
13770   return Value.getMinSignedBits() <= BitWidth;
13771 }
13772 
13773 // \brief Given an integral type, return the next larger integral type
13774 // (or a NULL type of no such type exists).
13775 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
13776   // FIXME: Int128/UInt128 support, which also needs to be introduced into
13777   // enum checking below.
13778   assert(T->isIntegralType(Context) && "Integral type required!");
13779   const unsigned NumTypes = 4;
13780   QualType SignedIntegralTypes[NumTypes] = {
13781     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
13782   };
13783   QualType UnsignedIntegralTypes[NumTypes] = {
13784     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
13785     Context.UnsignedLongLongTy
13786   };
13787 
13788   unsigned BitWidth = Context.getTypeSize(T);
13789   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
13790                                                         : UnsignedIntegralTypes;
13791   for (unsigned I = 0; I != NumTypes; ++I)
13792     if (Context.getTypeSize(Types[I]) > BitWidth)
13793       return Types[I];
13794 
13795   return QualType();
13796 }
13797 
13798 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
13799                                           EnumConstantDecl *LastEnumConst,
13800                                           SourceLocation IdLoc,
13801                                           IdentifierInfo *Id,
13802                                           Expr *Val) {
13803   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13804   llvm::APSInt EnumVal(IntWidth);
13805   QualType EltTy;
13806 
13807   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
13808     Val = nullptr;
13809 
13810   if (Val)
13811     Val = DefaultLvalueConversion(Val).get();
13812 
13813   if (Val) {
13814     if (Enum->isDependentType() || Val->isTypeDependent())
13815       EltTy = Context.DependentTy;
13816     else {
13817       SourceLocation ExpLoc;
13818       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
13819           !getLangOpts().MSVCCompat) {
13820         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
13821         // constant-expression in the enumerator-definition shall be a converted
13822         // constant expression of the underlying type.
13823         EltTy = Enum->getIntegerType();
13824         ExprResult Converted =
13825           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
13826                                            CCEK_Enumerator);
13827         if (Converted.isInvalid())
13828           Val = nullptr;
13829         else
13830           Val = Converted.get();
13831       } else if (!Val->isValueDependent() &&
13832                  !(Val = VerifyIntegerConstantExpression(Val,
13833                                                          &EnumVal).get())) {
13834         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
13835       } else {
13836         if (Enum->isFixed()) {
13837           EltTy = Enum->getIntegerType();
13838 
13839           // In Obj-C and Microsoft mode, require the enumeration value to be
13840           // representable in the underlying type of the enumeration. In C++11,
13841           // we perform a non-narrowing conversion as part of converted constant
13842           // expression checking.
13843           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13844             if (getLangOpts().MSVCCompat) {
13845               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
13846               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13847             } else
13848               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
13849           } else
13850             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13851         } else if (getLangOpts().CPlusPlus) {
13852           // C++11 [dcl.enum]p5:
13853           //   If the underlying type is not fixed, the type of each enumerator
13854           //   is the type of its initializing value:
13855           //     - If an initializer is specified for an enumerator, the
13856           //       initializing value has the same type as the expression.
13857           EltTy = Val->getType();
13858         } else {
13859           // C99 6.7.2.2p2:
13860           //   The expression that defines the value of an enumeration constant
13861           //   shall be an integer constant expression that has a value
13862           //   representable as an int.
13863 
13864           // Complain if the value is not representable in an int.
13865           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
13866             Diag(IdLoc, diag::ext_enum_value_not_int)
13867               << EnumVal.toString(10) << Val->getSourceRange()
13868               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13869           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13870             // Force the type of the expression to 'int'.
13871             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
13872           }
13873           EltTy = Val->getType();
13874         }
13875       }
13876     }
13877   }
13878 
13879   if (!Val) {
13880     if (Enum->isDependentType())
13881       EltTy = Context.DependentTy;
13882     else if (!LastEnumConst) {
13883       // C++0x [dcl.enum]p5:
13884       //   If the underlying type is not fixed, the type of each enumerator
13885       //   is the type of its initializing value:
13886       //     - If no initializer is specified for the first enumerator, the
13887       //       initializing value has an unspecified integral type.
13888       //
13889       // GCC uses 'int' for its unspecified integral type, as does
13890       // C99 6.7.2.2p3.
13891       if (Enum->isFixed()) {
13892         EltTy = Enum->getIntegerType();
13893       }
13894       else {
13895         EltTy = Context.IntTy;
13896       }
13897     } else {
13898       // Assign the last value + 1.
13899       EnumVal = LastEnumConst->getInitVal();
13900       ++EnumVal;
13901       EltTy = LastEnumConst->getType();
13902 
13903       // Check for overflow on increment.
13904       if (EnumVal < LastEnumConst->getInitVal()) {
13905         // C++0x [dcl.enum]p5:
13906         //   If the underlying type is not fixed, the type of each enumerator
13907         //   is the type of its initializing value:
13908         //
13909         //     - Otherwise the type of the initializing value is the same as
13910         //       the type of the initializing value of the preceding enumerator
13911         //       unless the incremented value is not representable in that type,
13912         //       in which case the type is an unspecified integral type
13913         //       sufficient to contain the incremented value. If no such type
13914         //       exists, the program is ill-formed.
13915         QualType T = getNextLargerIntegralType(Context, EltTy);
13916         if (T.isNull() || Enum->isFixed()) {
13917           // There is no integral type larger enough to represent this
13918           // value. Complain, then allow the value to wrap around.
13919           EnumVal = LastEnumConst->getInitVal();
13920           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
13921           ++EnumVal;
13922           if (Enum->isFixed())
13923             // When the underlying type is fixed, this is ill-formed.
13924             Diag(IdLoc, diag::err_enumerator_wrapped)
13925               << EnumVal.toString(10)
13926               << EltTy;
13927           else
13928             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
13929               << EnumVal.toString(10);
13930         } else {
13931           EltTy = T;
13932         }
13933 
13934         // Retrieve the last enumerator's value, extent that type to the
13935         // type that is supposed to be large enough to represent the incremented
13936         // value, then increment.
13937         EnumVal = LastEnumConst->getInitVal();
13938         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13939         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
13940         ++EnumVal;
13941 
13942         // If we're not in C++, diagnose the overflow of enumerator values,
13943         // which in C99 means that the enumerator value is not representable in
13944         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
13945         // permits enumerator values that are representable in some larger
13946         // integral type.
13947         if (!getLangOpts().CPlusPlus && !T.isNull())
13948           Diag(IdLoc, diag::warn_enum_value_overflow);
13949       } else if (!getLangOpts().CPlusPlus &&
13950                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13951         // Enforce C99 6.7.2.2p2 even when we compute the next value.
13952         Diag(IdLoc, diag::ext_enum_value_not_int)
13953           << EnumVal.toString(10) << 1;
13954       }
13955     }
13956   }
13957 
13958   if (!EltTy->isDependentType()) {
13959     // Make the enumerator value match the signedness and size of the
13960     // enumerator's type.
13961     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
13962     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13963   }
13964 
13965   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
13966                                   Val, EnumVal);
13967 }
13968 
13969 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
13970                                                 SourceLocation IILoc) {
13971   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
13972       !getLangOpts().CPlusPlus)
13973     return SkipBodyInfo();
13974 
13975   // We have an anonymous enum definition. Look up the first enumerator to
13976   // determine if we should merge the definition with an existing one and
13977   // skip the body.
13978   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
13979                                          ForRedeclaration);
13980   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
13981   if (!PrevECD)
13982     return SkipBodyInfo();
13983 
13984   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
13985   NamedDecl *Hidden;
13986   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
13987     SkipBodyInfo Skip;
13988     Skip.Previous = Hidden;
13989     return Skip;
13990   }
13991 
13992   return SkipBodyInfo();
13993 }
13994 
13995 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
13996                               SourceLocation IdLoc, IdentifierInfo *Id,
13997                               AttributeList *Attr,
13998                               SourceLocation EqualLoc, Expr *Val) {
13999   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14000   EnumConstantDecl *LastEnumConst =
14001     cast_or_null<EnumConstantDecl>(lastEnumConst);
14002 
14003   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14004   // we find one that is.
14005   S = getNonFieldDeclScope(S);
14006 
14007   // Verify that there isn't already something declared with this name in this
14008   // scope.
14009   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14010                                          ForRedeclaration);
14011   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14012     // Maybe we will complain about the shadowed template parameter.
14013     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14014     // Just pretend that we didn't see the previous declaration.
14015     PrevDecl = nullptr;
14016   }
14017 
14018   // C++ [class.mem]p15:
14019   // If T is the name of a class, then each of the following shall have a name
14020   // different from T:
14021   // - every enumerator of every member of class T that is an unscoped
14022   // enumerated type
14023   if (!TheEnumDecl->isScoped())
14024     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14025                             DeclarationNameInfo(Id, IdLoc));
14026 
14027   EnumConstantDecl *New =
14028     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14029   if (!New)
14030     return nullptr;
14031 
14032   if (PrevDecl) {
14033     // When in C++, we may get a TagDecl with the same name; in this case the
14034     // enum constant will 'hide' the tag.
14035     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14036            "Received TagDecl when not in C++!");
14037     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14038         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14039       if (isa<EnumConstantDecl>(PrevDecl))
14040         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14041       else
14042         Diag(IdLoc, diag::err_redefinition) << Id;
14043       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14044       return nullptr;
14045     }
14046   }
14047 
14048   // Process attributes.
14049   if (Attr) ProcessDeclAttributeList(S, New, Attr);
14050 
14051   // Register this decl in the current scope stack.
14052   New->setAccess(TheEnumDecl->getAccess());
14053   PushOnScopeChains(New, S);
14054 
14055   ActOnDocumentableDecl(New);
14056 
14057   return New;
14058 }
14059 
14060 // Returns true when the enum initial expression does not trigger the
14061 // duplicate enum warning.  A few common cases are exempted as follows:
14062 // Element2 = Element1
14063 // Element2 = Element1 + 1
14064 // Element2 = Element1 - 1
14065 // Where Element2 and Element1 are from the same enum.
14066 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14067   Expr *InitExpr = ECD->getInitExpr();
14068   if (!InitExpr)
14069     return true;
14070   InitExpr = InitExpr->IgnoreImpCasts();
14071 
14072   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14073     if (!BO->isAdditiveOp())
14074       return true;
14075     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14076     if (!IL)
14077       return true;
14078     if (IL->getValue() != 1)
14079       return true;
14080 
14081     InitExpr = BO->getLHS();
14082   }
14083 
14084   // This checks if the elements are from the same enum.
14085   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14086   if (!DRE)
14087     return true;
14088 
14089   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14090   if (!EnumConstant)
14091     return true;
14092 
14093   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14094       Enum)
14095     return true;
14096 
14097   return false;
14098 }
14099 
14100 namespace {
14101 struct DupKey {
14102   int64_t val;
14103   bool isTombstoneOrEmptyKey;
14104   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14105     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14106 };
14107 
14108 static DupKey GetDupKey(const llvm::APSInt& Val) {
14109   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14110                 false);
14111 }
14112 
14113 struct DenseMapInfoDupKey {
14114   static DupKey getEmptyKey() { return DupKey(0, true); }
14115   static DupKey getTombstoneKey() { return DupKey(1, true); }
14116   static unsigned getHashValue(const DupKey Key) {
14117     return (unsigned)(Key.val * 37);
14118   }
14119   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14120     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14121            LHS.val == RHS.val;
14122   }
14123 };
14124 } // end anonymous namespace
14125 
14126 // Emits a warning when an element is implicitly set a value that
14127 // a previous element has already been set to.
14128 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14129                                         EnumDecl *Enum,
14130                                         QualType EnumType) {
14131   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14132     return;
14133   // Avoid anonymous enums
14134   if (!Enum->getIdentifier())
14135     return;
14136 
14137   // Only check for small enums.
14138   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14139     return;
14140 
14141   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14142   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14143 
14144   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14145   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14146           ValueToVectorMap;
14147 
14148   DuplicatesVector DupVector;
14149   ValueToVectorMap EnumMap;
14150 
14151   // Populate the EnumMap with all values represented by enum constants without
14152   // an initialier.
14153   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14154     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14155 
14156     // Null EnumConstantDecl means a previous diagnostic has been emitted for
14157     // this constant.  Skip this enum since it may be ill-formed.
14158     if (!ECD) {
14159       return;
14160     }
14161 
14162     if (ECD->getInitExpr())
14163       continue;
14164 
14165     DupKey Key = GetDupKey(ECD->getInitVal());
14166     DeclOrVector &Entry = EnumMap[Key];
14167 
14168     // First time encountering this value.
14169     if (Entry.isNull())
14170       Entry = ECD;
14171   }
14172 
14173   // Create vectors for any values that has duplicates.
14174   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14175     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14176     if (!ValidDuplicateEnum(ECD, Enum))
14177       continue;
14178 
14179     DupKey Key = GetDupKey(ECD->getInitVal());
14180 
14181     DeclOrVector& Entry = EnumMap[Key];
14182     if (Entry.isNull())
14183       continue;
14184 
14185     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14186       // Ensure constants are different.
14187       if (D == ECD)
14188         continue;
14189 
14190       // Create new vector and push values onto it.
14191       ECDVector *Vec = new ECDVector();
14192       Vec->push_back(D);
14193       Vec->push_back(ECD);
14194 
14195       // Update entry to point to the duplicates vector.
14196       Entry = Vec;
14197 
14198       // Store the vector somewhere we can consult later for quick emission of
14199       // diagnostics.
14200       DupVector.push_back(Vec);
14201       continue;
14202     }
14203 
14204     ECDVector *Vec = Entry.get<ECDVector*>();
14205     // Make sure constants are not added more than once.
14206     if (*Vec->begin() == ECD)
14207       continue;
14208 
14209     Vec->push_back(ECD);
14210   }
14211 
14212   // Emit diagnostics.
14213   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14214                                   DupVectorEnd = DupVector.end();
14215        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14216     ECDVector *Vec = *DupVectorIter;
14217     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14218 
14219     // Emit warning for one enum constant.
14220     ECDVector::iterator I = Vec->begin();
14221     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14222       << (*I)->getName() << (*I)->getInitVal().toString(10)
14223       << (*I)->getSourceRange();
14224     ++I;
14225 
14226     // Emit one note for each of the remaining enum constants with
14227     // the same value.
14228     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14229       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14230         << (*I)->getName() << (*I)->getInitVal().toString(10)
14231         << (*I)->getSourceRange();
14232     delete Vec;
14233   }
14234 }
14235 
14236 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14237                              bool AllowMask) const {
14238   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14239   assert(ED->isCompleteDefinition() && "expected enum definition");
14240 
14241   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14242   llvm::APInt &FlagBits = R.first->second;
14243 
14244   if (R.second) {
14245     for (auto *E : ED->enumerators()) {
14246       const auto &EVal = E->getInitVal();
14247       // Only single-bit enumerators introduce new flag values.
14248       if (EVal.isPowerOf2())
14249         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14250     }
14251   }
14252 
14253   // A value is in a flag enum if either its bits are a subset of the enum's
14254   // flag bits (the first condition) or we are allowing masks and the same is
14255   // true of its complement (the second condition). When masks are allowed, we
14256   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14257   //
14258   // While it's true that any value could be used as a mask, the assumption is
14259   // that a mask will have all of the insignificant bits set. Anything else is
14260   // likely a logic error.
14261   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14262   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14263 }
14264 
14265 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14266                          SourceLocation RBraceLoc, Decl *EnumDeclX,
14267                          ArrayRef<Decl *> Elements,
14268                          Scope *S, AttributeList *Attr) {
14269   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14270   QualType EnumType = Context.getTypeDeclType(Enum);
14271 
14272   if (Attr)
14273     ProcessDeclAttributeList(S, Enum, Attr);
14274 
14275   if (Enum->isDependentType()) {
14276     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14277       EnumConstantDecl *ECD =
14278         cast_or_null<EnumConstantDecl>(Elements[i]);
14279       if (!ECD) continue;
14280 
14281       ECD->setType(EnumType);
14282     }
14283 
14284     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14285     return;
14286   }
14287 
14288   // TODO: If the result value doesn't fit in an int, it must be a long or long
14289   // long value.  ISO C does not support this, but GCC does as an extension,
14290   // emit a warning.
14291   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14292   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14293   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14294 
14295   // Verify that all the values are okay, compute the size of the values, and
14296   // reverse the list.
14297   unsigned NumNegativeBits = 0;
14298   unsigned NumPositiveBits = 0;
14299 
14300   // Keep track of whether all elements have type int.
14301   bool AllElementsInt = true;
14302 
14303   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14304     EnumConstantDecl *ECD =
14305       cast_or_null<EnumConstantDecl>(Elements[i]);
14306     if (!ECD) continue;  // Already issued a diagnostic.
14307 
14308     const llvm::APSInt &InitVal = ECD->getInitVal();
14309 
14310     // Keep track of the size of positive and negative values.
14311     if (InitVal.isUnsigned() || InitVal.isNonNegative())
14312       NumPositiveBits = std::max(NumPositiveBits,
14313                                  (unsigned)InitVal.getActiveBits());
14314     else
14315       NumNegativeBits = std::max(NumNegativeBits,
14316                                  (unsigned)InitVal.getMinSignedBits());
14317 
14318     // Keep track of whether every enum element has type int (very commmon).
14319     if (AllElementsInt)
14320       AllElementsInt = ECD->getType() == Context.IntTy;
14321   }
14322 
14323   // Figure out the type that should be used for this enum.
14324   QualType BestType;
14325   unsigned BestWidth;
14326 
14327   // C++0x N3000 [conv.prom]p3:
14328   //   An rvalue of an unscoped enumeration type whose underlying
14329   //   type is not fixed can be converted to an rvalue of the first
14330   //   of the following types that can represent all the values of
14331   //   the enumeration: int, unsigned int, long int, unsigned long
14332   //   int, long long int, or unsigned long long int.
14333   // C99 6.4.4.3p2:
14334   //   An identifier declared as an enumeration constant has type int.
14335   // The C99 rule is modified by a gcc extension
14336   QualType BestPromotionType;
14337 
14338   bool Packed = Enum->hasAttr<PackedAttr>();
14339   // -fshort-enums is the equivalent to specifying the packed attribute on all
14340   // enum definitions.
14341   if (LangOpts.ShortEnums)
14342     Packed = true;
14343 
14344   if (Enum->isFixed()) {
14345     BestType = Enum->getIntegerType();
14346     if (BestType->isPromotableIntegerType())
14347       BestPromotionType = Context.getPromotedIntegerType(BestType);
14348     else
14349       BestPromotionType = BestType;
14350 
14351     BestWidth = Context.getIntWidth(BestType);
14352   }
14353   else if (NumNegativeBits) {
14354     // If there is a negative value, figure out the smallest integer type (of
14355     // int/long/longlong) that fits.
14356     // If it's packed, check also if it fits a char or a short.
14357     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14358       BestType = Context.SignedCharTy;
14359       BestWidth = CharWidth;
14360     } else if (Packed && NumNegativeBits <= ShortWidth &&
14361                NumPositiveBits < ShortWidth) {
14362       BestType = Context.ShortTy;
14363       BestWidth = ShortWidth;
14364     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14365       BestType = Context.IntTy;
14366       BestWidth = IntWidth;
14367     } else {
14368       BestWidth = Context.getTargetInfo().getLongWidth();
14369 
14370       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14371         BestType = Context.LongTy;
14372       } else {
14373         BestWidth = Context.getTargetInfo().getLongLongWidth();
14374 
14375         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14376           Diag(Enum->getLocation(), diag::ext_enum_too_large);
14377         BestType = Context.LongLongTy;
14378       }
14379     }
14380     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14381   } else {
14382     // If there is no negative value, figure out the smallest type that fits
14383     // all of the enumerator values.
14384     // If it's packed, check also if it fits a char or a short.
14385     if (Packed && NumPositiveBits <= CharWidth) {
14386       BestType = Context.UnsignedCharTy;
14387       BestPromotionType = Context.IntTy;
14388       BestWidth = CharWidth;
14389     } else if (Packed && NumPositiveBits <= ShortWidth) {
14390       BestType = Context.UnsignedShortTy;
14391       BestPromotionType = Context.IntTy;
14392       BestWidth = ShortWidth;
14393     } else if (NumPositiveBits <= IntWidth) {
14394       BestType = Context.UnsignedIntTy;
14395       BestWidth = IntWidth;
14396       BestPromotionType
14397         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14398                            ? Context.UnsignedIntTy : Context.IntTy;
14399     } else if (NumPositiveBits <=
14400                (BestWidth = Context.getTargetInfo().getLongWidth())) {
14401       BestType = Context.UnsignedLongTy;
14402       BestPromotionType
14403         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14404                            ? Context.UnsignedLongTy : Context.LongTy;
14405     } else {
14406       BestWidth = Context.getTargetInfo().getLongLongWidth();
14407       assert(NumPositiveBits <= BestWidth &&
14408              "How could an initializer get larger than ULL?");
14409       BestType = Context.UnsignedLongLongTy;
14410       BestPromotionType
14411         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14412                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
14413     }
14414   }
14415 
14416   // Loop over all of the enumerator constants, changing their types to match
14417   // the type of the enum if needed.
14418   for (auto *D : Elements) {
14419     auto *ECD = cast_or_null<EnumConstantDecl>(D);
14420     if (!ECD) continue;  // Already issued a diagnostic.
14421 
14422     // Standard C says the enumerators have int type, but we allow, as an
14423     // extension, the enumerators to be larger than int size.  If each
14424     // enumerator value fits in an int, type it as an int, otherwise type it the
14425     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
14426     // that X has type 'int', not 'unsigned'.
14427 
14428     // Determine whether the value fits into an int.
14429     llvm::APSInt InitVal = ECD->getInitVal();
14430 
14431     // If it fits into an integer type, force it.  Otherwise force it to match
14432     // the enum decl type.
14433     QualType NewTy;
14434     unsigned NewWidth;
14435     bool NewSign;
14436     if (!getLangOpts().CPlusPlus &&
14437         !Enum->isFixed() &&
14438         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14439       NewTy = Context.IntTy;
14440       NewWidth = IntWidth;
14441       NewSign = true;
14442     } else if (ECD->getType() == BestType) {
14443       // Already the right type!
14444       if (getLangOpts().CPlusPlus)
14445         // C++ [dcl.enum]p4: Following the closing brace of an
14446         // enum-specifier, each enumerator has the type of its
14447         // enumeration.
14448         ECD->setType(EnumType);
14449       continue;
14450     } else {
14451       NewTy = BestType;
14452       NewWidth = BestWidth;
14453       NewSign = BestType->isSignedIntegerOrEnumerationType();
14454     }
14455 
14456     // Adjust the APSInt value.
14457     InitVal = InitVal.extOrTrunc(NewWidth);
14458     InitVal.setIsSigned(NewSign);
14459     ECD->setInitVal(InitVal);
14460 
14461     // Adjust the Expr initializer and type.
14462     if (ECD->getInitExpr() &&
14463         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14464       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14465                                                 CK_IntegralCast,
14466                                                 ECD->getInitExpr(),
14467                                                 /*base paths*/ nullptr,
14468                                                 VK_RValue));
14469     if (getLangOpts().CPlusPlus)
14470       // C++ [dcl.enum]p4: Following the closing brace of an
14471       // enum-specifier, each enumerator has the type of its
14472       // enumeration.
14473       ECD->setType(EnumType);
14474     else
14475       ECD->setType(NewTy);
14476   }
14477 
14478   Enum->completeDefinition(BestType, BestPromotionType,
14479                            NumPositiveBits, NumNegativeBits);
14480 
14481   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14482 
14483   if (Enum->hasAttr<FlagEnumAttr>()) {
14484     for (Decl *D : Elements) {
14485       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14486       if (!ECD) continue;  // Already issued a diagnostic.
14487 
14488       llvm::APSInt InitVal = ECD->getInitVal();
14489       if (InitVal != 0 && !InitVal.isPowerOf2() &&
14490           !IsValueInFlagEnum(Enum, InitVal, true))
14491         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14492           << ECD << Enum;
14493     }
14494   }
14495 
14496   // Now that the enum type is defined, ensure it's not been underaligned.
14497   if (Enum->hasAttrs())
14498     CheckAlignasUnderalignment(Enum);
14499 }
14500 
14501 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
14502                                   SourceLocation StartLoc,
14503                                   SourceLocation EndLoc) {
14504   StringLiteral *AsmString = cast<StringLiteral>(expr);
14505 
14506   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
14507                                                    AsmString, StartLoc,
14508                                                    EndLoc);
14509   CurContext->addDecl(New);
14510   return New;
14511 }
14512 
14513 static void checkModuleImportContext(Sema &S, Module *M,
14514                                      SourceLocation ImportLoc, DeclContext *DC,
14515                                      bool FromInclude = false) {
14516   SourceLocation ExternCLoc;
14517 
14518   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14519     switch (LSD->getLanguage()) {
14520     case LinkageSpecDecl::lang_c:
14521       if (ExternCLoc.isInvalid())
14522         ExternCLoc = LSD->getLocStart();
14523       break;
14524     case LinkageSpecDecl::lang_cxx:
14525       break;
14526     }
14527     DC = LSD->getParent();
14528   }
14529 
14530   while (isa<LinkageSpecDecl>(DC))
14531     DC = DC->getParent();
14532 
14533   if (!isa<TranslationUnitDecl>(DC)) {
14534     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
14535                           ? diag::ext_module_import_not_at_top_level_noop
14536                           : diag::err_module_import_not_at_top_level_fatal)
14537         << M->getFullModuleName() << DC;
14538     S.Diag(cast<Decl>(DC)->getLocStart(),
14539            diag::note_module_import_not_at_top_level) << DC;
14540   } else if (!M->IsExternC && ExternCLoc.isValid()) {
14541     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
14542       << M->getFullModuleName();
14543     S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
14544   }
14545 }
14546 
14547 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
14548   return checkModuleImportContext(*this, M, ImportLoc, CurContext);
14549 }
14550 
14551 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
14552                                    SourceLocation ImportLoc,
14553                                    ModuleIdPath Path) {
14554   Module *Mod =
14555       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
14556                                    /*IsIncludeDirective=*/false);
14557   if (!Mod)
14558     return true;
14559 
14560   VisibleModules.setVisible(Mod, ImportLoc);
14561 
14562   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
14563 
14564   // FIXME: we should support importing a submodule within a different submodule
14565   // of the same top-level module. Until we do, make it an error rather than
14566   // silently ignoring the import.
14567   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
14568     Diag(ImportLoc, diag::err_module_self_import)
14569         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
14570   else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
14571     Diag(ImportLoc, diag::err_module_import_in_implementation)
14572         << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
14573 
14574   SmallVector<SourceLocation, 2> IdentifierLocs;
14575   Module *ModCheck = Mod;
14576   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
14577     // If we've run out of module parents, just drop the remaining identifiers.
14578     // We need the length to be consistent.
14579     if (!ModCheck)
14580       break;
14581     ModCheck = ModCheck->Parent;
14582 
14583     IdentifierLocs.push_back(Path[I].second);
14584   }
14585 
14586   ImportDecl *Import = ImportDecl::Create(Context,
14587                                           Context.getTranslationUnitDecl(),
14588                                           AtLoc.isValid()? AtLoc : ImportLoc,
14589                                           Mod, IdentifierLocs);
14590   Context.getTranslationUnitDecl()->addDecl(Import);
14591   return Import;
14592 }
14593 
14594 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
14595   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
14596 
14597   // Determine whether we're in the #include buffer for a module. The #includes
14598   // in that buffer do not qualify as module imports; they're just an
14599   // implementation detail of us building the module.
14600   //
14601   // FIXME: Should we even get ActOnModuleInclude calls for those?
14602   bool IsInModuleIncludes =
14603       TUKind == TU_Module &&
14604       getSourceManager().isWrittenInMainFile(DirectiveLoc);
14605 
14606   // If this module import was due to an inclusion directive, create an
14607   // implicit import declaration to capture it in the AST.
14608   if (!IsInModuleIncludes) {
14609     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14610     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14611                                                      DirectiveLoc, Mod,
14612                                                      DirectiveLoc);
14613     TU->addDecl(ImportD);
14614     Consumer.HandleImplicitImportDecl(ImportD);
14615   }
14616 
14617   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
14618   VisibleModules.setVisible(Mod, DirectiveLoc);
14619 }
14620 
14621 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
14622   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14623 
14624   if (getLangOpts().ModulesLocalVisibility)
14625     VisibleModulesStack.push_back(std::move(VisibleModules));
14626   VisibleModules.setVisible(Mod, DirectiveLoc);
14627 }
14628 
14629 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
14630   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14631 
14632   if (getLangOpts().ModulesLocalVisibility) {
14633     VisibleModules = std::move(VisibleModulesStack.back());
14634     VisibleModulesStack.pop_back();
14635     VisibleModules.setVisible(Mod, DirectiveLoc);
14636   }
14637 }
14638 
14639 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
14640                                                       Module *Mod) {
14641   // Bail if we're not allowed to implicitly import a module here.
14642   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
14643     return;
14644 
14645   // Create the implicit import declaration.
14646   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14647   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14648                                                    Loc, Mod, Loc);
14649   TU->addDecl(ImportD);
14650   Consumer.HandleImplicitImportDecl(ImportD);
14651 
14652   // Make the module visible.
14653   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
14654   VisibleModules.setVisible(Mod, Loc);
14655 }
14656 
14657 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
14658                                       IdentifierInfo* AliasName,
14659                                       SourceLocation PragmaLoc,
14660                                       SourceLocation NameLoc,
14661                                       SourceLocation AliasNameLoc) {
14662   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
14663                                          LookupOrdinaryName);
14664   AsmLabelAttr *Attr =
14665       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
14666 
14667   // If a declaration that:
14668   // 1) declares a function or a variable
14669   // 2) has external linkage
14670   // already exists, add a label attribute to it.
14671   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
14672     if (isDeclExternC(PrevDecl))
14673       PrevDecl->addAttr(Attr);
14674     else
14675       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
14676           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
14677   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
14678   } else
14679     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
14680 }
14681 
14682 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
14683                              SourceLocation PragmaLoc,
14684                              SourceLocation NameLoc) {
14685   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
14686 
14687   if (PrevDecl) {
14688     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
14689   } else {
14690     (void)WeakUndeclaredIdentifiers.insert(
14691       std::pair<IdentifierInfo*,WeakInfo>
14692         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
14693   }
14694 }
14695 
14696 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
14697                                 IdentifierInfo* AliasName,
14698                                 SourceLocation PragmaLoc,
14699                                 SourceLocation NameLoc,
14700                                 SourceLocation AliasNameLoc) {
14701   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
14702                                     LookupOrdinaryName);
14703   WeakInfo W = WeakInfo(Name, NameLoc);
14704 
14705   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
14706     if (!PrevDecl->hasAttr<AliasAttr>())
14707       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
14708         DeclApplyPragmaWeak(TUScope, ND, W);
14709   } else {
14710     (void)WeakUndeclaredIdentifiers.insert(
14711       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
14712   }
14713 }
14714 
14715 Decl *Sema::getObjCDeclContext() const {
14716   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
14717 }
14718 
14719 AvailabilityResult Sema::getCurContextAvailability() const {
14720   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
14721   if (!D)
14722     return AR_Available;
14723 
14724   // If we are within an Objective-C method, we should consult
14725   // both the availability of the method as well as the
14726   // enclosing class.  If the class is (say) deprecated,
14727   // the entire method is considered deprecated from the
14728   // purpose of checking if the current context is deprecated.
14729   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
14730     AvailabilityResult R = MD->getAvailability();
14731     if (R != AR_Available)
14732       return R;
14733     D = MD->getClassInterface();
14734   }
14735   // If we are within an Objective-c @implementation, it
14736   // gets the same availability context as the @interface.
14737   else if (const ObjCImplementationDecl *ID =
14738             dyn_cast<ObjCImplementationDecl>(D)) {
14739     D = ID->getClassInterface();
14740   }
14741   // Recover from user error.
14742   return D ? D->getAvailability() : AR_Available;
14743 }
14744