]> granicus.if.org Git - clang/blob - lib/Sema/SemaDecl.cpp
[CUDA] Only __shared__ variables can be static local on device side.
[clang] / lib / Sema / SemaDecl.cpp
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50
51 using namespace clang;
52 using namespace sema;
53
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62
63 namespace {
64
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68                        bool AllowTemplates=false)
69       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70         AllowClassTemplates(AllowTemplates) {
71     WantExpressionKeywords = false;
72     WantCXXNamedCasts = false;
73     WantRemainingKeywords = false;
74   }
75
76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80       return (IsType || AllowedTemplate) &&
81              (AllowInvalidDecl || !ND->isInvalidDecl());
82     }
83     return !WantClassName && candidate.isKeyword();
84   }
85
86  private:
87   bool AllowInvalidDecl;
88   bool WantClassName;
89   bool AllowClassTemplates;
90 };
91
92 } // end anonymous namespace
93
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96   switch (Kind) {
97   // FIXME: Take into account the current language when deciding whether a
98   // token kind is a valid type specifier
99   case tok::kw_short:
100   case tok::kw_long:
101   case tok::kw___int64:
102   case tok::kw___int128:
103   case tok::kw_signed:
104   case tok::kw_unsigned:
105   case tok::kw_void:
106   case tok::kw_char:
107   case tok::kw_int:
108   case tok::kw_half:
109   case tok::kw_float:
110   case tok::kw_double:
111   case tok::kw___float128:
112   case tok::kw_wchar_t:
113   case tok::kw_bool:
114   case tok::kw___underlying_type:
115   case tok::kw___auto_type:
116     return true;
117
118   case tok::annot_typename:
119   case tok::kw_char16_t:
120   case tok::kw_char32_t:
121   case tok::kw_typeof:
122   case tok::annot_decltype:
123   case tok::kw_decltype:
124     return getLangOpts().CPlusPlus;
125
126   default:
127     break;
128   }
129
130   return false;
131 }
132
133 namespace {
134 enum class UnqualifiedTypeNameLookupResult {
135   NotFound,
136   FoundNonType,
137   FoundType
138 };
139 } // end anonymous namespace
140
141 /// \brief Tries to perform unqualified lookup of the type decls in bases for
142 /// dependent class.
143 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
144 /// type decl, \a FoundType if only type decls are found.
145 static UnqualifiedTypeNameLookupResult
146 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
147                                 SourceLocation NameLoc,
148                                 const CXXRecordDecl *RD) {
149   if (!RD->hasDefinition())
150     return UnqualifiedTypeNameLookupResult::NotFound;
151   // Look for type decls in base classes.
152   UnqualifiedTypeNameLookupResult FoundTypeDecl =
153       UnqualifiedTypeNameLookupResult::NotFound;
154   for (const auto &Base : RD->bases()) {
155     const CXXRecordDecl *BaseRD = nullptr;
156     if (auto *BaseTT = Base.getType()->getAs<TagType>())
157       BaseRD = BaseTT->getAsCXXRecordDecl();
158     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
159       // Look for type decls in dependent base classes that have known primary
160       // templates.
161       if (!TST || !TST->isDependentType())
162         continue;
163       auto *TD = TST->getTemplateName().getAsTemplateDecl();
164       if (!TD)
165         continue;
166       auto *BasePrimaryTemplate =
167           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
168       if (!BasePrimaryTemplate)
169         continue;
170       BaseRD = BasePrimaryTemplate;
171     }
172     if (BaseRD) {
173       for (NamedDecl *ND : BaseRD->lookup(&II)) {
174         if (!isa<TypeDecl>(ND))
175           return UnqualifiedTypeNameLookupResult::FoundNonType;
176         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
177       }
178       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
179         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
180         case UnqualifiedTypeNameLookupResult::FoundNonType:
181           return UnqualifiedTypeNameLookupResult::FoundNonType;
182         case UnqualifiedTypeNameLookupResult::FoundType:
183           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
184           break;
185         case UnqualifiedTypeNameLookupResult::NotFound:
186           break;
187         }
188       }
189     }
190   }
191
192   return FoundTypeDecl;
193 }
194
195 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
196                                                       const IdentifierInfo &II,
197                                                       SourceLocation NameLoc) {
198   // Lookup in the parent class template context, if any.
199   const CXXRecordDecl *RD = nullptr;
200   UnqualifiedTypeNameLookupResult FoundTypeDecl =
201       UnqualifiedTypeNameLookupResult::NotFound;
202   for (DeclContext *DC = S.CurContext;
203        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
204        DC = DC->getParent()) {
205     // Look for type decls in dependent base classes that have known primary
206     // templates.
207     RD = dyn_cast<CXXRecordDecl>(DC);
208     if (RD && RD->getDescribedClassTemplate())
209       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
210   }
211   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
212     return nullptr;
213
214   // We found some types in dependent base classes.  Recover as if the user
215   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
216   // lookup during template instantiation.
217   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
218
219   ASTContext &Context = S.Context;
220   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
221                                           cast<Type>(Context.getRecordType(RD)));
222   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
223
224   CXXScopeSpec SS;
225   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
226
227   TypeLocBuilder Builder;
228   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
229   DepTL.setNameLoc(NameLoc);
230   DepTL.setElaboratedKeywordLoc(SourceLocation());
231   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
232   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
233 }
234
235 /// \brief If the identifier refers to a type name within this scope,
236 /// return the declaration of that type.
237 ///
238 /// This routine performs ordinary name lookup of the identifier II
239 /// within the given scope, with optional C++ scope specifier SS, to
240 /// determine whether the name refers to a type. If so, returns an
241 /// opaque pointer (actually a QualType) corresponding to that
242 /// type. Otherwise, returns NULL.
243 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
244                              Scope *S, CXXScopeSpec *SS,
245                              bool isClassName, bool HasTrailingDot,
246                              ParsedType ObjectTypePtr,
247                              bool IsCtorOrDtorName,
248                              bool WantNontrivialTypeSourceInfo,
249                              IdentifierInfo **CorrectedII) {
250   // Determine where we will perform name lookup.
251   DeclContext *LookupCtx = nullptr;
252   if (ObjectTypePtr) {
253     QualType ObjectType = ObjectTypePtr.get();
254     if (ObjectType->isRecordType())
255       LookupCtx = computeDeclContext(ObjectType);
256   } else if (SS && SS->isNotEmpty()) {
257     LookupCtx = computeDeclContext(*SS, false);
258
259     if (!LookupCtx) {
260       if (isDependentScopeSpecifier(*SS)) {
261         // C++ [temp.res]p3:
262         //   A qualified-id that refers to a type and in which the
263         //   nested-name-specifier depends on a template-parameter (14.6.2)
264         //   shall be prefixed by the keyword typename to indicate that the
265         //   qualified-id denotes a type, forming an
266         //   elaborated-type-specifier (7.1.5.3).
267         //
268         // We therefore do not perform any name lookup if the result would
269         // refer to a member of an unknown specialization.
270         if (!isClassName && !IsCtorOrDtorName)
271           return nullptr;
272
273         // We know from the grammar that this name refers to a type,
274         // so build a dependent node to describe the type.
275         if (WantNontrivialTypeSourceInfo)
276           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
277
278         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
279         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
280                                        II, NameLoc);
281         return ParsedType::make(T);
282       }
283
284       return nullptr;
285     }
286
287     if (!LookupCtx->isDependentContext() &&
288         RequireCompleteDeclContext(*SS, LookupCtx))
289       return nullptr;
290   }
291
292   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
293   // lookup for class-names.
294   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
295                                       LookupOrdinaryName;
296   LookupResult Result(*this, &II, NameLoc, Kind);
297   if (LookupCtx) {
298     // Perform "qualified" name lookup into the declaration context we
299     // computed, which is either the type of the base of a member access
300     // expression or the declaration context associated with a prior
301     // nested-name-specifier.
302     LookupQualifiedName(Result, LookupCtx);
303
304     if (ObjectTypePtr && Result.empty()) {
305       // C++ [basic.lookup.classref]p3:
306       //   If the unqualified-id is ~type-name, the type-name is looked up
307       //   in the context of the entire postfix-expression. If the type T of
308       //   the object expression is of a class type C, the type-name is also
309       //   looked up in the scope of class C. At least one of the lookups shall
310       //   find a name that refers to (possibly cv-qualified) T.
311       LookupName(Result, S);
312     }
313   } else {
314     // Perform unqualified name lookup.
315     LookupName(Result, S);
316
317     // For unqualified lookup in a class template in MSVC mode, look into
318     // dependent base classes where the primary class template is known.
319     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
320       if (ParsedType TypeInBase =
321               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
322         return TypeInBase;
323     }
324   }
325
326   NamedDecl *IIDecl = nullptr;
327   switch (Result.getResultKind()) {
328   case LookupResult::NotFound:
329   case LookupResult::NotFoundInCurrentInstantiation:
330     if (CorrectedII) {
331       TypoCorrection Correction = CorrectTypo(
332           Result.getLookupNameInfo(), Kind, S, SS,
333           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
334           CTK_ErrorRecovery);
335       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
336       TemplateTy Template;
337       bool MemberOfUnknownSpecialization;
338       UnqualifiedId TemplateName;
339       TemplateName.setIdentifier(NewII, NameLoc);
340       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
341       CXXScopeSpec NewSS, *NewSSPtr = SS;
342       if (SS && NNS) {
343         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
344         NewSSPtr = &NewSS;
345       }
346       if (Correction && (NNS || NewII != &II) &&
347           // Ignore a correction to a template type as the to-be-corrected
348           // identifier is not a template (typo correction for template names
349           // is handled elsewhere).
350           !(getLangOpts().CPlusPlus && NewSSPtr &&
351             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
352                            Template, MemberOfUnknownSpecialization))) {
353         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
354                                     isClassName, HasTrailingDot, ObjectTypePtr,
355                                     IsCtorOrDtorName,
356                                     WantNontrivialTypeSourceInfo);
357         if (Ty) {
358           diagnoseTypo(Correction,
359                        PDiag(diag::err_unknown_type_or_class_name_suggest)
360                          << Result.getLookupName() << isClassName);
361           if (SS && NNS)
362             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
363           *CorrectedII = NewII;
364           return Ty;
365         }
366       }
367     }
368     // If typo correction failed or was not performed, fall through
369   case LookupResult::FoundOverloaded:
370   case LookupResult::FoundUnresolvedValue:
371     Result.suppressDiagnostics();
372     return nullptr;
373
374   case LookupResult::Ambiguous:
375     // Recover from type-hiding ambiguities by hiding the type.  We'll
376     // do the lookup again when looking for an object, and we can
377     // diagnose the error then.  If we don't do this, then the error
378     // about hiding the type will be immediately followed by an error
379     // that only makes sense if the identifier was treated like a type.
380     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
381       Result.suppressDiagnostics();
382       return nullptr;
383     }
384
385     // Look to see if we have a type anywhere in the list of results.
386     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
387          Res != ResEnd; ++Res) {
388       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
389         if (!IIDecl ||
390             (*Res)->getLocation().getRawEncoding() <
391               IIDecl->getLocation().getRawEncoding())
392           IIDecl = *Res;
393       }
394     }
395
396     if (!IIDecl) {
397       // None of the entities we found is a type, so there is no way
398       // to even assume that the result is a type. In this case, don't
399       // complain about the ambiguity. The parser will either try to
400       // perform this lookup again (e.g., as an object name), which
401       // will produce the ambiguity, or will complain that it expected
402       // a type name.
403       Result.suppressDiagnostics();
404       return nullptr;
405     }
406
407     // We found a type within the ambiguous lookup; diagnose the
408     // ambiguity and then return that type. This might be the right
409     // answer, or it might not be, but it suppresses any attempt to
410     // perform the name lookup again.
411     break;
412
413   case LookupResult::Found:
414     IIDecl = Result.getFoundDecl();
415     break;
416   }
417
418   assert(IIDecl && "Didn't find decl");
419
420   QualType T;
421   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
422     DiagnoseUseOfDecl(IIDecl, NameLoc);
423
424     T = Context.getTypeDeclType(TD);
425     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
426
427     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
428     // constructor or destructor name (in such a case, the scope specifier
429     // will be attached to the enclosing Expr or Decl node).
430     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
431       if (WantNontrivialTypeSourceInfo) {
432         // Construct a type with type-source information.
433         TypeLocBuilder Builder;
434         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
435
436         T = getElaboratedType(ETK_None, *SS, T);
437         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
438         ElabTL.setElaboratedKeywordLoc(SourceLocation());
439         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
440         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
441       } else {
442         T = getElaboratedType(ETK_None, *SS, T);
443       }
444     }
445   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
446     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
447     if (!HasTrailingDot)
448       T = Context.getObjCInterfaceType(IDecl);
449   }
450
451   if (T.isNull()) {
452     // If it's not plausibly a type, suppress diagnostics.
453     Result.suppressDiagnostics();
454     return nullptr;
455   }
456   return ParsedType::make(T);
457 }
458
459 // Builds a fake NNS for the given decl context.
460 static NestedNameSpecifier *
461 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
462   for (;; DC = DC->getLookupParent()) {
463     DC = DC->getPrimaryContext();
464     auto *ND = dyn_cast<NamespaceDecl>(DC);
465     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
466       return NestedNameSpecifier::Create(Context, nullptr, ND);
467     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
468       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
469                                          RD->getTypeForDecl());
470     else if (isa<TranslationUnitDecl>(DC))
471       return NestedNameSpecifier::GlobalSpecifier(Context);
472   }
473   llvm_unreachable("something isn't in TU scope?");
474 }
475
476 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
477                                                 SourceLocation NameLoc) {
478   // Accepting an undeclared identifier as a default argument for a template
479   // type parameter is a Microsoft extension.
480   Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
481
482   // Build a fake DependentNameType that will perform lookup into CurContext at
483   // instantiation time.  The name specifier isn't dependent, so template
484   // instantiation won't transform it.  It will retry the lookup, however.
485   NestedNameSpecifier *NNS =
486       synthesizeCurrentNestedNameSpecifier(Context, CurContext);
487   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
488
489   // Build type location information.  We synthesized the qualifier, so we have
490   // to build a fake NestedNameSpecifierLoc.
491   NestedNameSpecifierLocBuilder NNSLocBuilder;
492   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
493   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
494
495   TypeLocBuilder Builder;
496   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
497   DepTL.setNameLoc(NameLoc);
498   DepTL.setElaboratedKeywordLoc(SourceLocation());
499   DepTL.setQualifierLoc(QualifierLoc);
500   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
501 }
502
503 /// isTagName() - This method is called *for error recovery purposes only*
504 /// to determine if the specified name is a valid tag name ("struct foo").  If
505 /// so, this returns the TST for the tag corresponding to it (TST_enum,
506 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
507 /// cases in C where the user forgot to specify the tag.
508 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
509   // Do a tag name lookup in this scope.
510   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
511   LookupName(R, S, false);
512   R.suppressDiagnostics();
513   if (R.getResultKind() == LookupResult::Found)
514     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
515       switch (TD->getTagKind()) {
516       case TTK_Struct: return DeclSpec::TST_struct;
517       case TTK_Interface: return DeclSpec::TST_interface;
518       case TTK_Union:  return DeclSpec::TST_union;
519       case TTK_Class:  return DeclSpec::TST_class;
520       case TTK_Enum:   return DeclSpec::TST_enum;
521       }
522     }
523
524   return DeclSpec::TST_unspecified;
525 }
526
527 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
528 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
529 /// then downgrade the missing typename error to a warning.
530 /// This is needed for MSVC compatibility; Example:
531 /// @code
532 /// template<class T> class A {
533 /// public:
534 ///   typedef int TYPE;
535 /// };
536 /// template<class T> class B : public A<T> {
537 /// public:
538 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
539 /// };
540 /// @endcode
541 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
542   if (CurContext->isRecord()) {
543     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
544       return true;
545
546     const Type *Ty = SS->getScopeRep()->getAsType();
547
548     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
549     for (const auto &Base : RD->bases())
550       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
551         return true;
552     return S->isFunctionPrototypeScope();
553   }
554   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
555 }
556
557 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
558                                    SourceLocation IILoc,
559                                    Scope *S,
560                                    CXXScopeSpec *SS,
561                                    ParsedType &SuggestedType,
562                                    bool AllowClassTemplates) {
563   // We don't have anything to suggest (yet).
564   SuggestedType = nullptr;
565
566   // There may have been a typo in the name of the type. Look up typo
567   // results, in case we have something that we can suggest.
568   if (TypoCorrection Corrected =
569           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
570                       llvm::make_unique<TypeNameValidatorCCC>(
571                           false, false, AllowClassTemplates),
572                       CTK_ErrorRecovery)) {
573     if (Corrected.isKeyword()) {
574       // We corrected to a keyword.
575       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
576       II = Corrected.getCorrectionAsIdentifierInfo();
577     } else {
578       // We found a similarly-named type or interface; suggest that.
579       if (!SS || !SS->isSet()) {
580         diagnoseTypo(Corrected,
581                      PDiag(diag::err_unknown_typename_suggest) << II);
582       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
583         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
584         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
585                                 II->getName().equals(CorrectedStr);
586         diagnoseTypo(Corrected,
587                      PDiag(diag::err_unknown_nested_typename_suggest)
588                        << II << DC << DroppedSpecifier << SS->getRange());
589       } else {
590         llvm_unreachable("could not have corrected a typo here");
591       }
592
593       CXXScopeSpec tmpSS;
594       if (Corrected.getCorrectionSpecifier())
595         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
596                           SourceRange(IILoc));
597       SuggestedType =
598           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
599                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
600                       /*IsCtorOrDtorName=*/false,
601                       /*NonTrivialTypeSourceInfo=*/true);
602     }
603     return;
604   }
605
606   if (getLangOpts().CPlusPlus) {
607     // See if II is a class template that the user forgot to pass arguments to.
608     UnqualifiedId Name;
609     Name.setIdentifier(II, IILoc);
610     CXXScopeSpec EmptySS;
611     TemplateTy TemplateResult;
612     bool MemberOfUnknownSpecialization;
613     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
614                        Name, nullptr, true, TemplateResult,
615                        MemberOfUnknownSpecialization) == TNK_Type_template) {
616       TemplateName TplName = TemplateResult.get();
617       Diag(IILoc, diag::err_template_missing_args) << TplName;
618       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
619         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
620           << TplDecl->getTemplateParameters()->getSourceRange();
621       }
622       return;
623     }
624   }
625
626   // FIXME: Should we move the logic that tries to recover from a missing tag
627   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
628
629   if (!SS || (!SS->isSet() && !SS->isInvalid()))
630     Diag(IILoc, diag::err_unknown_typename) << II;
631   else if (DeclContext *DC = computeDeclContext(*SS, false))
632     Diag(IILoc, diag::err_typename_nested_not_found)
633       << II << DC << SS->getRange();
634   else if (isDependentScopeSpecifier(*SS)) {
635     unsigned DiagID = diag::err_typename_missing;
636     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
637       DiagID = diag::ext_typename_missing;
638
639     Diag(SS->getRange().getBegin(), DiagID)
640       << SS->getScopeRep() << II->getName()
641       << SourceRange(SS->getRange().getBegin(), IILoc)
642       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
643     SuggestedType = ActOnTypenameType(S, SourceLocation(),
644                                       *SS, *II, IILoc).get();
645   } else {
646     assert(SS && SS->isInvalid() &&
647            "Invalid scope specifier has already been diagnosed");
648   }
649 }
650
651 /// \brief Determine whether the given result set contains either a type name
652 /// or
653 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
654   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
655                        NextToken.is(tok::less);
656
657   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
658     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
659       return true;
660
661     if (CheckTemplate && isa<TemplateDecl>(*I))
662       return true;
663   }
664
665   return false;
666 }
667
668 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
669                                     Scope *S, CXXScopeSpec &SS,
670                                     IdentifierInfo *&Name,
671                                     SourceLocation NameLoc) {
672   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
673   SemaRef.LookupParsedName(R, S, &SS);
674   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
675     StringRef FixItTagName;
676     switch (Tag->getTagKind()) {
677       case TTK_Class:
678         FixItTagName = "class ";
679         break;
680
681       case TTK_Enum:
682         FixItTagName = "enum ";
683         break;
684
685       case TTK_Struct:
686         FixItTagName = "struct ";
687         break;
688
689       case TTK_Interface:
690         FixItTagName = "__interface ";
691         break;
692
693       case TTK_Union:
694         FixItTagName = "union ";
695         break;
696     }
697
698     StringRef TagName = FixItTagName.drop_back();
699     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
700       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
701       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
702
703     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
704          I != IEnd; ++I)
705       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
706         << Name << TagName;
707
708     // Replace lookup results with just the tag decl.
709     Result.clear(Sema::LookupTagName);
710     SemaRef.LookupParsedName(Result, S, &SS);
711     return true;
712   }
713
714   return false;
715 }
716
717 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
718 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
719                                   QualType T, SourceLocation NameLoc) {
720   ASTContext &Context = S.Context;
721
722   TypeLocBuilder Builder;
723   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
724
725   T = S.getElaboratedType(ETK_None, SS, T);
726   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
727   ElabTL.setElaboratedKeywordLoc(SourceLocation());
728   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
729   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
730 }
731
732 Sema::NameClassification
733 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
734                    SourceLocation NameLoc, const Token &NextToken,
735                    bool IsAddressOfOperand,
736                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
737   DeclarationNameInfo NameInfo(Name, NameLoc);
738   ObjCMethodDecl *CurMethod = getCurMethodDecl();
739
740   if (NextToken.is(tok::coloncolon)) {
741     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
742                                 QualType(), false, SS, nullptr, false);
743   }
744
745   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
746   LookupParsedName(Result, S, &SS, !CurMethod);
747
748   // For unqualified lookup in a class template in MSVC mode, look into
749   // dependent base classes where the primary class template is known.
750   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
751     if (ParsedType TypeInBase =
752             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
753       return TypeInBase;
754   }
755
756   // Perform lookup for Objective-C instance variables (including automatically
757   // synthesized instance variables), if we're in an Objective-C method.
758   // FIXME: This lookup really, really needs to be folded in to the normal
759   // unqualified lookup mechanism.
760   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
761     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
762     if (E.get() || E.isInvalid())
763       return E;
764   }
765
766   bool SecondTry = false;
767   bool IsFilteredTemplateName = false;
768
769 Corrected:
770   switch (Result.getResultKind()) {
771   case LookupResult::NotFound:
772     // If an unqualified-id is followed by a '(', then we have a function
773     // call.
774     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
775       // In C++, this is an ADL-only call.
776       // FIXME: Reference?
777       if (getLangOpts().CPlusPlus)
778         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
779
780       // C90 6.3.2.2:
781       //   If the expression that precedes the parenthesized argument list in a
782       //   function call consists solely of an identifier, and if no
783       //   declaration is visible for this identifier, the identifier is
784       //   implicitly declared exactly as if, in the innermost block containing
785       //   the function call, the declaration
786       //
787       //     extern int identifier ();
788       //
789       //   appeared.
790       //
791       // We also allow this in C99 as an extension.
792       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
793         Result.addDecl(D);
794         Result.resolveKind();
795         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
796       }
797     }
798
799     // In C, we first see whether there is a tag type by the same name, in
800     // which case it's likely that the user just forgot to write "enum",
801     // "struct", or "union".
802     if (!getLangOpts().CPlusPlus && !SecondTry &&
803         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
804       break;
805     }
806
807     // Perform typo correction to determine if there is another name that is
808     // close to this name.
809     if (!SecondTry && CCC) {
810       SecondTry = true;
811       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
812                                                  Result.getLookupKind(), S,
813                                                  &SS, std::move(CCC),
814                                                  CTK_ErrorRecovery)) {
815         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
816         unsigned QualifiedDiag = diag::err_no_member_suggest;
817
818         NamedDecl *FirstDecl = Corrected.getFoundDecl();
819         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
820         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
821             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
822           UnqualifiedDiag = diag::err_no_template_suggest;
823           QualifiedDiag = diag::err_no_member_template_suggest;
824         } else if (UnderlyingFirstDecl &&
825                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
826                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
827                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
828           UnqualifiedDiag = diag::err_unknown_typename_suggest;
829           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
830         }
831
832         if (SS.isEmpty()) {
833           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
834         } else {// FIXME: is this even reachable? Test it.
835           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
836           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
837                                   Name->getName().equals(CorrectedStr);
838           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
839                                     << Name << computeDeclContext(SS, false)
840                                     << DroppedSpecifier << SS.getRange());
841         }
842
843         // Update the name, so that the caller has the new name.
844         Name = Corrected.getCorrectionAsIdentifierInfo();
845
846         // Typo correction corrected to a keyword.
847         if (Corrected.isKeyword())
848           return Name;
849
850         // Also update the LookupResult...
851         // FIXME: This should probably go away at some point
852         Result.clear();
853         Result.setLookupName(Corrected.getCorrection());
854         if (FirstDecl)
855           Result.addDecl(FirstDecl);
856
857         // If we found an Objective-C instance variable, let
858         // LookupInObjCMethod build the appropriate expression to
859         // reference the ivar.
860         // FIXME: This is a gross hack.
861         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
862           Result.clear();
863           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
864           return E;
865         }
866
867         goto Corrected;
868       }
869     }
870
871     // We failed to correct; just fall through and let the parser deal with it.
872     Result.suppressDiagnostics();
873     return NameClassification::Unknown();
874
875   case LookupResult::NotFoundInCurrentInstantiation: {
876     // We performed name lookup into the current instantiation, and there were
877     // dependent bases, so we treat this result the same way as any other
878     // dependent nested-name-specifier.
879
880     // C++ [temp.res]p2:
881     //   A name used in a template declaration or definition and that is
882     //   dependent on a template-parameter is assumed not to name a type
883     //   unless the applicable name lookup finds a type name or the name is
884     //   qualified by the keyword typename.
885     //
886     // FIXME: If the next token is '<', we might want to ask the parser to
887     // perform some heroics to see if we actually have a
888     // template-argument-list, which would indicate a missing 'template'
889     // keyword here.
890     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
891                                       NameInfo, IsAddressOfOperand,
892                                       /*TemplateArgs=*/nullptr);
893   }
894
895   case LookupResult::Found:
896   case LookupResult::FoundOverloaded:
897   case LookupResult::FoundUnresolvedValue:
898     break;
899
900   case LookupResult::Ambiguous:
901     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
902         hasAnyAcceptableTemplateNames(Result)) {
903       // C++ [temp.local]p3:
904       //   A lookup that finds an injected-class-name (10.2) can result in an
905       //   ambiguity in certain cases (for example, if it is found in more than
906       //   one base class). If all of the injected-class-names that are found
907       //   refer to specializations of the same class template, and if the name
908       //   is followed by a template-argument-list, the reference refers to the
909       //   class template itself and not a specialization thereof, and is not
910       //   ambiguous.
911       //
912       // This filtering can make an ambiguous result into an unambiguous one,
913       // so try again after filtering out template names.
914       FilterAcceptableTemplateNames(Result);
915       if (!Result.isAmbiguous()) {
916         IsFilteredTemplateName = true;
917         break;
918       }
919     }
920
921     // Diagnose the ambiguity and return an error.
922     return NameClassification::Error();
923   }
924
925   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
926       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
927     // C++ [temp.names]p3:
928     //   After name lookup (3.4) finds that a name is a template-name or that
929     //   an operator-function-id or a literal- operator-id refers to a set of
930     //   overloaded functions any member of which is a function template if
931     //   this is followed by a <, the < is always taken as the delimiter of a
932     //   template-argument-list and never as the less-than operator.
933     if (!IsFilteredTemplateName)
934       FilterAcceptableTemplateNames(Result);
935
936     if (!Result.empty()) {
937       bool IsFunctionTemplate;
938       bool IsVarTemplate;
939       TemplateName Template;
940       if (Result.end() - Result.begin() > 1) {
941         IsFunctionTemplate = true;
942         Template = Context.getOverloadedTemplateName(Result.begin(),
943                                                      Result.end());
944       } else {
945         TemplateDecl *TD
946           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
947         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
948         IsVarTemplate = isa<VarTemplateDecl>(TD);
949
950         if (SS.isSet() && !SS.isInvalid())
951           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
952                                                     /*TemplateKeyword=*/false,
953                                                       TD);
954         else
955           Template = TemplateName(TD);
956       }
957
958       if (IsFunctionTemplate) {
959         // Function templates always go through overload resolution, at which
960         // point we'll perform the various checks (e.g., accessibility) we need
961         // to based on which function we selected.
962         Result.suppressDiagnostics();
963
964         return NameClassification::FunctionTemplate(Template);
965       }
966
967       return IsVarTemplate ? NameClassification::VarTemplate(Template)
968                            : NameClassification::TypeTemplate(Template);
969     }
970   }
971
972   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
973   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
974     DiagnoseUseOfDecl(Type, NameLoc);
975     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
976     QualType T = Context.getTypeDeclType(Type);
977     if (SS.isNotEmpty())
978       return buildNestedType(*this, SS, T, NameLoc);
979     return ParsedType::make(T);
980   }
981
982   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
983   if (!Class) {
984     // FIXME: It's unfortunate that we don't have a Type node for handling this.
985     if (ObjCCompatibleAliasDecl *Alias =
986             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
987       Class = Alias->getClassInterface();
988   }
989
990   if (Class) {
991     DiagnoseUseOfDecl(Class, NameLoc);
992
993     if (NextToken.is(tok::period)) {
994       // Interface. <something> is parsed as a property reference expression.
995       // Just return "unknown" as a fall-through for now.
996       Result.suppressDiagnostics();
997       return NameClassification::Unknown();
998     }
999
1000     QualType T = Context.getObjCInterfaceType(Class);
1001     return ParsedType::make(T);
1002   }
1003
1004   // We can have a type template here if we're classifying a template argument.
1005   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1006     return NameClassification::TypeTemplate(
1007         TemplateName(cast<TemplateDecl>(FirstDecl)));
1008
1009   // Check for a tag type hidden by a non-type decl in a few cases where it
1010   // seems likely a type is wanted instead of the non-type that was found.
1011   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1012   if ((NextToken.is(tok::identifier) ||
1013        (NextIsOp &&
1014         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1015       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1016     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1017     DiagnoseUseOfDecl(Type, NameLoc);
1018     QualType T = Context.getTypeDeclType(Type);
1019     if (SS.isNotEmpty())
1020       return buildNestedType(*this, SS, T, NameLoc);
1021     return ParsedType::make(T);
1022   }
1023
1024   if (FirstDecl->isCXXClassMember())
1025     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1026                                            nullptr, S);
1027
1028   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1029   return BuildDeclarationNameExpr(SS, Result, ADL);
1030 }
1031
1032 // Determines the context to return to after temporarily entering a
1033 // context.  This depends in an unnecessarily complicated way on the
1034 // exact ordering of callbacks from the parser.
1035 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1036
1037   // Functions defined inline within classes aren't parsed until we've
1038   // finished parsing the top-level class, so the top-level class is
1039   // the context we'll need to return to.
1040   // A Lambda call operator whose parent is a class must not be treated
1041   // as an inline member function.  A Lambda can be used legally
1042   // either as an in-class member initializer or a default argument.  These
1043   // are parsed once the class has been marked complete and so the containing
1044   // context would be the nested class (when the lambda is defined in one);
1045   // If the class is not complete, then the lambda is being used in an
1046   // ill-formed fashion (such as to specify the width of a bit-field, or
1047   // in an array-bound) - in which case we still want to return the
1048   // lexically containing DC (which could be a nested class).
1049   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1050     DC = DC->getLexicalParent();
1051
1052     // A function not defined within a class will always return to its
1053     // lexical context.
1054     if (!isa<CXXRecordDecl>(DC))
1055       return DC;
1056
1057     // A C++ inline method/friend is parsed *after* the topmost class
1058     // it was declared in is fully parsed ("complete");  the topmost
1059     // class is the context we need to return to.
1060     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1061       DC = RD;
1062
1063     // Return the declaration context of the topmost class the inline method is
1064     // declared in.
1065     return DC;
1066   }
1067
1068   return DC->getLexicalParent();
1069 }
1070
1071 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1072   assert(getContainingDC(DC) == CurContext &&
1073       "The next DeclContext should be lexically contained in the current one.");
1074   CurContext = DC;
1075   S->setEntity(DC);
1076 }
1077
1078 void Sema::PopDeclContext() {
1079   assert(CurContext && "DeclContext imbalance!");
1080
1081   CurContext = getContainingDC(CurContext);
1082   assert(CurContext && "Popped translation unit!");
1083 }
1084
1085 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1086                                                                     Decl *D) {
1087   // Unlike PushDeclContext, the context to which we return is not necessarily
1088   // the containing DC of TD, because the new context will be some pre-existing
1089   // TagDecl definition instead of a fresh one.
1090   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1091   CurContext = cast<TagDecl>(D)->getDefinition();
1092   assert(CurContext && "skipping definition of undefined tag");
1093   // Start lookups from the parent of the current context; we don't want to look
1094   // into the pre-existing complete definition.
1095   S->setEntity(CurContext->getLookupParent());
1096   return Result;
1097 }
1098
1099 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1100   CurContext = static_cast<decltype(CurContext)>(Context);
1101 }
1102
1103 /// EnterDeclaratorContext - Used when we must lookup names in the context
1104 /// of a declarator's nested name specifier.
1105 ///
1106 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1107   // C++0x [basic.lookup.unqual]p13:
1108   //   A name used in the definition of a static data member of class
1109   //   X (after the qualified-id of the static member) is looked up as
1110   //   if the name was used in a member function of X.
1111   // C++0x [basic.lookup.unqual]p14:
1112   //   If a variable member of a namespace is defined outside of the
1113   //   scope of its namespace then any name used in the definition of
1114   //   the variable member (after the declarator-id) is looked up as
1115   //   if the definition of the variable member occurred in its
1116   //   namespace.
1117   // Both of these imply that we should push a scope whose context
1118   // is the semantic context of the declaration.  We can't use
1119   // PushDeclContext here because that context is not necessarily
1120   // lexically contained in the current context.  Fortunately,
1121   // the containing scope should have the appropriate information.
1122
1123   assert(!S->getEntity() && "scope already has entity");
1124
1125 #ifndef NDEBUG
1126   Scope *Ancestor = S->getParent();
1127   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1128   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1129 #endif
1130
1131   CurContext = DC;
1132   S->setEntity(DC);
1133 }
1134
1135 void Sema::ExitDeclaratorContext(Scope *S) {
1136   assert(S->getEntity() == CurContext && "Context imbalance!");
1137
1138   // Switch back to the lexical context.  The safety of this is
1139   // enforced by an assert in EnterDeclaratorContext.
1140   Scope *Ancestor = S->getParent();
1141   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1142   CurContext = Ancestor->getEntity();
1143
1144   // We don't need to do anything with the scope, which is going to
1145   // disappear.
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 void Sema::ActOnExitFunctionContext() {
1173   // Same implementation as PopDeclContext, but returns to the lexical parent,
1174   // rather than the top-level class.
1175   assert(CurContext && "DeclContext imbalance!");
1176   CurContext = CurContext->getLexicalParent();
1177   assert(CurContext && "Popped translation unit!");
1178 }
1179
1180 /// \brief Determine whether we allow overloading of the function
1181 /// PrevDecl with another declaration.
1182 ///
1183 /// This routine determines whether overloading is possible, not
1184 /// whether some new function is actually an overload. It will return
1185 /// true in C++ (where we can always provide overloads) or, as an
1186 /// extension, in C when the previous function is already an
1187 /// overloaded function declaration or has the "overloadable"
1188 /// attribute.
1189 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1190                                        ASTContext &Context) {
1191   if (Context.getLangOpts().CPlusPlus)
1192     return true;
1193
1194   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1195     return true;
1196
1197   return (Previous.getResultKind() == LookupResult::Found
1198           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1199 }
1200
1201 /// Add this decl to the scope shadowed decl chains.
1202 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1203   // Move up the scope chain until we find the nearest enclosing
1204   // non-transparent context. The declaration will be introduced into this
1205   // scope.
1206   while (S->getEntity() && S->getEntity()->isTransparentContext())
1207     S = S->getParent();
1208
1209   // Add scoped declarations into their context, so that they can be
1210   // found later. Declarations without a context won't be inserted
1211   // into any context.
1212   if (AddToContext)
1213     CurContext->addDecl(D);
1214
1215   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1216   // are function-local declarations.
1217   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1218       !D->getDeclContext()->getRedeclContext()->Equals(
1219         D->getLexicalDeclContext()->getRedeclContext()) &&
1220       !D->getLexicalDeclContext()->isFunctionOrMethod())
1221     return;
1222
1223   // Template instantiations should also not be pushed into scope.
1224   if (isa<FunctionDecl>(D) &&
1225       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1226     return;
1227
1228   // If this replaces anything in the current scope,
1229   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1230                                IEnd = IdResolver.end();
1231   for (; I != IEnd; ++I) {
1232     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1233       S->RemoveDecl(*I);
1234       IdResolver.RemoveDecl(*I);
1235
1236       // Should only need to replace one decl.
1237       break;
1238     }
1239   }
1240
1241   S->AddDecl(D);
1242
1243   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1244     // Implicitly-generated labels may end up getting generated in an order that
1245     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1246     // the label at the appropriate place in the identifier chain.
1247     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1248       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1249       if (IDC == CurContext) {
1250         if (!S->isDeclScope(*I))
1251           continue;
1252       } else if (IDC->Encloses(CurContext))
1253         break;
1254     }
1255
1256     IdResolver.InsertDeclAfter(I, D);
1257   } else {
1258     IdResolver.AddDecl(D);
1259   }
1260 }
1261
1262 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1263   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1264     TUScope->AddDecl(D);
1265 }
1266
1267 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1268                          bool AllowInlineNamespace) {
1269   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1270 }
1271
1272 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1273   DeclContext *TargetDC = DC->getPrimaryContext();
1274   do {
1275     if (DeclContext *ScopeDC = S->getEntity())
1276       if (ScopeDC->getPrimaryContext() == TargetDC)
1277         return S;
1278   } while ((S = S->getParent()));
1279
1280   return nullptr;
1281 }
1282
1283 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1284                                             DeclContext*,
1285                                             ASTContext&);
1286
1287 /// Filters out lookup results that don't fall within the given scope
1288 /// as determined by isDeclInScope.
1289 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1290                                 bool ConsiderLinkage,
1291                                 bool AllowInlineNamespace) {
1292   LookupResult::Filter F = R.makeFilter();
1293   while (F.hasNext()) {
1294     NamedDecl *D = F.next();
1295
1296     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1297       continue;
1298
1299     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1300       continue;
1301
1302     F.erase();
1303   }
1304
1305   F.done();
1306 }
1307
1308 static bool isUsingDecl(NamedDecl *D) {
1309   return isa<UsingShadowDecl>(D) ||
1310          isa<UnresolvedUsingTypenameDecl>(D) ||
1311          isa<UnresolvedUsingValueDecl>(D);
1312 }
1313
1314 /// Removes using shadow declarations from the lookup results.
1315 static void RemoveUsingDecls(LookupResult &R) {
1316   LookupResult::Filter F = R.makeFilter();
1317   while (F.hasNext())
1318     if (isUsingDecl(F.next()))
1319       F.erase();
1320
1321   F.done();
1322 }
1323
1324 /// \brief Check for this common pattern:
1325 /// @code
1326 /// class S {
1327 ///   S(const S&); // DO NOT IMPLEMENT
1328 ///   void operator=(const S&); // DO NOT IMPLEMENT
1329 /// };
1330 /// @endcode
1331 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1332   // FIXME: Should check for private access too but access is set after we get
1333   // the decl here.
1334   if (D->doesThisDeclarationHaveABody())
1335     return false;
1336
1337   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1338     return CD->isCopyConstructor();
1339   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1340     return Method->isCopyAssignmentOperator();
1341   return false;
1342 }
1343
1344 // We need this to handle
1345 //
1346 // typedef struct {
1347 //   void *foo() { return 0; }
1348 // } A;
1349 //
1350 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1351 // for example. If 'A', foo will have external linkage. If we have '*A',
1352 // foo will have no linkage. Since we can't know until we get to the end
1353 // of the typedef, this function finds out if D might have non-external linkage.
1354 // Callers should verify at the end of the TU if it D has external linkage or
1355 // not.
1356 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1357   const DeclContext *DC = D->getDeclContext();
1358   while (!DC->isTranslationUnit()) {
1359     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1360       if (!RD->hasNameForLinkage())
1361         return true;
1362     }
1363     DC = DC->getParent();
1364   }
1365
1366   return !D->isExternallyVisible();
1367 }
1368
1369 // FIXME: This needs to be refactored; some other isInMainFile users want
1370 // these semantics.
1371 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1372   if (S.TUKind != TU_Complete)
1373     return false;
1374   return S.SourceMgr.isInMainFile(Loc);
1375 }
1376
1377 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1378   assert(D);
1379
1380   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1381     return false;
1382
1383   // Ignore all entities declared within templates, and out-of-line definitions
1384   // of members of class templates.
1385   if (D->getDeclContext()->isDependentContext() ||
1386       D->getLexicalDeclContext()->isDependentContext())
1387     return false;
1388
1389   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1390     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1391       return false;
1392
1393     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1394       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1395         return false;
1396     } else {
1397       // 'static inline' functions are defined in headers; don't warn.
1398       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1399         return false;
1400     }
1401
1402     if (FD->doesThisDeclarationHaveABody() &&
1403         Context.DeclMustBeEmitted(FD))
1404       return false;
1405   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1406     // Constants and utility variables are defined in headers with internal
1407     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1408     // like "inline".)
1409     if (!isMainFileLoc(*this, VD->getLocation()))
1410       return false;
1411
1412     if (Context.DeclMustBeEmitted(VD))
1413       return false;
1414
1415     if (VD->isStaticDataMember() &&
1416         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1417       return false;
1418   } else {
1419     return false;
1420   }
1421
1422   // Only warn for unused decls internal to the translation unit.
1423   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1424   // for inline functions defined in the main source file, for instance.
1425   return mightHaveNonExternalLinkage(D);
1426 }
1427
1428 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1429   if (!D)
1430     return;
1431
1432   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1433     const FunctionDecl *First = FD->getFirstDecl();
1434     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1435       return; // First should already be in the vector.
1436   }
1437
1438   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1439     const VarDecl *First = VD->getFirstDecl();
1440     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1441       return; // First should already be in the vector.
1442   }
1443
1444   if (ShouldWarnIfUnusedFileScopedDecl(D))
1445     UnusedFileScopedDecls.push_back(D);
1446 }
1447
1448 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1449   if (D->isInvalidDecl())
1450     return false;
1451
1452   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1453       D->hasAttr<ObjCPreciseLifetimeAttr>())
1454     return false;
1455
1456   if (isa<LabelDecl>(D))
1457     return true;
1458
1459   // Except for labels, we only care about unused decls that are local to
1460   // functions.
1461   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1462   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1463     // For dependent types, the diagnostic is deferred.
1464     WithinFunction =
1465         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1466   if (!WithinFunction)
1467     return false;
1468
1469   if (isa<TypedefNameDecl>(D))
1470     return true;
1471
1472   // White-list anything that isn't a local variable.
1473   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1474     return false;
1475
1476   // Types of valid local variables should be complete, so this should succeed.
1477   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1478
1479     // White-list anything with an __attribute__((unused)) type.
1480     QualType Ty = VD->getType();
1481
1482     // Only look at the outermost level of typedef.
1483     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1484       if (TT->getDecl()->hasAttr<UnusedAttr>())
1485         return false;
1486     }
1487
1488     // If we failed to complete the type for some reason, or if the type is
1489     // dependent, don't diagnose the variable.
1490     if (Ty->isIncompleteType() || Ty->isDependentType())
1491       return false;
1492
1493     if (const TagType *TT = Ty->getAs<TagType>()) {
1494       const TagDecl *Tag = TT->getDecl();
1495       if (Tag->hasAttr<UnusedAttr>())
1496         return false;
1497
1498       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1499         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1500           return false;
1501
1502         if (const Expr *Init = VD->getInit()) {
1503           if (const ExprWithCleanups *Cleanups =
1504                   dyn_cast<ExprWithCleanups>(Init))
1505             Init = Cleanups->getSubExpr();
1506           const CXXConstructExpr *Construct =
1507             dyn_cast<CXXConstructExpr>(Init);
1508           if (Construct && !Construct->isElidable()) {
1509             CXXConstructorDecl *CD = Construct->getConstructor();
1510             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1511               return false;
1512           }
1513         }
1514       }
1515     }
1516
1517     // TODO: __attribute__((unused)) templates?
1518   }
1519
1520   return true;
1521 }
1522
1523 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1524                                      FixItHint &Hint) {
1525   if (isa<LabelDecl>(D)) {
1526     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1527                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1528     if (AfterColon.isInvalid())
1529       return;
1530     Hint = FixItHint::CreateRemoval(CharSourceRange::
1531                                     getCharRange(D->getLocStart(), AfterColon));
1532   }
1533 }
1534
1535 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1536   if (D->getTypeForDecl()->isDependentType())
1537     return;
1538
1539   for (auto *TmpD : D->decls()) {
1540     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1541       DiagnoseUnusedDecl(T);
1542     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1543       DiagnoseUnusedNestedTypedefs(R);
1544   }
1545 }
1546
1547 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1548 /// unless they are marked attr(unused).
1549 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1550   if (!ShouldDiagnoseUnusedDecl(D))
1551     return;
1552
1553   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1554     // typedefs can be referenced later on, so the diagnostics are emitted
1555     // at end-of-translation-unit.
1556     UnusedLocalTypedefNameCandidates.insert(TD);
1557     return;
1558   }
1559
1560   FixItHint Hint;
1561   GenerateFixForUnusedDecl(D, Context, Hint);
1562
1563   unsigned DiagID;
1564   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1565     DiagID = diag::warn_unused_exception_param;
1566   else if (isa<LabelDecl>(D))
1567     DiagID = diag::warn_unused_label;
1568   else
1569     DiagID = diag::warn_unused_variable;
1570
1571   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1572 }
1573
1574 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1575   // Verify that we have no forward references left.  If so, there was a goto
1576   // or address of a label taken, but no definition of it.  Label fwd
1577   // definitions are indicated with a null substmt which is also not a resolved
1578   // MS inline assembly label name.
1579   bool Diagnose = false;
1580   if (L->isMSAsmLabel())
1581     Diagnose = !L->isResolvedMSAsmLabel();
1582   else
1583     Diagnose = L->getStmt() == nullptr;
1584   if (Diagnose)
1585     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1586 }
1587
1588 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1589   S->mergeNRVOIntoParent();
1590
1591   if (S->decl_empty()) return;
1592   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1593          "Scope shouldn't contain decls!");
1594
1595   for (auto *TmpD : S->decls()) {
1596     assert(TmpD && "This decl didn't get pushed??");
1597
1598     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1599     NamedDecl *D = cast<NamedDecl>(TmpD);
1600
1601     if (!D->getDeclName()) continue;
1602
1603     // Diagnose unused variables in this scope.
1604     if (!S->hasUnrecoverableErrorOccurred()) {
1605       DiagnoseUnusedDecl(D);
1606       if (const auto *RD = dyn_cast<RecordDecl>(D))
1607         DiagnoseUnusedNestedTypedefs(RD);
1608     }
1609
1610     // If this was a forward reference to a label, verify it was defined.
1611     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1612       CheckPoppedLabel(LD, *this);
1613
1614     // Remove this name from our lexical scope, and warn on it if we haven't
1615     // already.
1616     IdResolver.RemoveDecl(D);
1617     auto ShadowI = ShadowingDecls.find(D);
1618     if (ShadowI != ShadowingDecls.end()) {
1619       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1620         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1621             << D << FD << FD->getParent();
1622         Diag(FD->getLocation(), diag::note_previous_declaration);
1623       }
1624       ShadowingDecls.erase(ShadowI);
1625     }
1626   }
1627 }
1628
1629 /// \brief Look for an Objective-C class in the translation unit.
1630 ///
1631 /// \param Id The name of the Objective-C class we're looking for. If
1632 /// typo-correction fixes this name, the Id will be updated
1633 /// to the fixed name.
1634 ///
1635 /// \param IdLoc The location of the name in the translation unit.
1636 ///
1637 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1638 /// if there is no class with the given name.
1639 ///
1640 /// \returns The declaration of the named Objective-C class, or NULL if the
1641 /// class could not be found.
1642 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1643                                               SourceLocation IdLoc,
1644                                               bool DoTypoCorrection) {
1645   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1646   // creation from this context.
1647   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1648
1649   if (!IDecl && DoTypoCorrection) {
1650     // Perform typo correction at the given location, but only if we
1651     // find an Objective-C class name.
1652     if (TypoCorrection C = CorrectTypo(
1653             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1654             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1655             CTK_ErrorRecovery)) {
1656       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1657       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1658       Id = IDecl->getIdentifier();
1659     }
1660   }
1661   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1662   // This routine must always return a class definition, if any.
1663   if (Def && Def->getDefinition())
1664       Def = Def->getDefinition();
1665   return Def;
1666 }
1667
1668 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1669 /// from S, where a non-field would be declared. This routine copes
1670 /// with the difference between C and C++ scoping rules in structs and
1671 /// unions. For example, the following code is well-formed in C but
1672 /// ill-formed in C++:
1673 /// @code
1674 /// struct S6 {
1675 ///   enum { BAR } e;
1676 /// };
1677 ///
1678 /// void test_S6() {
1679 ///   struct S6 a;
1680 ///   a.e = BAR;
1681 /// }
1682 /// @endcode
1683 /// For the declaration of BAR, this routine will return a different
1684 /// scope. The scope S will be the scope of the unnamed enumeration
1685 /// within S6. In C++, this routine will return the scope associated
1686 /// with S6, because the enumeration's scope is a transparent
1687 /// context but structures can contain non-field names. In C, this
1688 /// routine will return the translation unit scope, since the
1689 /// enumeration's scope is a transparent context and structures cannot
1690 /// contain non-field names.
1691 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1692   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1693          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1694          (S->isClassScope() && !getLangOpts().CPlusPlus))
1695     S = S->getParent();
1696   return S;
1697 }
1698
1699 /// \brief Looks up the declaration of "struct objc_super" and
1700 /// saves it for later use in building builtin declaration of
1701 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1702 /// pre-existing declaration exists no action takes place.
1703 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1704                                         IdentifierInfo *II) {
1705   if (!II->isStr("objc_msgSendSuper"))
1706     return;
1707   ASTContext &Context = ThisSema.Context;
1708
1709   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1710                       SourceLocation(), Sema::LookupTagName);
1711   ThisSema.LookupName(Result, S);
1712   if (Result.getResultKind() == LookupResult::Found)
1713     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1714       Context.setObjCSuperType(Context.getTagDeclType(TD));
1715 }
1716
1717 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1718   switch (Error) {
1719   case ASTContext::GE_None:
1720     return "";
1721   case ASTContext::GE_Missing_stdio:
1722     return "stdio.h";
1723   case ASTContext::GE_Missing_setjmp:
1724     return "setjmp.h";
1725   case ASTContext::GE_Missing_ucontext:
1726     return "ucontext.h";
1727   }
1728   llvm_unreachable("unhandled error kind");
1729 }
1730
1731 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1732 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1733 /// if we're creating this built-in in anticipation of redeclaring the
1734 /// built-in.
1735 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1736                                      Scope *S, bool ForRedeclaration,
1737                                      SourceLocation Loc) {
1738   LookupPredefedObjCSuperType(*this, S, II);
1739
1740   ASTContext::GetBuiltinTypeError Error;
1741   QualType R = Context.GetBuiltinType(ID, Error);
1742   if (Error) {
1743     if (ForRedeclaration)
1744       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1745           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1746     return nullptr;
1747   }
1748
1749   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1750     Diag(Loc, diag::ext_implicit_lib_function_decl)
1751         << Context.BuiltinInfo.getName(ID) << R;
1752     if (Context.BuiltinInfo.getHeaderName(ID) &&
1753         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1754       Diag(Loc, diag::note_include_header_or_declare)
1755           << Context.BuiltinInfo.getHeaderName(ID)
1756           << Context.BuiltinInfo.getName(ID);
1757   }
1758
1759   if (R.isNull())
1760     return nullptr;
1761
1762   DeclContext *Parent = Context.getTranslationUnitDecl();
1763   if (getLangOpts().CPlusPlus) {
1764     LinkageSpecDecl *CLinkageDecl =
1765         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1766                                 LinkageSpecDecl::lang_c, false);
1767     CLinkageDecl->setImplicit();
1768     Parent->addDecl(CLinkageDecl);
1769     Parent = CLinkageDecl;
1770   }
1771
1772   FunctionDecl *New = FunctionDecl::Create(Context,
1773                                            Parent,
1774                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1775                                            SC_Extern,
1776                                            false,
1777                                            R->isFunctionProtoType());
1778   New->setImplicit();
1779
1780   // Create Decl objects for each parameter, adding them to the
1781   // FunctionDecl.
1782   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1783     SmallVector<ParmVarDecl*, 16> Params;
1784     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1785       ParmVarDecl *parm =
1786           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1787                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1788                               SC_None, nullptr);
1789       parm->setScopeInfo(0, i);
1790       Params.push_back(parm);
1791     }
1792     New->setParams(Params);
1793   }
1794
1795   AddKnownFunctionAttributes(New);
1796   RegisterLocallyScopedExternCDecl(New, S);
1797
1798   // TUScope is the translation-unit scope to insert this function into.
1799   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1800   // relate Scopes to DeclContexts, and probably eliminate CurContext
1801   // entirely, but we're not there yet.
1802   DeclContext *SavedContext = CurContext;
1803   CurContext = Parent;
1804   PushOnScopeChains(New, TUScope);
1805   CurContext = SavedContext;
1806   return New;
1807 }
1808
1809 /// Typedef declarations don't have linkage, but they still denote the same
1810 /// entity if their types are the same.
1811 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1812 /// isSameEntity.
1813 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1814                                                      TypedefNameDecl *Decl,
1815                                                      LookupResult &Previous) {
1816   // This is only interesting when modules are enabled.
1817   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1818     return;
1819
1820   // Empty sets are uninteresting.
1821   if (Previous.empty())
1822     return;
1823
1824   LookupResult::Filter Filter = Previous.makeFilter();
1825   while (Filter.hasNext()) {
1826     NamedDecl *Old = Filter.next();
1827
1828     // Non-hidden declarations are never ignored.
1829     if (S.isVisible(Old))
1830       continue;
1831
1832     // Declarations of the same entity are not ignored, even if they have
1833     // different linkages.
1834     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1835       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1836                                 Decl->getUnderlyingType()))
1837         continue;
1838
1839       // If both declarations give a tag declaration a typedef name for linkage
1840       // purposes, then they declare the same entity.
1841       if (S.getLangOpts().CPlusPlus &&
1842           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1843           Decl->getAnonDeclWithTypedefName())
1844         continue;
1845     }
1846
1847     Filter.erase();
1848   }
1849
1850   Filter.done();
1851 }
1852
1853 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1854   QualType OldType;
1855   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1856     OldType = OldTypedef->getUnderlyingType();
1857   else
1858     OldType = Context.getTypeDeclType(Old);
1859   QualType NewType = New->getUnderlyingType();
1860
1861   if (NewType->isVariablyModifiedType()) {
1862     // Must not redefine a typedef with a variably-modified type.
1863     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1864     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1865       << Kind << NewType;
1866     if (Old->getLocation().isValid())
1867       Diag(Old->getLocation(), diag::note_previous_definition);
1868     New->setInvalidDecl();
1869     return true;
1870   }
1871
1872   if (OldType != NewType &&
1873       !OldType->isDependentType() &&
1874       !NewType->isDependentType() &&
1875       !Context.hasSameType(OldType, NewType)) {
1876     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1877     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1878       << Kind << NewType << OldType;
1879     if (Old->getLocation().isValid())
1880       Diag(Old->getLocation(), diag::note_previous_definition);
1881     New->setInvalidDecl();
1882     return true;
1883   }
1884   return false;
1885 }
1886
1887 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1888 /// same name and scope as a previous declaration 'Old'.  Figure out
1889 /// how to resolve this situation, merging decls or emitting
1890 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1891 ///
1892 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1893                                 LookupResult &OldDecls) {
1894   // If the new decl is known invalid already, don't bother doing any
1895   // merging checks.
1896   if (New->isInvalidDecl()) return;
1897
1898   // Allow multiple definitions for ObjC built-in typedefs.
1899   // FIXME: Verify the underlying types are equivalent!
1900   if (getLangOpts().ObjC1) {
1901     const IdentifierInfo *TypeID = New->getIdentifier();
1902     switch (TypeID->getLength()) {
1903     default: break;
1904     case 2:
1905       {
1906         if (!TypeID->isStr("id"))
1907           break;
1908         QualType T = New->getUnderlyingType();
1909         if (!T->isPointerType())
1910           break;
1911         if (!T->isVoidPointerType()) {
1912           QualType PT = T->getAs<PointerType>()->getPointeeType();
1913           if (!PT->isStructureType())
1914             break;
1915         }
1916         Context.setObjCIdRedefinitionType(T);
1917         // Install the built-in type for 'id', ignoring the current definition.
1918         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1919         return;
1920       }
1921     case 5:
1922       if (!TypeID->isStr("Class"))
1923         break;
1924       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1925       // Install the built-in type for 'Class', ignoring the current definition.
1926       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1927       return;
1928     case 3:
1929       if (!TypeID->isStr("SEL"))
1930         break;
1931       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1932       // Install the built-in type for 'SEL', ignoring the current definition.
1933       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1934       return;
1935     }
1936     // Fall through - the typedef name was not a builtin type.
1937   }
1938
1939   // Verify the old decl was also a type.
1940   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1941   if (!Old) {
1942     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1943       << New->getDeclName();
1944
1945     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1946     if (OldD->getLocation().isValid())
1947       Diag(OldD->getLocation(), diag::note_previous_definition);
1948
1949     return New->setInvalidDecl();
1950   }
1951
1952   // If the old declaration is invalid, just give up here.
1953   if (Old->isInvalidDecl())
1954     return New->setInvalidDecl();
1955
1956   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1957     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
1958     auto *NewTag = New->getAnonDeclWithTypedefName();
1959     NamedDecl *Hidden = nullptr;
1960     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
1961         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
1962         !hasVisibleDefinition(OldTag, &Hidden)) {
1963       // There is a definition of this tag, but it is not visible. Use it
1964       // instead of our tag.
1965       New->setTypeForDecl(OldTD->getTypeForDecl());
1966       if (OldTD->isModed())
1967         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
1968                                     OldTD->getUnderlyingType());
1969       else
1970         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
1971
1972       // Make the old tag definition visible.
1973       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
1974
1975       // If this was an unscoped enumeration, yank all of its enumerators
1976       // out of the scope.
1977       if (isa<EnumDecl>(NewTag)) {
1978         Scope *EnumScope = getNonFieldDeclScope(S);
1979         for (auto *D : NewTag->decls()) {
1980           auto *ED = cast<EnumConstantDecl>(D);
1981           assert(EnumScope->isDeclScope(ED));
1982           EnumScope->RemoveDecl(ED);
1983           IdResolver.RemoveDecl(ED);
1984           ED->getLexicalDeclContext()->removeDecl(ED);
1985         }
1986       }
1987     }
1988   }
1989
1990   // If the typedef types are not identical, reject them in all languages and
1991   // with any extensions enabled.
1992   if (isIncompatibleTypedef(Old, New))
1993     return;
1994
1995   // The types match.  Link up the redeclaration chain and merge attributes if
1996   // the old declaration was a typedef.
1997   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1998     New->setPreviousDecl(Typedef);
1999     mergeDeclAttributes(New, Old);
2000   }
2001
2002   if (getLangOpts().MicrosoftExt)
2003     return;
2004
2005   if (getLangOpts().CPlusPlus) {
2006     // C++ [dcl.typedef]p2:
2007     //   In a given non-class scope, a typedef specifier can be used to
2008     //   redefine the name of any type declared in that scope to refer
2009     //   to the type to which it already refers.
2010     if (!isa<CXXRecordDecl>(CurContext))
2011       return;
2012
2013     // C++0x [dcl.typedef]p4:
2014     //   In a given class scope, a typedef specifier can be used to redefine
2015     //   any class-name declared in that scope that is not also a typedef-name
2016     //   to refer to the type to which it already refers.
2017     //
2018     // This wording came in via DR424, which was a correction to the
2019     // wording in DR56, which accidentally banned code like:
2020     //
2021     //   struct S {
2022     //     typedef struct A { } A;
2023     //   };
2024     //
2025     // in the C++03 standard. We implement the C++0x semantics, which
2026     // allow the above but disallow
2027     //
2028     //   struct S {
2029     //     typedef int I;
2030     //     typedef int I;
2031     //   };
2032     //
2033     // since that was the intent of DR56.
2034     if (!isa<TypedefNameDecl>(Old))
2035       return;
2036
2037     Diag(New->getLocation(), diag::err_redefinition)
2038       << New->getDeclName();
2039     Diag(Old->getLocation(), diag::note_previous_definition);
2040     return New->setInvalidDecl();
2041   }
2042
2043   // Modules always permit redefinition of typedefs, as does C11.
2044   if (getLangOpts().Modules || getLangOpts().C11)
2045     return;
2046
2047   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2048   // is normally mapped to an error, but can be controlled with
2049   // -Wtypedef-redefinition.  If either the original or the redefinition is
2050   // in a system header, don't emit this for compatibility with GCC.
2051   if (getDiagnostics().getSuppressSystemWarnings() &&
2052       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2053        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2054     return;
2055
2056   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2057     << New->getDeclName();
2058   Diag(Old->getLocation(), diag::note_previous_definition);
2059 }
2060
2061 /// DeclhasAttr - returns true if decl Declaration already has the target
2062 /// attribute.
2063 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2064   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2065   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2066   for (const auto *i : D->attrs())
2067     if (i->getKind() == A->getKind()) {
2068       if (Ann) {
2069         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2070           return true;
2071         continue;
2072       }
2073       // FIXME: Don't hardcode this check
2074       if (OA && isa<OwnershipAttr>(i))
2075         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2076       return true;
2077     }
2078
2079   return false;
2080 }
2081
2082 static bool isAttributeTargetADefinition(Decl *D) {
2083   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2084     return VD->isThisDeclarationADefinition();
2085   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2086     return TD->isCompleteDefinition() || TD->isBeingDefined();
2087   return true;
2088 }
2089
2090 /// Merge alignment attributes from \p Old to \p New, taking into account the
2091 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2092 ///
2093 /// \return \c true if any attributes were added to \p New.
2094 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2095   // Look for alignas attributes on Old, and pick out whichever attribute
2096   // specifies the strictest alignment requirement.
2097   AlignedAttr *OldAlignasAttr = nullptr;
2098   AlignedAttr *OldStrictestAlignAttr = nullptr;
2099   unsigned OldAlign = 0;
2100   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2101     // FIXME: We have no way of representing inherited dependent alignments
2102     // in a case like:
2103     //   template<int A, int B> struct alignas(A) X;
2104     //   template<int A, int B> struct alignas(B) X {};
2105     // For now, we just ignore any alignas attributes which are not on the
2106     // definition in such a case.
2107     if (I->isAlignmentDependent())
2108       return false;
2109
2110     if (I->isAlignas())
2111       OldAlignasAttr = I;
2112
2113     unsigned Align = I->getAlignment(S.Context);
2114     if (Align > OldAlign) {
2115       OldAlign = Align;
2116       OldStrictestAlignAttr = I;
2117     }
2118   }
2119
2120   // Look for alignas attributes on New.
2121   AlignedAttr *NewAlignasAttr = nullptr;
2122   unsigned NewAlign = 0;
2123   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2124     if (I->isAlignmentDependent())
2125       return false;
2126
2127     if (I->isAlignas())
2128       NewAlignasAttr = I;
2129
2130     unsigned Align = I->getAlignment(S.Context);
2131     if (Align > NewAlign)
2132       NewAlign = Align;
2133   }
2134
2135   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2136     // Both declarations have 'alignas' attributes. We require them to match.
2137     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2138     // fall short. (If two declarations both have alignas, they must both match
2139     // every definition, and so must match each other if there is a definition.)
2140
2141     // If either declaration only contains 'alignas(0)' specifiers, then it
2142     // specifies the natural alignment for the type.
2143     if (OldAlign == 0 || NewAlign == 0) {
2144       QualType Ty;
2145       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2146         Ty = VD->getType();
2147       else
2148         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2149
2150       if (OldAlign == 0)
2151         OldAlign = S.Context.getTypeAlign(Ty);
2152       if (NewAlign == 0)
2153         NewAlign = S.Context.getTypeAlign(Ty);
2154     }
2155
2156     if (OldAlign != NewAlign) {
2157       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2158         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2159         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2160       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2161     }
2162   }
2163
2164   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2165     // C++11 [dcl.align]p6:
2166     //   if any declaration of an entity has an alignment-specifier,
2167     //   every defining declaration of that entity shall specify an
2168     //   equivalent alignment.
2169     // C11 6.7.5/7:
2170     //   If the definition of an object does not have an alignment
2171     //   specifier, any other declaration of that object shall also
2172     //   have no alignment specifier.
2173     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2174       << OldAlignasAttr;
2175     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2176       << OldAlignasAttr;
2177   }
2178
2179   bool AnyAdded = false;
2180
2181   // Ensure we have an attribute representing the strictest alignment.
2182   if (OldAlign > NewAlign) {
2183     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2184     Clone->setInherited(true);
2185     New->addAttr(Clone);
2186     AnyAdded = true;
2187   }
2188
2189   // Ensure we have an alignas attribute if the old declaration had one.
2190   if (OldAlignasAttr && !NewAlignasAttr &&
2191       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2192     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2193     Clone->setInherited(true);
2194     New->addAttr(Clone);
2195     AnyAdded = true;
2196   }
2197
2198   return AnyAdded;
2199 }
2200
2201 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2202                                const InheritableAttr *Attr,
2203                                Sema::AvailabilityMergeKind AMK) {
2204   InheritableAttr *NewAttr = nullptr;
2205   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2206   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2207     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2208                                       AA->isImplicit(), AA->getIntroduced(),
2209                                       AA->getDeprecated(),
2210                                       AA->getObsoleted(), AA->getUnavailable(),
2211                                       AA->getMessage(), AA->getStrict(),
2212                                       AA->getReplacement(), AMK,
2213                                       AttrSpellingListIndex);
2214   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2215     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2216                                     AttrSpellingListIndex);
2217   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2218     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2219                                         AttrSpellingListIndex);
2220   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2221     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2222                                    AttrSpellingListIndex);
2223   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2224     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2225                                    AttrSpellingListIndex);
2226   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2227     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2228                                 FA->getFormatIdx(), FA->getFirstArg(),
2229                                 AttrSpellingListIndex);
2230   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2231     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2232                                  AttrSpellingListIndex);
2233   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2234     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2235                                        AttrSpellingListIndex,
2236                                        IA->getSemanticSpelling());
2237   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2238     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2239                                       &S.Context.Idents.get(AA->getSpelling()),
2240                                       AttrSpellingListIndex);
2241   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2242     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2243   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2244     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2245   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2246     NewAttr = S.mergeInternalLinkageAttr(
2247         D, InternalLinkageA->getRange(),
2248         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2249         AttrSpellingListIndex);
2250   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2251     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2252                                 &S.Context.Idents.get(CommonA->getSpelling()),
2253                                 AttrSpellingListIndex);
2254   else if (isa<AlignedAttr>(Attr))
2255     // AlignedAttrs are handled separately, because we need to handle all
2256     // such attributes on a declaration at the same time.
2257     NewAttr = nullptr;
2258   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2259            (AMK == Sema::AMK_Override ||
2260             AMK == Sema::AMK_ProtocolImplementation))
2261     NewAttr = nullptr;
2262   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2263     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2264
2265   if (NewAttr) {
2266     NewAttr->setInherited(true);
2267     D->addAttr(NewAttr);
2268     if (isa<MSInheritanceAttr>(NewAttr))
2269       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2270     return true;
2271   }
2272
2273   return false;
2274 }
2275
2276 static const Decl *getDefinition(const Decl *D) {
2277   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2278     return TD->getDefinition();
2279   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2280     const VarDecl *Def = VD->getDefinition();
2281     if (Def)
2282       return Def;
2283     return VD->getActingDefinition();
2284   }
2285   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2286     const FunctionDecl* Def;
2287     if (FD->isDefined(Def))
2288       return Def;
2289   }
2290   return nullptr;
2291 }
2292
2293 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2294   for (const auto *Attribute : D->attrs())
2295     if (Attribute->getKind() == Kind)
2296       return true;
2297   return false;
2298 }
2299
2300 /// checkNewAttributesAfterDef - If we already have a definition, check that
2301 /// there are no new attributes in this declaration.
2302 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2303   if (!New->hasAttrs())
2304     return;
2305
2306   const Decl *Def = getDefinition(Old);
2307   if (!Def || Def == New)
2308     return;
2309
2310   AttrVec &NewAttributes = New->getAttrs();
2311   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2312     const Attr *NewAttribute = NewAttributes[I];
2313
2314     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2315       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2316         Sema::SkipBodyInfo SkipBody;
2317         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2318
2319         // If we're skipping this definition, drop the "alias" attribute.
2320         if (SkipBody.ShouldSkip) {
2321           NewAttributes.erase(NewAttributes.begin() + I);
2322           --E;
2323           continue;
2324         }
2325       } else {
2326         VarDecl *VD = cast<VarDecl>(New);
2327         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2328                                 VarDecl::TentativeDefinition
2329                             ? diag::err_alias_after_tentative
2330                             : diag::err_redefinition;
2331         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2332         S.Diag(Def->getLocation(), diag::note_previous_definition);
2333         VD->setInvalidDecl();
2334       }
2335       ++I;
2336       continue;
2337     }
2338
2339     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2340       // Tentative definitions are only interesting for the alias check above.
2341       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2342         ++I;
2343         continue;
2344       }
2345     }
2346
2347     if (hasAttribute(Def, NewAttribute->getKind())) {
2348       ++I;
2349       continue; // regular attr merging will take care of validating this.
2350     }
2351
2352     if (isa<C11NoReturnAttr>(NewAttribute)) {
2353       // C's _Noreturn is allowed to be added to a function after it is defined.
2354       ++I;
2355       continue;
2356     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2357       if (AA->isAlignas()) {
2358         // C++11 [dcl.align]p6:
2359         //   if any declaration of an entity has an alignment-specifier,
2360         //   every defining declaration of that entity shall specify an
2361         //   equivalent alignment.
2362         // C11 6.7.5/7:
2363         //   If the definition of an object does not have an alignment
2364         //   specifier, any other declaration of that object shall also
2365         //   have no alignment specifier.
2366         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2367           << AA;
2368         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2369           << AA;
2370         NewAttributes.erase(NewAttributes.begin() + I);
2371         --E;
2372         continue;
2373       }
2374     }
2375
2376     S.Diag(NewAttribute->getLocation(),
2377            diag::warn_attribute_precede_definition);
2378     S.Diag(Def->getLocation(), diag::note_previous_definition);
2379     NewAttributes.erase(NewAttributes.begin() + I);
2380     --E;
2381   }
2382 }
2383
2384 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2385 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2386                                AvailabilityMergeKind AMK) {
2387   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2388     UsedAttr *NewAttr = OldAttr->clone(Context);
2389     NewAttr->setInherited(true);
2390     New->addAttr(NewAttr);
2391   }
2392
2393   if (!Old->hasAttrs() && !New->hasAttrs())
2394     return;
2395
2396   // Attributes declared post-definition are currently ignored.
2397   checkNewAttributesAfterDef(*this, New, Old);
2398
2399   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2400     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2401       if (OldA->getLabel() != NewA->getLabel()) {
2402         // This redeclaration changes __asm__ label.
2403         Diag(New->getLocation(), diag::err_different_asm_label);
2404         Diag(OldA->getLocation(), diag::note_previous_declaration);
2405       }
2406     } else if (Old->isUsed()) {
2407       // This redeclaration adds an __asm__ label to a declaration that has
2408       // already been ODR-used.
2409       Diag(New->getLocation(), diag::err_late_asm_label_name)
2410         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2411     }
2412   }
2413
2414   // Re-declaration cannot add abi_tag's.
2415   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2416     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2417       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2418         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2419                       NewTag) == OldAbiTagAttr->tags_end()) {
2420           Diag(NewAbiTagAttr->getLocation(),
2421                diag::err_new_abi_tag_on_redeclaration)
2422               << NewTag;
2423           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2424         }
2425       }
2426     } else {
2427       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2428       Diag(Old->getLocation(), diag::note_previous_declaration);
2429     }
2430   }
2431
2432   if (!Old->hasAttrs())
2433     return;
2434
2435   bool foundAny = New->hasAttrs();
2436
2437   // Ensure that any moving of objects within the allocated map is done before
2438   // we process them.
2439   if (!foundAny) New->setAttrs(AttrVec());
2440
2441   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2442     // Ignore deprecated/unavailable/availability attributes if requested.
2443     AvailabilityMergeKind LocalAMK = AMK_None;
2444     if (isa<DeprecatedAttr>(I) ||
2445         isa<UnavailableAttr>(I) ||
2446         isa<AvailabilityAttr>(I)) {
2447       switch (AMK) {
2448       case AMK_None:
2449         continue;
2450
2451       case AMK_Redeclaration:
2452       case AMK_Override:
2453       case AMK_ProtocolImplementation:
2454         LocalAMK = AMK;
2455         break;
2456       }
2457     }
2458
2459     // Already handled.
2460     if (isa<UsedAttr>(I))
2461       continue;
2462
2463     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2464       foundAny = true;
2465   }
2466
2467   if (mergeAlignedAttrs(*this, New, Old))
2468     foundAny = true;
2469
2470   if (!foundAny) New->dropAttrs();
2471 }
2472
2473 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2474 /// to the new one.
2475 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2476                                      const ParmVarDecl *oldDecl,
2477                                      Sema &S) {
2478   // C++11 [dcl.attr.depend]p2:
2479   //   The first declaration of a function shall specify the
2480   //   carries_dependency attribute for its declarator-id if any declaration
2481   //   of the function specifies the carries_dependency attribute.
2482   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2483   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2484     S.Diag(CDA->getLocation(),
2485            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2486     // Find the first declaration of the parameter.
2487     // FIXME: Should we build redeclaration chains for function parameters?
2488     const FunctionDecl *FirstFD =
2489       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2490     const ParmVarDecl *FirstVD =
2491       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2492     S.Diag(FirstVD->getLocation(),
2493            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2494   }
2495
2496   if (!oldDecl->hasAttrs())
2497     return;
2498
2499   bool foundAny = newDecl->hasAttrs();
2500
2501   // Ensure that any moving of objects within the allocated map is
2502   // done before we process them.
2503   if (!foundAny) newDecl->setAttrs(AttrVec());
2504
2505   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2506     if (!DeclHasAttr(newDecl, I)) {
2507       InheritableAttr *newAttr =
2508         cast<InheritableParamAttr>(I->clone(S.Context));
2509       newAttr->setInherited(true);
2510       newDecl->addAttr(newAttr);
2511       foundAny = true;
2512     }
2513   }
2514
2515   if (!foundAny) newDecl->dropAttrs();
2516 }
2517
2518 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2519                                 const ParmVarDecl *OldParam,
2520                                 Sema &S) {
2521   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2522     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2523       if (*Oldnullability != *Newnullability) {
2524         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2525           << DiagNullabilityKind(
2526                *Newnullability,
2527                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2528                 != 0))
2529           << DiagNullabilityKind(
2530                *Oldnullability,
2531                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2532                 != 0));
2533         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2534       }
2535     } else {
2536       QualType NewT = NewParam->getType();
2537       NewT = S.Context.getAttributedType(
2538                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2539                          NewT, NewT);
2540       NewParam->setType(NewT);
2541     }
2542   }
2543 }
2544
2545 namespace {
2546
2547 /// Used in MergeFunctionDecl to keep track of function parameters in
2548 /// C.
2549 struct GNUCompatibleParamWarning {
2550   ParmVarDecl *OldParm;
2551   ParmVarDecl *NewParm;
2552   QualType PromotedType;
2553 };
2554
2555 } // end anonymous namespace
2556
2557 /// getSpecialMember - get the special member enum for a method.
2558 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2559   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2560     if (Ctor->isDefaultConstructor())
2561       return Sema::CXXDefaultConstructor;
2562
2563     if (Ctor->isCopyConstructor())
2564       return Sema::CXXCopyConstructor;
2565
2566     if (Ctor->isMoveConstructor())
2567       return Sema::CXXMoveConstructor;
2568   } else if (isa<CXXDestructorDecl>(MD)) {
2569     return Sema::CXXDestructor;
2570   } else if (MD->isCopyAssignmentOperator()) {
2571     return Sema::CXXCopyAssignment;
2572   } else if (MD->isMoveAssignmentOperator()) {
2573     return Sema::CXXMoveAssignment;
2574   }
2575
2576   return Sema::CXXInvalid;
2577 }
2578
2579 // Determine whether the previous declaration was a definition, implicit
2580 // declaration, or a declaration.
2581 template <typename T>
2582 static std::pair<diag::kind, SourceLocation>
2583 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2584   diag::kind PrevDiag;
2585   SourceLocation OldLocation = Old->getLocation();
2586   if (Old->isThisDeclarationADefinition())
2587     PrevDiag = diag::note_previous_definition;
2588   else if (Old->isImplicit()) {
2589     PrevDiag = diag::note_previous_implicit_declaration;
2590     if (OldLocation.isInvalid())
2591       OldLocation = New->getLocation();
2592   } else
2593     PrevDiag = diag::note_previous_declaration;
2594   return std::make_pair(PrevDiag, OldLocation);
2595 }
2596
2597 /// canRedefineFunction - checks if a function can be redefined. Currently,
2598 /// only extern inline functions can be redefined, and even then only in
2599 /// GNU89 mode.
2600 static bool canRedefineFunction(const FunctionDecl *FD,
2601                                 const LangOptions& LangOpts) {
2602   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2603           !LangOpts.CPlusPlus &&
2604           FD->isInlineSpecified() &&
2605           FD->getStorageClass() == SC_Extern);
2606 }
2607
2608 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2609   const AttributedType *AT = T->getAs<AttributedType>();
2610   while (AT && !AT->isCallingConv())
2611     AT = AT->getModifiedType()->getAs<AttributedType>();
2612   return AT;
2613 }
2614
2615 template <typename T>
2616 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2617   const DeclContext *DC = Old->getDeclContext();
2618   if (DC->isRecord())
2619     return false;
2620
2621   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2622   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2623     return true;
2624   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2625     return true;
2626   return false;
2627 }
2628
2629 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2630 static bool isExternC(VarTemplateDecl *) { return false; }
2631
2632 /// \brief Check whether a redeclaration of an entity introduced by a
2633 /// using-declaration is valid, given that we know it's not an overload
2634 /// (nor a hidden tag declaration).
2635 template<typename ExpectedDecl>
2636 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2637                                    ExpectedDecl *New) {
2638   // C++11 [basic.scope.declarative]p4:
2639   //   Given a set of declarations in a single declarative region, each of
2640   //   which specifies the same unqualified name,
2641   //   -- they shall all refer to the same entity, or all refer to functions
2642   //      and function templates; or
2643   //   -- exactly one declaration shall declare a class name or enumeration
2644   //      name that is not a typedef name and the other declarations shall all
2645   //      refer to the same variable or enumerator, or all refer to functions
2646   //      and function templates; in this case the class name or enumeration
2647   //      name is hidden (3.3.10).
2648
2649   // C++11 [namespace.udecl]p14:
2650   //   If a function declaration in namespace scope or block scope has the
2651   //   same name and the same parameter-type-list as a function introduced
2652   //   by a using-declaration, and the declarations do not declare the same
2653   //   function, the program is ill-formed.
2654
2655   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2656   if (Old &&
2657       !Old->getDeclContext()->getRedeclContext()->Equals(
2658           New->getDeclContext()->getRedeclContext()) &&
2659       !(isExternC(Old) && isExternC(New)))
2660     Old = nullptr;
2661
2662   if (!Old) {
2663     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2664     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2665     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2666     return true;
2667   }
2668   return false;
2669 }
2670
2671 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2672                                             const FunctionDecl *B) {
2673   assert(A->getNumParams() == B->getNumParams());
2674
2675   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2676     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2677     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2678     if (AttrA == AttrB)
2679       return true;
2680     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2681   };
2682
2683   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2684 }
2685
2686 /// MergeFunctionDecl - We just parsed a function 'New' from
2687 /// declarator D which has the same name and scope as a previous
2688 /// declaration 'Old'.  Figure out how to resolve this situation,
2689 /// merging decls or emitting diagnostics as appropriate.
2690 ///
2691 /// In C++, New and Old must be declarations that are not
2692 /// overloaded. Use IsOverload to determine whether New and Old are
2693 /// overloaded, and to select the Old declaration that New should be
2694 /// merged with.
2695 ///
2696 /// Returns true if there was an error, false otherwise.
2697 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2698                              Scope *S, bool MergeTypeWithOld) {
2699   // Verify the old decl was also a function.
2700   FunctionDecl *Old = OldD->getAsFunction();
2701   if (!Old) {
2702     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2703       if (New->getFriendObjectKind()) {
2704         Diag(New->getLocation(), diag::err_using_decl_friend);
2705         Diag(Shadow->getTargetDecl()->getLocation(),
2706              diag::note_using_decl_target);
2707         Diag(Shadow->getUsingDecl()->getLocation(),
2708              diag::note_using_decl) << 0;
2709         return true;
2710       }
2711
2712       // Check whether the two declarations might declare the same function.
2713       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2714         return true;
2715       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2716     } else {
2717       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2718         << New->getDeclName();
2719       Diag(OldD->getLocation(), diag::note_previous_definition);
2720       return true;
2721     }
2722   }
2723
2724   // If the old declaration is invalid, just give up here.
2725   if (Old->isInvalidDecl())
2726     return true;
2727
2728   diag::kind PrevDiag;
2729   SourceLocation OldLocation;
2730   std::tie(PrevDiag, OldLocation) =
2731       getNoteDiagForInvalidRedeclaration(Old, New);
2732
2733   // Don't complain about this if we're in GNU89 mode and the old function
2734   // is an extern inline function.
2735   // Don't complain about specializations. They are not supposed to have
2736   // storage classes.
2737   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2738       New->getStorageClass() == SC_Static &&
2739       Old->hasExternalFormalLinkage() &&
2740       !New->getTemplateSpecializationInfo() &&
2741       !canRedefineFunction(Old, getLangOpts())) {
2742     if (getLangOpts().MicrosoftExt) {
2743       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2744       Diag(OldLocation, PrevDiag);
2745     } else {
2746       Diag(New->getLocation(), diag::err_static_non_static) << New;
2747       Diag(OldLocation, PrevDiag);
2748       return true;
2749     }
2750   }
2751
2752   if (New->hasAttr<InternalLinkageAttr>() &&
2753       !Old->hasAttr<InternalLinkageAttr>()) {
2754     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2755         << New->getDeclName();
2756     Diag(Old->getLocation(), diag::note_previous_definition);
2757     New->dropAttr<InternalLinkageAttr>();
2758   }
2759
2760   // If a function is first declared with a calling convention, but is later
2761   // declared or defined without one, all following decls assume the calling
2762   // convention of the first.
2763   //
2764   // It's OK if a function is first declared without a calling convention,
2765   // but is later declared or defined with the default calling convention.
2766   //
2767   // To test if either decl has an explicit calling convention, we look for
2768   // AttributedType sugar nodes on the type as written.  If they are missing or
2769   // were canonicalized away, we assume the calling convention was implicit.
2770   //
2771   // Note also that we DO NOT return at this point, because we still have
2772   // other tests to run.
2773   QualType OldQType = Context.getCanonicalType(Old->getType());
2774   QualType NewQType = Context.getCanonicalType(New->getType());
2775   const FunctionType *OldType = cast<FunctionType>(OldQType);
2776   const FunctionType *NewType = cast<FunctionType>(NewQType);
2777   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2778   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2779   bool RequiresAdjustment = false;
2780
2781   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2782     FunctionDecl *First = Old->getFirstDecl();
2783     const FunctionType *FT =
2784         First->getType().getCanonicalType()->castAs<FunctionType>();
2785     FunctionType::ExtInfo FI = FT->getExtInfo();
2786     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2787     if (!NewCCExplicit) {
2788       // Inherit the CC from the previous declaration if it was specified
2789       // there but not here.
2790       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2791       RequiresAdjustment = true;
2792     } else {
2793       // Calling conventions aren't compatible, so complain.
2794       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2795       Diag(New->getLocation(), diag::err_cconv_change)
2796         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2797         << !FirstCCExplicit
2798         << (!FirstCCExplicit ? "" :
2799             FunctionType::getNameForCallConv(FI.getCC()));
2800
2801       // Put the note on the first decl, since it is the one that matters.
2802       Diag(First->getLocation(), diag::note_previous_declaration);
2803       return true;
2804     }
2805   }
2806
2807   // FIXME: diagnose the other way around?
2808   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2809     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2810     RequiresAdjustment = true;
2811   }
2812
2813   // Merge regparm attribute.
2814   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2815       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2816     if (NewTypeInfo.getHasRegParm()) {
2817       Diag(New->getLocation(), diag::err_regparm_mismatch)
2818         << NewType->getRegParmType()
2819         << OldType->getRegParmType();
2820       Diag(OldLocation, diag::note_previous_declaration);
2821       return true;
2822     }
2823
2824     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2825     RequiresAdjustment = true;
2826   }
2827
2828   // Merge ns_returns_retained attribute.
2829   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2830     if (NewTypeInfo.getProducesResult()) {
2831       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2832       Diag(OldLocation, diag::note_previous_declaration);
2833       return true;
2834     }
2835
2836     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2837     RequiresAdjustment = true;
2838   }
2839
2840   if (RequiresAdjustment) {
2841     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2842     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2843     New->setType(QualType(AdjustedType, 0));
2844     NewQType = Context.getCanonicalType(New->getType());
2845     NewType = cast<FunctionType>(NewQType);
2846   }
2847
2848   // If this redeclaration makes the function inline, we may need to add it to
2849   // UndefinedButUsed.
2850   if (!Old->isInlined() && New->isInlined() &&
2851       !New->hasAttr<GNUInlineAttr>() &&
2852       !getLangOpts().GNUInline &&
2853       Old->isUsed(false) &&
2854       !Old->isDefined() && !New->isThisDeclarationADefinition())
2855     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2856                                            SourceLocation()));
2857
2858   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2859   // about it.
2860   if (New->hasAttr<GNUInlineAttr>() &&
2861       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2862     UndefinedButUsed.erase(Old->getCanonicalDecl());
2863   }
2864
2865   // If pass_object_size params don't match up perfectly, this isn't a valid
2866   // redeclaration.
2867   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2868       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2869     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2870         << New->getDeclName();
2871     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2872     return true;
2873   }
2874
2875   if (getLangOpts().CPlusPlus) {
2876     // (C++98 13.1p2):
2877     //   Certain function declarations cannot be overloaded:
2878     //     -- Function declarations that differ only in the return type
2879     //        cannot be overloaded.
2880
2881     // Go back to the type source info to compare the declared return types,
2882     // per C++1y [dcl.type.auto]p13:
2883     //   Redeclarations or specializations of a function or function template
2884     //   with a declared return type that uses a placeholder type shall also
2885     //   use that placeholder, not a deduced type.
2886     QualType OldDeclaredReturnType =
2887         (Old->getTypeSourceInfo()
2888              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2889              : OldType)->getReturnType();
2890     QualType NewDeclaredReturnType =
2891         (New->getTypeSourceInfo()
2892              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2893              : NewType)->getReturnType();
2894     QualType ResQT;
2895     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2896         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2897           New->isLocalExternDecl())) {
2898       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2899           OldDeclaredReturnType->isObjCObjectPointerType())
2900         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2901       if (ResQT.isNull()) {
2902         if (New->isCXXClassMember() && New->isOutOfLine())
2903           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2904               << New << New->getReturnTypeSourceRange();
2905         else
2906           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2907               << New->getReturnTypeSourceRange();
2908         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2909                                     << Old->getReturnTypeSourceRange();
2910         return true;
2911       }
2912       else
2913         NewQType = ResQT;
2914     }
2915
2916     QualType OldReturnType = OldType->getReturnType();
2917     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2918     if (OldReturnType != NewReturnType) {
2919       // If this function has a deduced return type and has already been
2920       // defined, copy the deduced value from the old declaration.
2921       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2922       if (OldAT && OldAT->isDeduced()) {
2923         New->setType(
2924             SubstAutoType(New->getType(),
2925                           OldAT->isDependentType() ? Context.DependentTy
2926                                                    : OldAT->getDeducedType()));
2927         NewQType = Context.getCanonicalType(
2928             SubstAutoType(NewQType,
2929                           OldAT->isDependentType() ? Context.DependentTy
2930                                                    : OldAT->getDeducedType()));
2931       }
2932     }
2933
2934     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2935     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2936     if (OldMethod && NewMethod) {
2937       // Preserve triviality.
2938       NewMethod->setTrivial(OldMethod->isTrivial());
2939
2940       // MSVC allows explicit template specialization at class scope:
2941       // 2 CXXMethodDecls referring to the same function will be injected.
2942       // We don't want a redeclaration error.
2943       bool IsClassScopeExplicitSpecialization =
2944                               OldMethod->isFunctionTemplateSpecialization() &&
2945                               NewMethod->isFunctionTemplateSpecialization();
2946       bool isFriend = NewMethod->getFriendObjectKind();
2947
2948       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2949           !IsClassScopeExplicitSpecialization) {
2950         //    -- Member function declarations with the same name and the
2951         //       same parameter types cannot be overloaded if any of them
2952         //       is a static member function declaration.
2953         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2954           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2955           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2956           return true;
2957         }
2958
2959         // C++ [class.mem]p1:
2960         //   [...] A member shall not be declared twice in the
2961         //   member-specification, except that a nested class or member
2962         //   class template can be declared and then later defined.
2963         if (ActiveTemplateInstantiations.empty()) {
2964           unsigned NewDiag;
2965           if (isa<CXXConstructorDecl>(OldMethod))
2966             NewDiag = diag::err_constructor_redeclared;
2967           else if (isa<CXXDestructorDecl>(NewMethod))
2968             NewDiag = diag::err_destructor_redeclared;
2969           else if (isa<CXXConversionDecl>(NewMethod))
2970             NewDiag = diag::err_conv_function_redeclared;
2971           else
2972             NewDiag = diag::err_member_redeclared;
2973
2974           Diag(New->getLocation(), NewDiag);
2975         } else {
2976           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2977             << New << New->getType();
2978         }
2979         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2980         return true;
2981
2982       // Complain if this is an explicit declaration of a special
2983       // member that was initially declared implicitly.
2984       //
2985       // As an exception, it's okay to befriend such methods in order
2986       // to permit the implicit constructor/destructor/operator calls.
2987       } else if (OldMethod->isImplicit()) {
2988         if (isFriend) {
2989           NewMethod->setImplicit();
2990         } else {
2991           Diag(NewMethod->getLocation(),
2992                diag::err_definition_of_implicitly_declared_member)
2993             << New << getSpecialMember(OldMethod);
2994           return true;
2995         }
2996       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2997         Diag(NewMethod->getLocation(),
2998              diag::err_definition_of_explicitly_defaulted_member)
2999           << getSpecialMember(OldMethod);
3000         return true;
3001       }
3002     }
3003
3004     // C++11 [dcl.attr.noreturn]p1:
3005     //   The first declaration of a function shall specify the noreturn
3006     //   attribute if any declaration of that function specifies the noreturn
3007     //   attribute.
3008     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3009     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3010       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3011       Diag(Old->getFirstDecl()->getLocation(),
3012            diag::note_noreturn_missing_first_decl);
3013     }
3014
3015     // C++11 [dcl.attr.depend]p2:
3016     //   The first declaration of a function shall specify the
3017     //   carries_dependency attribute for its declarator-id if any declaration
3018     //   of the function specifies the carries_dependency attribute.
3019     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3020     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3021       Diag(CDA->getLocation(),
3022            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3023       Diag(Old->getFirstDecl()->getLocation(),
3024            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3025     }
3026
3027     // (C++98 8.3.5p3):
3028     //   All declarations for a function shall agree exactly in both the
3029     //   return type and the parameter-type-list.
3030     // We also want to respect all the extended bits except noreturn.
3031
3032     // noreturn should now match unless the old type info didn't have it.
3033     QualType OldQTypeForComparison = OldQType;
3034     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3035       assert(OldQType == QualType(OldType, 0));
3036       const FunctionType *OldTypeForComparison
3037         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3038       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3039       assert(OldQTypeForComparison.isCanonical());
3040     }
3041
3042     if (haveIncompatibleLanguageLinkages(Old, New)) {
3043       // As a special case, retain the language linkage from previous
3044       // declarations of a friend function as an extension.
3045       //
3046       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3047       // and is useful because there's otherwise no way to specify language
3048       // linkage within class scope.
3049       //
3050       // Check cautiously as the friend object kind isn't yet complete.
3051       if (New->getFriendObjectKind() != Decl::FOK_None) {
3052         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3053         Diag(OldLocation, PrevDiag);
3054       } else {
3055         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3056         Diag(OldLocation, PrevDiag);
3057         return true;
3058       }
3059     }
3060
3061     if (OldQTypeForComparison == NewQType)
3062       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3063
3064     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3065         New->isLocalExternDecl()) {
3066       // It's OK if we couldn't merge types for a local function declaraton
3067       // if either the old or new type is dependent. We'll merge the types
3068       // when we instantiate the function.
3069       return false;
3070     }
3071
3072     // Fall through for conflicting redeclarations and redefinitions.
3073   }
3074
3075   // C: Function types need to be compatible, not identical. This handles
3076   // duplicate function decls like "void f(int); void f(enum X);" properly.
3077   if (!getLangOpts().CPlusPlus &&
3078       Context.typesAreCompatible(OldQType, NewQType)) {
3079     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3080     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3081     const FunctionProtoType *OldProto = nullptr;
3082     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3083         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3084       // The old declaration provided a function prototype, but the
3085       // new declaration does not. Merge in the prototype.
3086       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3087       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3088       NewQType =
3089           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3090                                   OldProto->getExtProtoInfo());
3091       New->setType(NewQType);
3092       New->setHasInheritedPrototype();
3093
3094       // Synthesize parameters with the same types.
3095       SmallVector<ParmVarDecl*, 16> Params;
3096       for (const auto &ParamType : OldProto->param_types()) {
3097         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3098                                                  SourceLocation(), nullptr,
3099                                                  ParamType, /*TInfo=*/nullptr,
3100                                                  SC_None, nullptr);
3101         Param->setScopeInfo(0, Params.size());
3102         Param->setImplicit();
3103         Params.push_back(Param);
3104       }
3105
3106       New->setParams(Params);
3107     }
3108
3109     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3110   }
3111
3112   // GNU C permits a K&R definition to follow a prototype declaration
3113   // if the declared types of the parameters in the K&R definition
3114   // match the types in the prototype declaration, even when the
3115   // promoted types of the parameters from the K&R definition differ
3116   // from the types in the prototype. GCC then keeps the types from
3117   // the prototype.
3118   //
3119   // If a variadic prototype is followed by a non-variadic K&R definition,
3120   // the K&R definition becomes variadic.  This is sort of an edge case, but
3121   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3122   // C99 6.9.1p8.
3123   if (!getLangOpts().CPlusPlus &&
3124       Old->hasPrototype() && !New->hasPrototype() &&
3125       New->getType()->getAs<FunctionProtoType>() &&
3126       Old->getNumParams() == New->getNumParams()) {
3127     SmallVector<QualType, 16> ArgTypes;
3128     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3129     const FunctionProtoType *OldProto
3130       = Old->getType()->getAs<FunctionProtoType>();
3131     const FunctionProtoType *NewProto
3132       = New->getType()->getAs<FunctionProtoType>();
3133
3134     // Determine whether this is the GNU C extension.
3135     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3136                                                NewProto->getReturnType());
3137     bool LooseCompatible = !MergedReturn.isNull();
3138     for (unsigned Idx = 0, End = Old->getNumParams();
3139          LooseCompatible && Idx != End; ++Idx) {
3140       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3141       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3142       if (Context.typesAreCompatible(OldParm->getType(),
3143                                      NewProto->getParamType(Idx))) {
3144         ArgTypes.push_back(NewParm->getType());
3145       } else if (Context.typesAreCompatible(OldParm->getType(),
3146                                             NewParm->getType(),
3147                                             /*CompareUnqualified=*/true)) {
3148         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3149                                            NewProto->getParamType(Idx) };
3150         Warnings.push_back(Warn);
3151         ArgTypes.push_back(NewParm->getType());
3152       } else
3153         LooseCompatible = false;
3154     }
3155
3156     if (LooseCompatible) {
3157       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3158         Diag(Warnings[Warn].NewParm->getLocation(),
3159              diag::ext_param_promoted_not_compatible_with_prototype)
3160           << Warnings[Warn].PromotedType
3161           << Warnings[Warn].OldParm->getType();
3162         if (Warnings[Warn].OldParm->getLocation().isValid())
3163           Diag(Warnings[Warn].OldParm->getLocation(),
3164                diag::note_previous_declaration);
3165       }
3166
3167       if (MergeTypeWithOld)
3168         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3169                                              OldProto->getExtProtoInfo()));
3170       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3171     }
3172
3173     // Fall through to diagnose conflicting types.
3174   }
3175
3176   // A function that has already been declared has been redeclared or
3177   // defined with a different type; show an appropriate diagnostic.
3178
3179   // If the previous declaration was an implicitly-generated builtin
3180   // declaration, then at the very least we should use a specialized note.
3181   unsigned BuiltinID;
3182   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3183     // If it's actually a library-defined builtin function like 'malloc'
3184     // or 'printf', just warn about the incompatible redeclaration.
3185     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3186       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3187       Diag(OldLocation, diag::note_previous_builtin_declaration)
3188         << Old << Old->getType();
3189
3190       // If this is a global redeclaration, just forget hereafter
3191       // about the "builtin-ness" of the function.
3192       //
3193       // Doing this for local extern declarations is problematic.  If
3194       // the builtin declaration remains visible, a second invalid
3195       // local declaration will produce a hard error; if it doesn't
3196       // remain visible, a single bogus local redeclaration (which is
3197       // actually only a warning) could break all the downstream code.
3198       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3199         New->getIdentifier()->revertBuiltin();
3200
3201       return false;
3202     }
3203
3204     PrevDiag = diag::note_previous_builtin_declaration;
3205   }
3206
3207   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3208   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3209   return true;
3210 }
3211
3212 /// \brief Completes the merge of two function declarations that are
3213 /// known to be compatible.
3214 ///
3215 /// This routine handles the merging of attributes and other
3216 /// properties of function declarations from the old declaration to
3217 /// the new declaration, once we know that New is in fact a
3218 /// redeclaration of Old.
3219 ///
3220 /// \returns false
3221 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3222                                         Scope *S, bool MergeTypeWithOld) {
3223   // Merge the attributes
3224   mergeDeclAttributes(New, Old);
3225
3226   // Merge "pure" flag.
3227   if (Old->isPure())
3228     New->setPure();
3229
3230   // Merge "used" flag.
3231   if (Old->getMostRecentDecl()->isUsed(false))
3232     New->setIsUsed();
3233
3234   // Merge attributes from the parameters.  These can mismatch with K&R
3235   // declarations.
3236   if (New->getNumParams() == Old->getNumParams())
3237       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3238         ParmVarDecl *NewParam = New->getParamDecl(i);
3239         ParmVarDecl *OldParam = Old->getParamDecl(i);
3240         mergeParamDeclAttributes(NewParam, OldParam, *this);
3241         mergeParamDeclTypes(NewParam, OldParam, *this);
3242       }
3243
3244   if (getLangOpts().CPlusPlus)
3245     return MergeCXXFunctionDecl(New, Old, S);
3246
3247   // Merge the function types so the we get the composite types for the return
3248   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3249   // was visible.
3250   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3251   if (!Merged.isNull() && MergeTypeWithOld)
3252     New->setType(Merged);
3253
3254   return false;
3255 }
3256
3257 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3258                                 ObjCMethodDecl *oldMethod) {
3259   // Merge the attributes, including deprecated/unavailable
3260   AvailabilityMergeKind MergeKind =
3261     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3262       ? AMK_ProtocolImplementation
3263       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3264                                                        : AMK_Override;
3265
3266   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3267
3268   // Merge attributes from the parameters.
3269   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3270                                        oe = oldMethod->param_end();
3271   for (ObjCMethodDecl::param_iterator
3272          ni = newMethod->param_begin(), ne = newMethod->param_end();
3273        ni != ne && oi != oe; ++ni, ++oi)
3274     mergeParamDeclAttributes(*ni, *oi, *this);
3275
3276   CheckObjCMethodOverride(newMethod, oldMethod);
3277 }
3278
3279 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3280   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3281
3282   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3283          ? diag::err_redefinition_different_type
3284          : diag::err_redeclaration_different_type)
3285     << New->getDeclName() << New->getType() << Old->getType();
3286
3287   diag::kind PrevDiag;
3288   SourceLocation OldLocation;
3289   std::tie(PrevDiag, OldLocation)
3290     = getNoteDiagForInvalidRedeclaration(Old, New);
3291   S.Diag(OldLocation, PrevDiag);
3292   New->setInvalidDecl();
3293 }
3294
3295 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3296 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3297 /// emitting diagnostics as appropriate.
3298 ///
3299 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3300 /// to here in AddInitializerToDecl. We can't check them before the initializer
3301 /// is attached.
3302 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3303                              bool MergeTypeWithOld) {
3304   if (New->isInvalidDecl() || Old->isInvalidDecl())
3305     return;
3306
3307   QualType MergedT;
3308   if (getLangOpts().CPlusPlus) {
3309     if (New->getType()->isUndeducedType()) {
3310       // We don't know what the new type is until the initializer is attached.
3311       return;
3312     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3313       // These could still be something that needs exception specs checked.
3314       return MergeVarDeclExceptionSpecs(New, Old);
3315     }
3316     // C++ [basic.link]p10:
3317     //   [...] the types specified by all declarations referring to a given
3318     //   object or function shall be identical, except that declarations for an
3319     //   array object can specify array types that differ by the presence or
3320     //   absence of a major array bound (8.3.4).
3321     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3322       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3323       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3324
3325       // We are merging a variable declaration New into Old. If it has an array
3326       // bound, and that bound differs from Old's bound, we should diagnose the
3327       // mismatch.
3328       if (!NewArray->isIncompleteArrayType()) {
3329         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3330              PrevVD = PrevVD->getPreviousDecl()) {
3331           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3332           if (PrevVDTy->isIncompleteArrayType())
3333             continue;
3334
3335           if (!Context.hasSameType(NewArray, PrevVDTy))
3336             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3337         }
3338       }
3339
3340       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3341         if (Context.hasSameType(OldArray->getElementType(),
3342                                 NewArray->getElementType()))
3343           MergedT = New->getType();
3344       }
3345       // FIXME: Check visibility. New is hidden but has a complete type. If New
3346       // has no array bound, it should not inherit one from Old, if Old is not
3347       // visible.
3348       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3349         if (Context.hasSameType(OldArray->getElementType(),
3350                                 NewArray->getElementType()))
3351           MergedT = Old->getType();
3352       }
3353     }
3354     else if (New->getType()->isObjCObjectPointerType() &&
3355                Old->getType()->isObjCObjectPointerType()) {
3356       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3357                                               Old->getType());
3358     }
3359   } else {
3360     // C 6.2.7p2:
3361     //   All declarations that refer to the same object or function shall have
3362     //   compatible type.
3363     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3364   }
3365   if (MergedT.isNull()) {
3366     // It's OK if we couldn't merge types if either type is dependent, for a
3367     // block-scope variable. In other cases (static data members of class
3368     // templates, variable templates, ...), we require the types to be
3369     // equivalent.
3370     // FIXME: The C++ standard doesn't say anything about this.
3371     if ((New->getType()->isDependentType() ||
3372          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3373       // If the old type was dependent, we can't merge with it, so the new type
3374       // becomes dependent for now. We'll reproduce the original type when we
3375       // instantiate the TypeSourceInfo for the variable.
3376       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3377         New->setType(Context.DependentTy);
3378       return;
3379     }
3380     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3381   }
3382
3383   // Don't actually update the type on the new declaration if the old
3384   // declaration was an extern declaration in a different scope.
3385   if (MergeTypeWithOld)
3386     New->setType(MergedT);
3387 }
3388
3389 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3390                                   LookupResult &Previous) {
3391   // C11 6.2.7p4:
3392   //   For an identifier with internal or external linkage declared
3393   //   in a scope in which a prior declaration of that identifier is
3394   //   visible, if the prior declaration specifies internal or
3395   //   external linkage, the type of the identifier at the later
3396   //   declaration becomes the composite type.
3397   //
3398   // If the variable isn't visible, we do not merge with its type.
3399   if (Previous.isShadowed())
3400     return false;
3401
3402   if (S.getLangOpts().CPlusPlus) {
3403     // C++11 [dcl.array]p3:
3404     //   If there is a preceding declaration of the entity in the same
3405     //   scope in which the bound was specified, an omitted array bound
3406     //   is taken to be the same as in that earlier declaration.
3407     return NewVD->isPreviousDeclInSameBlockScope() ||
3408            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3409             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3410   } else {
3411     // If the old declaration was function-local, don't merge with its
3412     // type unless we're in the same function.
3413     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3414            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3415   }
3416 }
3417
3418 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3419 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3420 /// situation, merging decls or emitting diagnostics as appropriate.
3421 ///
3422 /// Tentative definition rules (C99 6.9.2p2) are checked by
3423 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3424 /// definitions here, since the initializer hasn't been attached.
3425 ///
3426 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3427   // If the new decl is already invalid, don't do any other checking.
3428   if (New->isInvalidDecl())
3429     return;
3430
3431   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3432     return;
3433
3434   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3435
3436   // Verify the old decl was also a variable or variable template.
3437   VarDecl *Old = nullptr;
3438   VarTemplateDecl *OldTemplate = nullptr;
3439   if (Previous.isSingleResult()) {
3440     if (NewTemplate) {
3441       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3442       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3443
3444       if (auto *Shadow =
3445               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3446         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3447           return New->setInvalidDecl();
3448     } else {
3449       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3450
3451       if (auto *Shadow =
3452               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3453         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3454           return New->setInvalidDecl();
3455     }
3456   }
3457   if (!Old) {
3458     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3459       << New->getDeclName();
3460     Diag(Previous.getRepresentativeDecl()->getLocation(),
3461          diag::note_previous_definition);
3462     return New->setInvalidDecl();
3463   }
3464
3465   // Ensure the template parameters are compatible.
3466   if (NewTemplate &&
3467       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3468                                       OldTemplate->getTemplateParameters(),
3469                                       /*Complain=*/true, TPL_TemplateMatch))
3470     return New->setInvalidDecl();
3471
3472   // C++ [class.mem]p1:
3473   //   A member shall not be declared twice in the member-specification [...]
3474   //
3475   // Here, we need only consider static data members.
3476   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3477     Diag(New->getLocation(), diag::err_duplicate_member)
3478       << New->getIdentifier();
3479     Diag(Old->getLocation(), diag::note_previous_declaration);
3480     New->setInvalidDecl();
3481   }
3482
3483   mergeDeclAttributes(New, Old);
3484   // Warn if an already-declared variable is made a weak_import in a subsequent
3485   // declaration
3486   if (New->hasAttr<WeakImportAttr>() &&
3487       Old->getStorageClass() == SC_None &&
3488       !Old->hasAttr<WeakImportAttr>()) {
3489     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3490     Diag(Old->getLocation(), diag::note_previous_definition);
3491     // Remove weak_import attribute on new declaration.
3492     New->dropAttr<WeakImportAttr>();
3493   }
3494
3495   if (New->hasAttr<InternalLinkageAttr>() &&
3496       !Old->hasAttr<InternalLinkageAttr>()) {
3497     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3498         << New->getDeclName();
3499     Diag(Old->getLocation(), diag::note_previous_definition);
3500     New->dropAttr<InternalLinkageAttr>();
3501   }
3502
3503   // Merge the types.
3504   VarDecl *MostRecent = Old->getMostRecentDecl();
3505   if (MostRecent != Old) {
3506     MergeVarDeclTypes(New, MostRecent,
3507                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3508     if (New->isInvalidDecl())
3509       return;
3510   }
3511
3512   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3513   if (New->isInvalidDecl())
3514     return;
3515
3516   diag::kind PrevDiag;
3517   SourceLocation OldLocation;
3518   std::tie(PrevDiag, OldLocation) =
3519       getNoteDiagForInvalidRedeclaration(Old, New);
3520
3521   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3522   if (New->getStorageClass() == SC_Static &&
3523       !New->isStaticDataMember() &&
3524       Old->hasExternalFormalLinkage()) {
3525     if (getLangOpts().MicrosoftExt) {
3526       Diag(New->getLocation(), diag::ext_static_non_static)
3527           << New->getDeclName();
3528       Diag(OldLocation, PrevDiag);
3529     } else {
3530       Diag(New->getLocation(), diag::err_static_non_static)
3531           << New->getDeclName();
3532       Diag(OldLocation, PrevDiag);
3533       return New->setInvalidDecl();
3534     }
3535   }
3536   // C99 6.2.2p4:
3537   //   For an identifier declared with the storage-class specifier
3538   //   extern in a scope in which a prior declaration of that
3539   //   identifier is visible,23) if the prior declaration specifies
3540   //   internal or external linkage, the linkage of the identifier at
3541   //   the later declaration is the same as the linkage specified at
3542   //   the prior declaration. If no prior declaration is visible, or
3543   //   if the prior declaration specifies no linkage, then the
3544   //   identifier has external linkage.
3545   if (New->hasExternalStorage() && Old->hasLinkage())
3546     /* Okay */;
3547   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3548            !New->isStaticDataMember() &&
3549            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3550     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3551     Diag(OldLocation, PrevDiag);
3552     return New->setInvalidDecl();
3553   }
3554
3555   // Check if extern is followed by non-extern and vice-versa.
3556   if (New->hasExternalStorage() &&
3557       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3558     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3559     Diag(OldLocation, PrevDiag);
3560     return New->setInvalidDecl();
3561   }
3562   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3563       !New->hasExternalStorage()) {
3564     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3565     Diag(OldLocation, PrevDiag);
3566     return New->setInvalidDecl();
3567   }
3568
3569   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3570
3571   // FIXME: The test for external storage here seems wrong? We still
3572   // need to check for mismatches.
3573   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3574       // Don't complain about out-of-line definitions of static members.
3575       !(Old->getLexicalDeclContext()->isRecord() &&
3576         !New->getLexicalDeclContext()->isRecord())) {
3577     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3578     Diag(OldLocation, PrevDiag);
3579     return New->setInvalidDecl();
3580   }
3581
3582   if (New->getTLSKind() != Old->getTLSKind()) {
3583     if (!Old->getTLSKind()) {
3584       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3585       Diag(OldLocation, PrevDiag);
3586     } else if (!New->getTLSKind()) {
3587       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3588       Diag(OldLocation, PrevDiag);
3589     } else {
3590       // Do not allow redeclaration to change the variable between requiring
3591       // static and dynamic initialization.
3592       // FIXME: GCC allows this, but uses the TLS keyword on the first
3593       // declaration to determine the kind. Do we need to be compatible here?
3594       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3595         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3596       Diag(OldLocation, PrevDiag);
3597     }
3598   }
3599
3600   // C++ doesn't have tentative definitions, so go right ahead and check here.
3601   VarDecl *Def;
3602   if (getLangOpts().CPlusPlus &&
3603       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3604       (Def = Old->getDefinition())) {
3605     NamedDecl *Hidden = nullptr;
3606     if (!hasVisibleDefinition(Def, &Hidden) &&
3607         (New->getFormalLinkage() == InternalLinkage ||
3608          New->getDescribedVarTemplate() ||
3609          New->getNumTemplateParameterLists() ||
3610          New->getDeclContext()->isDependentContext())) {
3611       // The previous definition is hidden, and multiple definitions are
3612       // permitted (in separate TUs). Form another definition of it.
3613     } else {
3614       Diag(New->getLocation(), diag::err_redefinition) << New;
3615       Diag(Def->getLocation(), diag::note_previous_definition);
3616       New->setInvalidDecl();
3617       return;
3618     }
3619   }
3620
3621   if (haveIncompatibleLanguageLinkages(Old, New)) {
3622     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3623     Diag(OldLocation, PrevDiag);
3624     New->setInvalidDecl();
3625     return;
3626   }
3627
3628   // Merge "used" flag.
3629   if (Old->getMostRecentDecl()->isUsed(false))
3630     New->setIsUsed();
3631
3632   // Keep a chain of previous declarations.
3633   New->setPreviousDecl(Old);
3634   if (NewTemplate)
3635     NewTemplate->setPreviousDecl(OldTemplate);
3636
3637   // Inherit access appropriately.
3638   New->setAccess(Old->getAccess());
3639   if (NewTemplate)
3640     NewTemplate->setAccess(New->getAccess());
3641 }
3642
3643 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3644 /// no declarator (e.g. "struct foo;") is parsed.
3645 Decl *
3646 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3647                                  RecordDecl *&AnonRecord) {
3648   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3649                                     AnonRecord);
3650 }
3651
3652 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3653 // disambiguate entities defined in different scopes.
3654 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3655 // compatibility.
3656 // We will pick our mangling number depending on which version of MSVC is being
3657 // targeted.
3658 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3659   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3660              ? S->getMSCurManglingNumber()
3661              : S->getMSLastManglingNumber();
3662 }
3663
3664 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3665   if (!Context.getLangOpts().CPlusPlus)
3666     return;
3667
3668   if (isa<CXXRecordDecl>(Tag->getParent())) {
3669     // If this tag is the direct child of a class, number it if
3670     // it is anonymous.
3671     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3672       return;
3673     MangleNumberingContext &MCtx =
3674         Context.getManglingNumberContext(Tag->getParent());
3675     Context.setManglingNumber(
3676         Tag, MCtx.getManglingNumber(
3677                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3678     return;
3679   }
3680
3681   // If this tag isn't a direct child of a class, number it if it is local.
3682   Decl *ManglingContextDecl;
3683   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3684           Tag->getDeclContext(), ManglingContextDecl)) {
3685     Context.setManglingNumber(
3686         Tag, MCtx->getManglingNumber(
3687                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3688   }
3689 }
3690
3691 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3692                                         TypedefNameDecl *NewTD) {
3693   if (TagFromDeclSpec->isInvalidDecl())
3694     return;
3695
3696   // Do nothing if the tag already has a name for linkage purposes.
3697   if (TagFromDeclSpec->hasNameForLinkage())
3698     return;
3699
3700   // A well-formed anonymous tag must always be a TUK_Definition.
3701   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3702
3703   // The type must match the tag exactly;  no qualifiers allowed.
3704   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3705                            Context.getTagDeclType(TagFromDeclSpec))) {
3706     if (getLangOpts().CPlusPlus)
3707       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3708     return;
3709   }
3710
3711   // If we've already computed linkage for the anonymous tag, then
3712   // adding a typedef name for the anonymous decl can change that
3713   // linkage, which might be a serious problem.  Diagnose this as
3714   // unsupported and ignore the typedef name.  TODO: we should
3715   // pursue this as a language defect and establish a formal rule
3716   // for how to handle it.
3717   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3718     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3719
3720     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3721     tagLoc = getLocForEndOfToken(tagLoc);
3722
3723     llvm::SmallString<40> textToInsert;
3724     textToInsert += ' ';
3725     textToInsert += NewTD->getIdentifier()->getName();
3726     Diag(tagLoc, diag::note_typedef_changes_linkage)
3727         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3728     return;
3729   }
3730
3731   // Otherwise, set this is the anon-decl typedef for the tag.
3732   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3733 }
3734
3735 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3736   switch (T) {
3737   case DeclSpec::TST_class:
3738     return 0;
3739   case DeclSpec::TST_struct:
3740     return 1;
3741   case DeclSpec::TST_interface:
3742     return 2;
3743   case DeclSpec::TST_union:
3744     return 3;
3745   case DeclSpec::TST_enum:
3746     return 4;
3747   default:
3748     llvm_unreachable("unexpected type specifier");
3749   }
3750 }
3751
3752 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3753 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3754 /// parameters to cope with template friend declarations.
3755 Decl *
3756 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3757                                  MultiTemplateParamsArg TemplateParams,
3758                                  bool IsExplicitInstantiation,
3759                                  RecordDecl *&AnonRecord) {
3760   Decl *TagD = nullptr;
3761   TagDecl *Tag = nullptr;
3762   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3763       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3764       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3765       DS.getTypeSpecType() == DeclSpec::TST_union ||
3766       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3767     TagD = DS.getRepAsDecl();
3768
3769     if (!TagD) // We probably had an error
3770       return nullptr;
3771
3772     // Note that the above type specs guarantee that the
3773     // type rep is a Decl, whereas in many of the others
3774     // it's a Type.
3775     if (isa<TagDecl>(TagD))
3776       Tag = cast<TagDecl>(TagD);
3777     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3778       Tag = CTD->getTemplatedDecl();
3779   }
3780
3781   if (Tag) {
3782     handleTagNumbering(Tag, S);
3783     Tag->setFreeStanding();
3784     if (Tag->isInvalidDecl())
3785       return Tag;
3786   }
3787
3788   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3789     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3790     // or incomplete types shall not be restrict-qualified."
3791     if (TypeQuals & DeclSpec::TQ_restrict)
3792       Diag(DS.getRestrictSpecLoc(),
3793            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3794            << DS.getSourceRange();
3795   }
3796
3797   if (DS.isConstexprSpecified()) {
3798     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3799     // and definitions of functions and variables.
3800     if (Tag)
3801       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3802           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3803     else
3804       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3805     // Don't emit warnings after this error.
3806     return TagD;
3807   }
3808
3809   if (DS.isConceptSpecified()) {
3810     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3811     // either a function concept and its definition or a variable concept and
3812     // its initializer.
3813     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3814     return TagD;
3815   }
3816
3817   DiagnoseFunctionSpecifiers(DS);
3818
3819   if (DS.isFriendSpecified()) {
3820     // If we're dealing with a decl but not a TagDecl, assume that
3821     // whatever routines created it handled the friendship aspect.
3822     if (TagD && !Tag)
3823       return nullptr;
3824     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3825   }
3826
3827   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3828   bool IsExplicitSpecialization =
3829     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3830   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3831       !IsExplicitInstantiation && !IsExplicitSpecialization &&
3832       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3833     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3834     // nested-name-specifier unless it is an explicit instantiation
3835     // or an explicit specialization.
3836     //
3837     // FIXME: We allow class template partial specializations here too, per the
3838     // obvious intent of DR1819.
3839     //
3840     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3841     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3842         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3843     return nullptr;
3844   }
3845
3846   // Track whether this decl-specifier declares anything.
3847   bool DeclaresAnything = true;
3848
3849   // Handle anonymous struct definitions.
3850   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3851     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3852         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3853       if (getLangOpts().CPlusPlus ||
3854           Record->getDeclContext()->isRecord()) {
3855         // If CurContext is a DeclContext that can contain statements,
3856         // RecursiveASTVisitor won't visit the decls that
3857         // BuildAnonymousStructOrUnion() will put into CurContext.
3858         // Also store them here so that they can be part of the
3859         // DeclStmt that gets created in this case.
3860         // FIXME: Also return the IndirectFieldDecls created by
3861         // BuildAnonymousStructOr union, for the same reason?
3862         if (CurContext->isFunctionOrMethod())
3863           AnonRecord = Record;
3864         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3865                                            Context.getPrintingPolicy());
3866       }
3867
3868       DeclaresAnything = false;
3869     }
3870   }
3871
3872   // C11 6.7.2.1p2:
3873   //   A struct-declaration that does not declare an anonymous structure or
3874   //   anonymous union shall contain a struct-declarator-list.
3875   //
3876   // This rule also existed in C89 and C99; the grammar for struct-declaration
3877   // did not permit a struct-declaration without a struct-declarator-list.
3878   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3879       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3880     // Check for Microsoft C extension: anonymous struct/union member.
3881     // Handle 2 kinds of anonymous struct/union:
3882     //   struct STRUCT;
3883     //   union UNION;
3884     // and
3885     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3886     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3887     if ((Tag && Tag->getDeclName()) ||
3888         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3889       RecordDecl *Record = nullptr;
3890       if (Tag)
3891         Record = dyn_cast<RecordDecl>(Tag);
3892       else if (const RecordType *RT =
3893                    DS.getRepAsType().get()->getAsStructureType())
3894         Record = RT->getDecl();
3895       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3896         Record = UT->getDecl();
3897
3898       if (Record && getLangOpts().MicrosoftExt) {
3899         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3900           << Record->isUnion() << DS.getSourceRange();
3901         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3902       }
3903
3904       DeclaresAnything = false;
3905     }
3906   }
3907
3908   // Skip all the checks below if we have a type error.
3909   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3910       (TagD && TagD->isInvalidDecl()))
3911     return TagD;
3912
3913   if (getLangOpts().CPlusPlus &&
3914       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3915     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3916       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3917           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3918         DeclaresAnything = false;
3919
3920   if (!DS.isMissingDeclaratorOk()) {
3921     // Customize diagnostic for a typedef missing a name.
3922     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3923       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3924         << DS.getSourceRange();
3925     else
3926       DeclaresAnything = false;
3927   }
3928
3929   if (DS.isModulePrivateSpecified() &&
3930       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3931     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3932       << Tag->getTagKind()
3933       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3934
3935   ActOnDocumentableDecl(TagD);
3936
3937   // C 6.7/2:
3938   //   A declaration [...] shall declare at least a declarator [...], a tag,
3939   //   or the members of an enumeration.
3940   // C++ [dcl.dcl]p3:
3941   //   [If there are no declarators], and except for the declaration of an
3942   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3943   //   names into the program, or shall redeclare a name introduced by a
3944   //   previous declaration.
3945   if (!DeclaresAnything) {
3946     // In C, we allow this as a (popular) extension / bug. Don't bother
3947     // producing further diagnostics for redundant qualifiers after this.
3948     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3949     return TagD;
3950   }
3951
3952   // C++ [dcl.stc]p1:
3953   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3954   //   init-declarator-list of the declaration shall not be empty.
3955   // C++ [dcl.fct.spec]p1:
3956   //   If a cv-qualifier appears in a decl-specifier-seq, the
3957   //   init-declarator-list of the declaration shall not be empty.
3958   //
3959   // Spurious qualifiers here appear to be valid in C.
3960   unsigned DiagID = diag::warn_standalone_specifier;
3961   if (getLangOpts().CPlusPlus)
3962     DiagID = diag::ext_standalone_specifier;
3963
3964   // Note that a linkage-specification sets a storage class, but
3965   // 'extern "C" struct foo;' is actually valid and not theoretically
3966   // useless.
3967   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3968     if (SCS == DeclSpec::SCS_mutable)
3969       // Since mutable is not a viable storage class specifier in C, there is
3970       // no reason to treat it as an extension. Instead, diagnose as an error.
3971       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3972     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3973       Diag(DS.getStorageClassSpecLoc(), DiagID)
3974         << DeclSpec::getSpecifierName(SCS);
3975   }
3976
3977   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3978     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3979       << DeclSpec::getSpecifierName(TSCS);
3980   if (DS.getTypeQualifiers()) {
3981     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3982       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3983     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3984       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3985     // Restrict is covered above.
3986     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3987       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3988   }
3989
3990   // Warn about ignored type attributes, for example:
3991   // __attribute__((aligned)) struct A;
3992   // Attributes should be placed after tag to apply to type declaration.
3993   if (!DS.getAttributes().empty()) {
3994     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3995     if (TypeSpecType == DeclSpec::TST_class ||
3996         TypeSpecType == DeclSpec::TST_struct ||
3997         TypeSpecType == DeclSpec::TST_interface ||
3998         TypeSpecType == DeclSpec::TST_union ||
3999         TypeSpecType == DeclSpec::TST_enum) {
4000       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4001            attrs = attrs->getNext())
4002         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4003             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4004     }
4005   }
4006
4007   return TagD;
4008 }
4009
4010 /// We are trying to inject an anonymous member into the given scope;
4011 /// check if there's an existing declaration that can't be overloaded.
4012 ///
4013 /// \return true if this is a forbidden redeclaration
4014 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4015                                          Scope *S,
4016                                          DeclContext *Owner,
4017                                          DeclarationName Name,
4018                                          SourceLocation NameLoc,
4019                                          bool IsUnion) {
4020   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4021                  Sema::ForRedeclaration);
4022   if (!SemaRef.LookupName(R, S)) return false;
4023
4024   // Pick a representative declaration.
4025   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4026   assert(PrevDecl && "Expected a non-null Decl");
4027
4028   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4029     return false;
4030
4031   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4032     << IsUnion << Name;
4033   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4034
4035   return true;
4036 }
4037
4038 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4039 /// anonymous struct or union AnonRecord into the owning context Owner
4040 /// and scope S. This routine will be invoked just after we realize
4041 /// that an unnamed union or struct is actually an anonymous union or
4042 /// struct, e.g.,
4043 ///
4044 /// @code
4045 /// union {
4046 ///   int i;
4047 ///   float f;
4048 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4049 ///    // f into the surrounding scope.x
4050 /// @endcode
4051 ///
4052 /// This routine is recursive, injecting the names of nested anonymous
4053 /// structs/unions into the owning context and scope as well.
4054 static bool
4055 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4056                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4057                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4058   bool Invalid = false;
4059
4060   // Look every FieldDecl and IndirectFieldDecl with a name.
4061   for (auto *D : AnonRecord->decls()) {
4062     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4063         cast<NamedDecl>(D)->getDeclName()) {
4064       ValueDecl *VD = cast<ValueDecl>(D);
4065       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4066                                        VD->getLocation(),
4067                                        AnonRecord->isUnion())) {
4068         // C++ [class.union]p2:
4069         //   The names of the members of an anonymous union shall be
4070         //   distinct from the names of any other entity in the
4071         //   scope in which the anonymous union is declared.
4072         Invalid = true;
4073       } else {
4074         // C++ [class.union]p2:
4075         //   For the purpose of name lookup, after the anonymous union
4076         //   definition, the members of the anonymous union are
4077         //   considered to have been defined in the scope in which the
4078         //   anonymous union is declared.
4079         unsigned OldChainingSize = Chaining.size();
4080         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4081           Chaining.append(IF->chain_begin(), IF->chain_end());
4082         else
4083           Chaining.push_back(VD);
4084
4085         assert(Chaining.size() >= 2);
4086         NamedDecl **NamedChain =
4087           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4088         for (unsigned i = 0; i < Chaining.size(); i++)
4089           NamedChain[i] = Chaining[i];
4090
4091         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4092             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4093             VD->getType(), NamedChain, Chaining.size());
4094
4095         for (const auto *Attr : VD->attrs())
4096           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4097
4098         IndirectField->setAccess(AS);
4099         IndirectField->setImplicit();
4100         SemaRef.PushOnScopeChains(IndirectField, S);
4101
4102         // That includes picking up the appropriate access specifier.
4103         if (AS != AS_none) IndirectField->setAccess(AS);
4104
4105         Chaining.resize(OldChainingSize);
4106       }
4107     }
4108   }
4109
4110   return Invalid;
4111 }
4112
4113 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4114 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4115 /// illegal input values are mapped to SC_None.
4116 static StorageClass
4117 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4118   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4119   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4120          "Parser allowed 'typedef' as storage class VarDecl.");
4121   switch (StorageClassSpec) {
4122   case DeclSpec::SCS_unspecified:    return SC_None;
4123   case DeclSpec::SCS_extern:
4124     if (DS.isExternInLinkageSpec())
4125       return SC_None;
4126     return SC_Extern;
4127   case DeclSpec::SCS_static:         return SC_Static;
4128   case DeclSpec::SCS_auto:           return SC_Auto;
4129   case DeclSpec::SCS_register:       return SC_Register;
4130   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4131     // Illegal SCSs map to None: error reporting is up to the caller.
4132   case DeclSpec::SCS_mutable:        // Fall through.
4133   case DeclSpec::SCS_typedef:        return SC_None;
4134   }
4135   llvm_unreachable("unknown storage class specifier");
4136 }
4137
4138 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4139   assert(Record->hasInClassInitializer());
4140
4141   for (const auto *I : Record->decls()) {
4142     const auto *FD = dyn_cast<FieldDecl>(I);
4143     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4144       FD = IFD->getAnonField();
4145     if (FD && FD->hasInClassInitializer())
4146       return FD->getLocation();
4147   }
4148
4149   llvm_unreachable("couldn't find in-class initializer");
4150 }
4151
4152 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4153                                       SourceLocation DefaultInitLoc) {
4154   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4155     return;
4156
4157   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4158   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4159 }
4160
4161 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4162                                       CXXRecordDecl *AnonUnion) {
4163   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4164     return;
4165
4166   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4167 }
4168
4169 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4170 /// anonymous structure or union. Anonymous unions are a C++ feature
4171 /// (C++ [class.union]) and a C11 feature; anonymous structures
4172 /// are a C11 feature and GNU C++ extension.
4173 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4174                                         AccessSpecifier AS,
4175                                         RecordDecl *Record,
4176                                         const PrintingPolicy &Policy) {
4177   DeclContext *Owner = Record->getDeclContext();
4178
4179   // Diagnose whether this anonymous struct/union is an extension.
4180   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4181     Diag(Record->getLocation(), diag::ext_anonymous_union);
4182   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4183     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4184   else if (!Record->isUnion() && !getLangOpts().C11)
4185     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4186
4187   // C and C++ require different kinds of checks for anonymous
4188   // structs/unions.
4189   bool Invalid = false;
4190   if (getLangOpts().CPlusPlus) {
4191     const char *PrevSpec = nullptr;
4192     unsigned DiagID;
4193     if (Record->isUnion()) {
4194       // C++ [class.union]p6:
4195       //   Anonymous unions declared in a named namespace or in the
4196       //   global namespace shall be declared static.
4197       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4198           (isa<TranslationUnitDecl>(Owner) ||
4199            (isa<NamespaceDecl>(Owner) &&
4200             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4201         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4202           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4203
4204         // Recover by adding 'static'.
4205         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4206                                PrevSpec, DiagID, Policy);
4207       }
4208       // C++ [class.union]p6:
4209       //   A storage class is not allowed in a declaration of an
4210       //   anonymous union in a class scope.
4211       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4212                isa<RecordDecl>(Owner)) {
4213         Diag(DS.getStorageClassSpecLoc(),
4214              diag::err_anonymous_union_with_storage_spec)
4215           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4216
4217         // Recover by removing the storage specifier.
4218         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4219                                SourceLocation(),
4220                                PrevSpec, DiagID, Context.getPrintingPolicy());
4221       }
4222     }
4223
4224     // Ignore const/volatile/restrict qualifiers.
4225     if (DS.getTypeQualifiers()) {
4226       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4227         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4228           << Record->isUnion() << "const"
4229           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4230       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4231         Diag(DS.getVolatileSpecLoc(),
4232              diag::ext_anonymous_struct_union_qualified)
4233           << Record->isUnion() << "volatile"
4234           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4235       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4236         Diag(DS.getRestrictSpecLoc(),
4237              diag::ext_anonymous_struct_union_qualified)
4238           << Record->isUnion() << "restrict"
4239           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4240       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4241         Diag(DS.getAtomicSpecLoc(),
4242              diag::ext_anonymous_struct_union_qualified)
4243           << Record->isUnion() << "_Atomic"
4244           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4245
4246       DS.ClearTypeQualifiers();
4247     }
4248
4249     // C++ [class.union]p2:
4250     //   The member-specification of an anonymous union shall only
4251     //   define non-static data members. [Note: nested types and
4252     //   functions cannot be declared within an anonymous union. ]
4253     for (auto *Mem : Record->decls()) {
4254       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4255         // C++ [class.union]p3:
4256         //   An anonymous union shall not have private or protected
4257         //   members (clause 11).
4258         assert(FD->getAccess() != AS_none);
4259         if (FD->getAccess() != AS_public) {
4260           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4261             << Record->isUnion() << (FD->getAccess() == AS_protected);
4262           Invalid = true;
4263         }
4264
4265         // C++ [class.union]p1
4266         //   An object of a class with a non-trivial constructor, a non-trivial
4267         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4268         //   assignment operator cannot be a member of a union, nor can an
4269         //   array of such objects.
4270         if (CheckNontrivialField(FD))
4271           Invalid = true;
4272       } else if (Mem->isImplicit()) {
4273         // Any implicit members are fine.
4274       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4275         // This is a type that showed up in an
4276         // elaborated-type-specifier inside the anonymous struct or
4277         // union, but which actually declares a type outside of the
4278         // anonymous struct or union. It's okay.
4279       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4280         if (!MemRecord->isAnonymousStructOrUnion() &&
4281             MemRecord->getDeclName()) {
4282           // Visual C++ allows type definition in anonymous struct or union.
4283           if (getLangOpts().MicrosoftExt)
4284             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4285               << Record->isUnion();
4286           else {
4287             // This is a nested type declaration.
4288             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4289               << Record->isUnion();
4290             Invalid = true;
4291           }
4292         } else {
4293           // This is an anonymous type definition within another anonymous type.
4294           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4295           // not part of standard C++.
4296           Diag(MemRecord->getLocation(),
4297                diag::ext_anonymous_record_with_anonymous_type)
4298             << Record->isUnion();
4299         }
4300       } else if (isa<AccessSpecDecl>(Mem)) {
4301         // Any access specifier is fine.
4302       } else if (isa<StaticAssertDecl>(Mem)) {
4303         // In C++1z, static_assert declarations are also fine.
4304       } else {
4305         // We have something that isn't a non-static data
4306         // member. Complain about it.
4307         unsigned DK = diag::err_anonymous_record_bad_member;
4308         if (isa<TypeDecl>(Mem))
4309           DK = diag::err_anonymous_record_with_type;
4310         else if (isa<FunctionDecl>(Mem))
4311           DK = diag::err_anonymous_record_with_function;
4312         else if (isa<VarDecl>(Mem))
4313           DK = diag::err_anonymous_record_with_static;
4314
4315         // Visual C++ allows type definition in anonymous struct or union.
4316         if (getLangOpts().MicrosoftExt &&
4317             DK == diag::err_anonymous_record_with_type)
4318           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4319             << Record->isUnion();
4320         else {
4321           Diag(Mem->getLocation(), DK) << Record->isUnion();
4322           Invalid = true;
4323         }
4324       }
4325     }
4326
4327     // C++11 [class.union]p8 (DR1460):
4328     //   At most one variant member of a union may have a
4329     //   brace-or-equal-initializer.
4330     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4331         Owner->isRecord())
4332       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4333                                 cast<CXXRecordDecl>(Record));
4334   }
4335
4336   if (!Record->isUnion() && !Owner->isRecord()) {
4337     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4338       << getLangOpts().CPlusPlus;
4339     Invalid = true;
4340   }
4341
4342   // Mock up a declarator.
4343   Declarator Dc(DS, Declarator::MemberContext);
4344   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4345   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4346
4347   // Create a declaration for this anonymous struct/union.
4348   NamedDecl *Anon = nullptr;
4349   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4350     Anon = FieldDecl::Create(Context, OwningClass,
4351                              DS.getLocStart(),
4352                              Record->getLocation(),
4353                              /*IdentifierInfo=*/nullptr,
4354                              Context.getTypeDeclType(Record),
4355                              TInfo,
4356                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4357                              /*InitStyle=*/ICIS_NoInit);
4358     Anon->setAccess(AS);
4359     if (getLangOpts().CPlusPlus)
4360       FieldCollector->Add(cast<FieldDecl>(Anon));
4361   } else {
4362     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4363     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4364     if (SCSpec == DeclSpec::SCS_mutable) {
4365       // mutable can only appear on non-static class members, so it's always
4366       // an error here
4367       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4368       Invalid = true;
4369       SC = SC_None;
4370     }
4371
4372     Anon = VarDecl::Create(Context, Owner,
4373                            DS.getLocStart(),
4374                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4375                            Context.getTypeDeclType(Record),
4376                            TInfo, SC);
4377
4378     // Default-initialize the implicit variable. This initialization will be
4379     // trivial in almost all cases, except if a union member has an in-class
4380     // initializer:
4381     //   union { int n = 0; };
4382     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4383   }
4384   Anon->setImplicit();
4385
4386   // Mark this as an anonymous struct/union type.
4387   Record->setAnonymousStructOrUnion(true);
4388
4389   // Add the anonymous struct/union object to the current
4390   // context. We'll be referencing this object when we refer to one of
4391   // its members.
4392   Owner->addDecl(Anon);
4393
4394   // Inject the members of the anonymous struct/union into the owning
4395   // context and into the identifier resolver chain for name lookup
4396   // purposes.
4397   SmallVector<NamedDecl*, 2> Chain;
4398   Chain.push_back(Anon);
4399
4400   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4401     Invalid = true;
4402
4403   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4404     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4405       Decl *ManglingContextDecl;
4406       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4407               NewVD->getDeclContext(), ManglingContextDecl)) {
4408         Context.setManglingNumber(
4409             NewVD, MCtx->getManglingNumber(
4410                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4411         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4412       }
4413     }
4414   }
4415
4416   if (Invalid)
4417     Anon->setInvalidDecl();
4418
4419   return Anon;
4420 }
4421
4422 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4423 /// Microsoft C anonymous structure.
4424 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4425 /// Example:
4426 ///
4427 /// struct A { int a; };
4428 /// struct B { struct A; int b; };
4429 ///
4430 /// void foo() {
4431 ///   B var;
4432 ///   var.a = 3;
4433 /// }
4434 ///
4435 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4436                                            RecordDecl *Record) {
4437   assert(Record && "expected a record!");
4438
4439   // Mock up a declarator.
4440   Declarator Dc(DS, Declarator::TypeNameContext);
4441   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4442   assert(TInfo && "couldn't build declarator info for anonymous struct");
4443
4444   auto *ParentDecl = cast<RecordDecl>(CurContext);
4445   QualType RecTy = Context.getTypeDeclType(Record);
4446
4447   // Create a declaration for this anonymous struct.
4448   NamedDecl *Anon = FieldDecl::Create(Context,
4449                              ParentDecl,
4450                              DS.getLocStart(),
4451                              DS.getLocStart(),
4452                              /*IdentifierInfo=*/nullptr,
4453                              RecTy,
4454                              TInfo,
4455                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4456                              /*InitStyle=*/ICIS_NoInit);
4457   Anon->setImplicit();
4458
4459   // Add the anonymous struct object to the current context.
4460   CurContext->addDecl(Anon);
4461
4462   // Inject the members of the anonymous struct into the current
4463   // context and into the identifier resolver chain for name lookup
4464   // purposes.
4465   SmallVector<NamedDecl*, 2> Chain;
4466   Chain.push_back(Anon);
4467
4468   RecordDecl *RecordDef = Record->getDefinition();
4469   if (RequireCompleteType(Anon->getLocation(), RecTy,
4470                           diag::err_field_incomplete) ||
4471       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4472                                           AS_none, Chain)) {
4473     Anon->setInvalidDecl();
4474     ParentDecl->setInvalidDecl();
4475   }
4476
4477   return Anon;
4478 }
4479
4480 /// GetNameForDeclarator - Determine the full declaration name for the
4481 /// given Declarator.
4482 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4483   return GetNameFromUnqualifiedId(D.getName());
4484 }
4485
4486 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4487 DeclarationNameInfo
4488 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4489   DeclarationNameInfo NameInfo;
4490   NameInfo.setLoc(Name.StartLocation);
4491
4492   switch (Name.getKind()) {
4493
4494   case UnqualifiedId::IK_ImplicitSelfParam:
4495   case UnqualifiedId::IK_Identifier:
4496     NameInfo.setName(Name.Identifier);
4497     NameInfo.setLoc(Name.StartLocation);
4498     return NameInfo;
4499
4500   case UnqualifiedId::IK_OperatorFunctionId:
4501     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4502                                            Name.OperatorFunctionId.Operator));
4503     NameInfo.setLoc(Name.StartLocation);
4504     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4505       = Name.OperatorFunctionId.SymbolLocations[0];
4506     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4507       = Name.EndLocation.getRawEncoding();
4508     return NameInfo;
4509
4510   case UnqualifiedId::IK_LiteralOperatorId:
4511     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4512                                                            Name.Identifier));
4513     NameInfo.setLoc(Name.StartLocation);
4514     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4515     return NameInfo;
4516
4517   case UnqualifiedId::IK_ConversionFunctionId: {
4518     TypeSourceInfo *TInfo;
4519     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4520     if (Ty.isNull())
4521       return DeclarationNameInfo();
4522     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4523                                                Context.getCanonicalType(Ty)));
4524     NameInfo.setLoc(Name.StartLocation);
4525     NameInfo.setNamedTypeInfo(TInfo);
4526     return NameInfo;
4527   }
4528
4529   case UnqualifiedId::IK_ConstructorName: {
4530     TypeSourceInfo *TInfo;
4531     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4532     if (Ty.isNull())
4533       return DeclarationNameInfo();
4534     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4535                                               Context.getCanonicalType(Ty)));
4536     NameInfo.setLoc(Name.StartLocation);
4537     NameInfo.setNamedTypeInfo(TInfo);
4538     return NameInfo;
4539   }
4540
4541   case UnqualifiedId::IK_ConstructorTemplateId: {
4542     // In well-formed code, we can only have a constructor
4543     // template-id that refers to the current context, so go there
4544     // to find the actual type being constructed.
4545     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4546     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4547       return DeclarationNameInfo();
4548
4549     // Determine the type of the class being constructed.
4550     QualType CurClassType = Context.getTypeDeclType(CurClass);
4551
4552     // FIXME: Check two things: that the template-id names the same type as
4553     // CurClassType, and that the template-id does not occur when the name
4554     // was qualified.
4555
4556     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4557                                     Context.getCanonicalType(CurClassType)));
4558     NameInfo.setLoc(Name.StartLocation);
4559     // FIXME: should we retrieve TypeSourceInfo?
4560     NameInfo.setNamedTypeInfo(nullptr);
4561     return NameInfo;
4562   }
4563
4564   case UnqualifiedId::IK_DestructorName: {
4565     TypeSourceInfo *TInfo;
4566     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4567     if (Ty.isNull())
4568       return DeclarationNameInfo();
4569     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4570                                               Context.getCanonicalType(Ty)));
4571     NameInfo.setLoc(Name.StartLocation);
4572     NameInfo.setNamedTypeInfo(TInfo);
4573     return NameInfo;
4574   }
4575
4576   case UnqualifiedId::IK_TemplateId: {
4577     TemplateName TName = Name.TemplateId->Template.get();
4578     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4579     return Context.getNameForTemplate(TName, TNameLoc);
4580   }
4581
4582   } // switch (Name.getKind())
4583
4584   llvm_unreachable("Unknown name kind");
4585 }
4586
4587 static QualType getCoreType(QualType Ty) {
4588   do {
4589     if (Ty->isPointerType() || Ty->isReferenceType())
4590       Ty = Ty->getPointeeType();
4591     else if (Ty->isArrayType())
4592       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4593     else
4594       return Ty.withoutLocalFastQualifiers();
4595   } while (true);
4596 }
4597
4598 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4599 /// and Definition have "nearly" matching parameters. This heuristic is
4600 /// used to improve diagnostics in the case where an out-of-line function
4601 /// definition doesn't match any declaration within the class or namespace.
4602 /// Also sets Params to the list of indices to the parameters that differ
4603 /// between the declaration and the definition. If hasSimilarParameters
4604 /// returns true and Params is empty, then all of the parameters match.
4605 static bool hasSimilarParameters(ASTContext &Context,
4606                                      FunctionDecl *Declaration,
4607                                      FunctionDecl *Definition,
4608                                      SmallVectorImpl<unsigned> &Params) {
4609   Params.clear();
4610   if (Declaration->param_size() != Definition->param_size())
4611     return false;
4612   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4613     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4614     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4615
4616     // The parameter types are identical
4617     if (Context.hasSameType(DefParamTy, DeclParamTy))
4618       continue;
4619
4620     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4621     QualType DefParamBaseTy = getCoreType(DefParamTy);
4622     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4623     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4624
4625     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4626         (DeclTyName && DeclTyName == DefTyName))
4627       Params.push_back(Idx);
4628     else  // The two parameters aren't even close
4629       return false;
4630   }
4631
4632   return true;
4633 }
4634
4635 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4636 /// declarator needs to be rebuilt in the current instantiation.
4637 /// Any bits of declarator which appear before the name are valid for
4638 /// consideration here.  That's specifically the type in the decl spec
4639 /// and the base type in any member-pointer chunks.
4640 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4641                                                     DeclarationName Name) {
4642   // The types we specifically need to rebuild are:
4643   //   - typenames, typeofs, and decltypes
4644   //   - types which will become injected class names
4645   // Of course, we also need to rebuild any type referencing such a
4646   // type.  It's safest to just say "dependent", but we call out a
4647   // few cases here.
4648
4649   DeclSpec &DS = D.getMutableDeclSpec();
4650   switch (DS.getTypeSpecType()) {
4651   case DeclSpec::TST_typename:
4652   case DeclSpec::TST_typeofType:
4653   case DeclSpec::TST_underlyingType:
4654   case DeclSpec::TST_atomic: {
4655     // Grab the type from the parser.
4656     TypeSourceInfo *TSI = nullptr;
4657     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4658     if (T.isNull() || !T->isDependentType()) break;
4659
4660     // Make sure there's a type source info.  This isn't really much
4661     // of a waste; most dependent types should have type source info
4662     // attached already.
4663     if (!TSI)
4664       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4665
4666     // Rebuild the type in the current instantiation.
4667     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4668     if (!TSI) return true;
4669
4670     // Store the new type back in the decl spec.
4671     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4672     DS.UpdateTypeRep(LocType);
4673     break;
4674   }
4675
4676   case DeclSpec::TST_decltype:
4677   case DeclSpec::TST_typeofExpr: {
4678     Expr *E = DS.getRepAsExpr();
4679     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4680     if (Result.isInvalid()) return true;
4681     DS.UpdateExprRep(Result.get());
4682     break;
4683   }
4684
4685   default:
4686     // Nothing to do for these decl specs.
4687     break;
4688   }
4689
4690   // It doesn't matter what order we do this in.
4691   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4692     DeclaratorChunk &Chunk = D.getTypeObject(I);
4693
4694     // The only type information in the declarator which can come
4695     // before the declaration name is the base type of a member
4696     // pointer.
4697     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4698       continue;
4699
4700     // Rebuild the scope specifier in-place.
4701     CXXScopeSpec &SS = Chunk.Mem.Scope();
4702     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4703       return true;
4704   }
4705
4706   return false;
4707 }
4708
4709 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4710   D.setFunctionDefinitionKind(FDK_Declaration);
4711   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4712
4713   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4714       Dcl && Dcl->getDeclContext()->isFileContext())
4715     Dcl->setTopLevelDeclInObjCContainer();
4716
4717   return Dcl;
4718 }
4719
4720 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4721 ///   If T is the name of a class, then each of the following shall have a
4722 ///   name different from T:
4723 ///     - every static data member of class T;
4724 ///     - every member function of class T
4725 ///     - every member of class T that is itself a type;
4726 /// \returns true if the declaration name violates these rules.
4727 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4728                                    DeclarationNameInfo NameInfo) {
4729   DeclarationName Name = NameInfo.getName();
4730
4731   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4732   while (Record && Record->isAnonymousStructOrUnion())
4733     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4734   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4735     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4736     return true;
4737   }
4738
4739   return false;
4740 }
4741
4742 /// \brief Diagnose a declaration whose declarator-id has the given
4743 /// nested-name-specifier.
4744 ///
4745 /// \param SS The nested-name-specifier of the declarator-id.
4746 ///
4747 /// \param DC The declaration context to which the nested-name-specifier
4748 /// resolves.
4749 ///
4750 /// \param Name The name of the entity being declared.
4751 ///
4752 /// \param Loc The location of the name of the entity being declared.
4753 ///
4754 /// \returns true if we cannot safely recover from this error, false otherwise.
4755 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4756                                         DeclarationName Name,
4757                                         SourceLocation Loc) {
4758   DeclContext *Cur = CurContext;
4759   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4760     Cur = Cur->getParent();
4761
4762   // If the user provided a superfluous scope specifier that refers back to the
4763   // class in which the entity is already declared, diagnose and ignore it.
4764   //
4765   // class X {
4766   //   void X::f();
4767   // };
4768   //
4769   // Note, it was once ill-formed to give redundant qualification in all
4770   // contexts, but that rule was removed by DR482.
4771   if (Cur->Equals(DC)) {
4772     if (Cur->isRecord()) {
4773       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4774                                       : diag::err_member_extra_qualification)
4775         << Name << FixItHint::CreateRemoval(SS.getRange());
4776       SS.clear();
4777     } else {
4778       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4779     }
4780     return false;
4781   }
4782
4783   // Check whether the qualifying scope encloses the scope of the original
4784   // declaration.
4785   if (!Cur->Encloses(DC)) {
4786     if (Cur->isRecord())
4787       Diag(Loc, diag::err_member_qualification)
4788         << Name << SS.getRange();
4789     else if (isa<TranslationUnitDecl>(DC))
4790       Diag(Loc, diag::err_invalid_declarator_global_scope)
4791         << Name << SS.getRange();
4792     else if (isa<FunctionDecl>(Cur))
4793       Diag(Loc, diag::err_invalid_declarator_in_function)
4794         << Name << SS.getRange();
4795     else if (isa<BlockDecl>(Cur))
4796       Diag(Loc, diag::err_invalid_declarator_in_block)
4797         << Name << SS.getRange();
4798     else
4799       Diag(Loc, diag::err_invalid_declarator_scope)
4800       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4801
4802     return true;
4803   }
4804
4805   if (Cur->isRecord()) {
4806     // Cannot qualify members within a class.
4807     Diag(Loc, diag::err_member_qualification)
4808       << Name << SS.getRange();
4809     SS.clear();
4810
4811     // C++ constructors and destructors with incorrect scopes can break
4812     // our AST invariants by having the wrong underlying types. If
4813     // that's the case, then drop this declaration entirely.
4814     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4815          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4816         !Context.hasSameType(Name.getCXXNameType(),
4817                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4818       return true;
4819
4820     return false;
4821   }
4822
4823   // C++11 [dcl.meaning]p1:
4824   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4825   //   not begin with a decltype-specifer"
4826   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4827   while (SpecLoc.getPrefix())
4828     SpecLoc = SpecLoc.getPrefix();
4829   if (dyn_cast_or_null<DecltypeType>(
4830         SpecLoc.getNestedNameSpecifier()->getAsType()))
4831     Diag(Loc, diag::err_decltype_in_declarator)
4832       << SpecLoc.getTypeLoc().getSourceRange();
4833
4834   return false;
4835 }
4836
4837 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4838                                   MultiTemplateParamsArg TemplateParamLists) {
4839   // TODO: consider using NameInfo for diagnostic.
4840   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4841   DeclarationName Name = NameInfo.getName();
4842
4843   // All of these full declarators require an identifier.  If it doesn't have
4844   // one, the ParsedFreeStandingDeclSpec action should be used.
4845   if (!Name) {
4846     if (!D.isInvalidType())  // Reject this if we think it is valid.
4847       Diag(D.getDeclSpec().getLocStart(),
4848            diag::err_declarator_need_ident)
4849         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4850     return nullptr;
4851   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4852     return nullptr;
4853
4854   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4855   // we find one that is.
4856   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4857          (S->getFlags() & Scope::TemplateParamScope) != 0)
4858     S = S->getParent();
4859
4860   DeclContext *DC = CurContext;
4861   if (D.getCXXScopeSpec().isInvalid())
4862     D.setInvalidType();
4863   else if (D.getCXXScopeSpec().isSet()) {
4864     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4865                                         UPPC_DeclarationQualifier))
4866       return nullptr;
4867
4868     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4869     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4870     if (!DC || isa<EnumDecl>(DC)) {
4871       // If we could not compute the declaration context, it's because the
4872       // declaration context is dependent but does not refer to a class,
4873       // class template, or class template partial specialization. Complain
4874       // and return early, to avoid the coming semantic disaster.
4875       Diag(D.getIdentifierLoc(),
4876            diag::err_template_qualified_declarator_no_match)
4877         << D.getCXXScopeSpec().getScopeRep()
4878         << D.getCXXScopeSpec().getRange();
4879       return nullptr;
4880     }
4881     bool IsDependentContext = DC->isDependentContext();
4882
4883     if (!IsDependentContext &&
4884         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4885       return nullptr;
4886
4887     // If a class is incomplete, do not parse entities inside it.
4888     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4889       Diag(D.getIdentifierLoc(),
4890            diag::err_member_def_undefined_record)
4891         << Name << DC << D.getCXXScopeSpec().getRange();
4892       return nullptr;
4893     }
4894     if (!D.getDeclSpec().isFriendSpecified()) {
4895       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4896                                       Name, D.getIdentifierLoc())) {
4897         if (DC->isRecord())
4898           return nullptr;
4899
4900         D.setInvalidType();
4901       }
4902     }
4903
4904     // Check whether we need to rebuild the type of the given
4905     // declaration in the current instantiation.
4906     if (EnteringContext && IsDependentContext &&
4907         TemplateParamLists.size() != 0) {
4908       ContextRAII SavedContext(*this, DC);
4909       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4910         D.setInvalidType();
4911     }
4912   }
4913
4914   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4915   QualType R = TInfo->getType();
4916
4917   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4918     // If this is a typedef, we'll end up spewing multiple diagnostics.
4919     // Just return early; it's safer. If this is a function, let the
4920     // "constructor cannot have a return type" diagnostic handle it.
4921     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4922       return nullptr;
4923
4924   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4925                                       UPPC_DeclarationType))
4926     D.setInvalidType();
4927
4928   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4929                         ForRedeclaration);
4930
4931   // See if this is a redefinition of a variable in the same scope.
4932   if (!D.getCXXScopeSpec().isSet()) {
4933     bool IsLinkageLookup = false;
4934     bool CreateBuiltins = false;
4935
4936     // If the declaration we're planning to build will be a function
4937     // or object with linkage, then look for another declaration with
4938     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4939     //
4940     // If the declaration we're planning to build will be declared with
4941     // external linkage in the translation unit, create any builtin with
4942     // the same name.
4943     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4944       /* Do nothing*/;
4945     else if (CurContext->isFunctionOrMethod() &&
4946              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4947               R->isFunctionType())) {
4948       IsLinkageLookup = true;
4949       CreateBuiltins =
4950           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4951     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4952                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4953       CreateBuiltins = true;
4954
4955     if (IsLinkageLookup)
4956       Previous.clear(LookupRedeclarationWithLinkage);
4957
4958     LookupName(Previous, S, CreateBuiltins);
4959   } else { // Something like "int foo::x;"
4960     LookupQualifiedName(Previous, DC);
4961
4962     // C++ [dcl.meaning]p1:
4963     //   When the declarator-id is qualified, the declaration shall refer to a
4964     //  previously declared member of the class or namespace to which the
4965     //  qualifier refers (or, in the case of a namespace, of an element of the
4966     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4967     //  thereof; [...]
4968     //
4969     // Note that we already checked the context above, and that we do not have
4970     // enough information to make sure that Previous contains the declaration
4971     // we want to match. For example, given:
4972     //
4973     //   class X {
4974     //     void f();
4975     //     void f(float);
4976     //   };
4977     //
4978     //   void X::f(int) { } // ill-formed
4979     //
4980     // In this case, Previous will point to the overload set
4981     // containing the two f's declared in X, but neither of them
4982     // matches.
4983
4984     // C++ [dcl.meaning]p1:
4985     //   [...] the member shall not merely have been introduced by a
4986     //   using-declaration in the scope of the class or namespace nominated by
4987     //   the nested-name-specifier of the declarator-id.
4988     RemoveUsingDecls(Previous);
4989   }
4990
4991   if (Previous.isSingleResult() &&
4992       Previous.getFoundDecl()->isTemplateParameter()) {
4993     // Maybe we will complain about the shadowed template parameter.
4994     if (!D.isInvalidType())
4995       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4996                                       Previous.getFoundDecl());
4997
4998     // Just pretend that we didn't see the previous declaration.
4999     Previous.clear();
5000   }
5001
5002   // In C++, the previous declaration we find might be a tag type
5003   // (class or enum). In this case, the new declaration will hide the
5004   // tag type. Note that this does does not apply if we're declaring a
5005   // typedef (C++ [dcl.typedef]p4).
5006   if (Previous.isSingleTagDecl() &&
5007       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5008     Previous.clear();
5009
5010   // Check that there are no default arguments other than in the parameters
5011   // of a function declaration (C++ only).
5012   if (getLangOpts().CPlusPlus)
5013     CheckExtraCXXDefaultArguments(D);
5014
5015   if (D.getDeclSpec().isConceptSpecified()) {
5016     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5017     // applied only to the definition of a function template or variable
5018     // template, declared in namespace scope
5019     if (!TemplateParamLists.size()) {
5020       Diag(D.getDeclSpec().getConceptSpecLoc(),
5021            diag:: err_concept_wrong_decl_kind);
5022       return nullptr;
5023     }
5024
5025     if (!DC->getRedeclContext()->isFileContext()) {
5026       Diag(D.getIdentifierLoc(),
5027            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5028       return nullptr;
5029     }
5030   }
5031
5032   NamedDecl *New;
5033
5034   bool AddToScope = true;
5035   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5036     if (TemplateParamLists.size()) {
5037       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5038       return nullptr;
5039     }
5040
5041     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5042   } else if (R->isFunctionType()) {
5043     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5044                                   TemplateParamLists,
5045                                   AddToScope);
5046   } else {
5047     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5048                                   AddToScope);
5049   }
5050
5051   if (!New)
5052     return nullptr;
5053
5054   // If this has an identifier and is not an invalid redeclaration or
5055   // function template specialization, add it to the scope stack.
5056   if (New->getDeclName() && AddToScope &&
5057        !(D.isRedeclaration() && New->isInvalidDecl())) {
5058     // Only make a locally-scoped extern declaration visible if it is the first
5059     // declaration of this entity. Qualified lookup for such an entity should
5060     // only find this declaration if there is no visible declaration of it.
5061     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5062     PushOnScopeChains(New, S, AddToContext);
5063     if (!AddToContext)
5064       CurContext->addHiddenDecl(New);
5065   }
5066
5067   if (isInOpenMPDeclareTargetContext())
5068     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5069
5070   return New;
5071 }
5072
5073 /// Helper method to turn variable array types into constant array
5074 /// types in certain situations which would otherwise be errors (for
5075 /// GCC compatibility).
5076 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5077                                                     ASTContext &Context,
5078                                                     bool &SizeIsNegative,
5079                                                     llvm::APSInt &Oversized) {
5080   // This method tries to turn a variable array into a constant
5081   // array even when the size isn't an ICE.  This is necessary
5082   // for compatibility with code that depends on gcc's buggy
5083   // constant expression folding, like struct {char x[(int)(char*)2];}
5084   SizeIsNegative = false;
5085   Oversized = 0;
5086
5087   if (T->isDependentType())
5088     return QualType();
5089
5090   QualifierCollector Qs;
5091   const Type *Ty = Qs.strip(T);
5092
5093   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5094     QualType Pointee = PTy->getPointeeType();
5095     QualType FixedType =
5096         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5097                                             Oversized);
5098     if (FixedType.isNull()) return FixedType;
5099     FixedType = Context.getPointerType(FixedType);
5100     return Qs.apply(Context, FixedType);
5101   }
5102   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5103     QualType Inner = PTy->getInnerType();
5104     QualType FixedType =
5105         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5106                                             Oversized);
5107     if (FixedType.isNull()) return FixedType;
5108     FixedType = Context.getParenType(FixedType);
5109     return Qs.apply(Context, FixedType);
5110   }
5111
5112   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5113   if (!VLATy)
5114     return QualType();
5115   // FIXME: We should probably handle this case
5116   if (VLATy->getElementType()->isVariablyModifiedType())
5117     return QualType();
5118
5119   llvm::APSInt Res;
5120   if (!VLATy->getSizeExpr() ||
5121       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5122     return QualType();
5123
5124   // Check whether the array size is negative.
5125   if (Res.isSigned() && Res.isNegative()) {
5126     SizeIsNegative = true;
5127     return QualType();
5128   }
5129
5130   // Check whether the array is too large to be addressed.
5131   unsigned ActiveSizeBits
5132     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5133                                               Res);
5134   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5135     Oversized = Res;
5136     return QualType();
5137   }
5138
5139   return Context.getConstantArrayType(VLATy->getElementType(),
5140                                       Res, ArrayType::Normal, 0);
5141 }
5142
5143 static void
5144 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5145   SrcTL = SrcTL.getUnqualifiedLoc();
5146   DstTL = DstTL.getUnqualifiedLoc();
5147   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5148     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5149     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5150                                       DstPTL.getPointeeLoc());
5151     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5152     return;
5153   }
5154   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5155     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5156     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5157                                       DstPTL.getInnerLoc());
5158     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5159     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5160     return;
5161   }
5162   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5163   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5164   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5165   TypeLoc DstElemTL = DstATL.getElementLoc();
5166   DstElemTL.initializeFullCopy(SrcElemTL);
5167   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5168   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5169   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5170 }
5171
5172 /// Helper method to turn variable array types into constant array
5173 /// types in certain situations which would otherwise be errors (for
5174 /// GCC compatibility).
5175 static TypeSourceInfo*
5176 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5177                                               ASTContext &Context,
5178                                               bool &SizeIsNegative,
5179                                               llvm::APSInt &Oversized) {
5180   QualType FixedTy
5181     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5182                                           SizeIsNegative, Oversized);
5183   if (FixedTy.isNull())
5184     return nullptr;
5185   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5186   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5187                                     FixedTInfo->getTypeLoc());
5188   return FixedTInfo;
5189 }
5190
5191 /// \brief Register the given locally-scoped extern "C" declaration so
5192 /// that it can be found later for redeclarations. We include any extern "C"
5193 /// declaration that is not visible in the translation unit here, not just
5194 /// function-scope declarations.
5195 void
5196 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5197   if (!getLangOpts().CPlusPlus &&
5198       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5199     // Don't need to track declarations in the TU in C.
5200     return;
5201
5202   // Note that we have a locally-scoped external with this name.
5203   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5204 }
5205
5206 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5207   // FIXME: We can have multiple results via __attribute__((overloadable)).
5208   auto Result = Context.getExternCContextDecl()->lookup(Name);
5209   return Result.empty() ? nullptr : *Result.begin();
5210 }
5211
5212 /// \brief Diagnose function specifiers on a declaration of an identifier that
5213 /// does not identify a function.
5214 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5215   // FIXME: We should probably indicate the identifier in question to avoid
5216   // confusion for constructs like "inline int a(), b;"
5217   if (DS.isInlineSpecified())
5218     Diag(DS.getInlineSpecLoc(),
5219          diag::err_inline_non_function);
5220
5221   if (DS.isVirtualSpecified())
5222     Diag(DS.getVirtualSpecLoc(),
5223          diag::err_virtual_non_function);
5224
5225   if (DS.isExplicitSpecified())
5226     Diag(DS.getExplicitSpecLoc(),
5227          diag::err_explicit_non_function);
5228
5229   if (DS.isNoreturnSpecified())
5230     Diag(DS.getNoreturnSpecLoc(),
5231          diag::err_noreturn_non_function);
5232 }
5233
5234 NamedDecl*
5235 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5236                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5237   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5238   if (D.getCXXScopeSpec().isSet()) {
5239     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5240       << D.getCXXScopeSpec().getRange();
5241     D.setInvalidType();
5242     // Pretend we didn't see the scope specifier.
5243     DC = CurContext;
5244     Previous.clear();
5245   }
5246
5247   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5248
5249   if (D.getDeclSpec().isConstexprSpecified())
5250     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5251       << 1;
5252   if (D.getDeclSpec().isConceptSpecified())
5253     Diag(D.getDeclSpec().getConceptSpecLoc(),
5254          diag::err_concept_wrong_decl_kind);
5255
5256   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5257     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5258       << D.getName().getSourceRange();
5259     return nullptr;
5260   }
5261
5262   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5263   if (!NewTD) return nullptr;
5264
5265   // Handle attributes prior to checking for duplicates in MergeVarDecl
5266   ProcessDeclAttributes(S, NewTD, D);
5267
5268   CheckTypedefForVariablyModifiedType(S, NewTD);
5269
5270   bool Redeclaration = D.isRedeclaration();
5271   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5272   D.setRedeclaration(Redeclaration);
5273   return ND;
5274 }
5275
5276 void
5277 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5278   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5279   // then it shall have block scope.
5280   // Note that variably modified types must be fixed before merging the decl so
5281   // that redeclarations will match.
5282   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5283   QualType T = TInfo->getType();
5284   if (T->isVariablyModifiedType()) {
5285     getCurFunction()->setHasBranchProtectedScope();
5286
5287     if (S->getFnParent() == nullptr) {
5288       bool SizeIsNegative;
5289       llvm::APSInt Oversized;
5290       TypeSourceInfo *FixedTInfo =
5291         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5292                                                       SizeIsNegative,
5293                                                       Oversized);
5294       if (FixedTInfo) {
5295         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5296         NewTD->setTypeSourceInfo(FixedTInfo);
5297       } else {
5298         if (SizeIsNegative)
5299           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5300         else if (T->isVariableArrayType())
5301           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5302         else if (Oversized.getBoolValue())
5303           Diag(NewTD->getLocation(), diag::err_array_too_large)
5304             << Oversized.toString(10);
5305         else
5306           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5307         NewTD->setInvalidDecl();
5308       }
5309     }
5310   }
5311 }
5312
5313 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5314 /// declares a typedef-name, either using the 'typedef' type specifier or via
5315 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5316 NamedDecl*
5317 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5318                            LookupResult &Previous, bool &Redeclaration) {
5319   // Merge the decl with the existing one if appropriate. If the decl is
5320   // in an outer scope, it isn't the same thing.
5321   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5322                        /*AllowInlineNamespace*/false);
5323   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5324   if (!Previous.empty()) {
5325     Redeclaration = true;
5326     MergeTypedefNameDecl(S, NewTD, Previous);
5327   }
5328
5329   // If this is the C FILE type, notify the AST context.
5330   if (IdentifierInfo *II = NewTD->getIdentifier())
5331     if (!NewTD->isInvalidDecl() &&
5332         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5333       if (II->isStr("FILE"))
5334         Context.setFILEDecl(NewTD);
5335       else if (II->isStr("jmp_buf"))
5336         Context.setjmp_bufDecl(NewTD);
5337       else if (II->isStr("sigjmp_buf"))
5338         Context.setsigjmp_bufDecl(NewTD);
5339       else if (II->isStr("ucontext_t"))
5340         Context.setucontext_tDecl(NewTD);
5341     }
5342
5343   return NewTD;
5344 }
5345
5346 /// \brief Determines whether the given declaration is an out-of-scope
5347 /// previous declaration.
5348 ///
5349 /// This routine should be invoked when name lookup has found a
5350 /// previous declaration (PrevDecl) that is not in the scope where a
5351 /// new declaration by the same name is being introduced. If the new
5352 /// declaration occurs in a local scope, previous declarations with
5353 /// linkage may still be considered previous declarations (C99
5354 /// 6.2.2p4-5, C++ [basic.link]p6).
5355 ///
5356 /// \param PrevDecl the previous declaration found by name
5357 /// lookup
5358 ///
5359 /// \param DC the context in which the new declaration is being
5360 /// declared.
5361 ///
5362 /// \returns true if PrevDecl is an out-of-scope previous declaration
5363 /// for a new delcaration with the same name.
5364 static bool
5365 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5366                                 ASTContext &Context) {
5367   if (!PrevDecl)
5368     return false;
5369
5370   if (!PrevDecl->hasLinkage())
5371     return false;
5372
5373   if (Context.getLangOpts().CPlusPlus) {
5374     // C++ [basic.link]p6:
5375     //   If there is a visible declaration of an entity with linkage
5376     //   having the same name and type, ignoring entities declared
5377     //   outside the innermost enclosing namespace scope, the block
5378     //   scope declaration declares that same entity and receives the
5379     //   linkage of the previous declaration.
5380     DeclContext *OuterContext = DC->getRedeclContext();
5381     if (!OuterContext->isFunctionOrMethod())
5382       // This rule only applies to block-scope declarations.
5383       return false;
5384
5385     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5386     if (PrevOuterContext->isRecord())
5387       // We found a member function: ignore it.
5388       return false;
5389
5390     // Find the innermost enclosing namespace for the new and
5391     // previous declarations.
5392     OuterContext = OuterContext->getEnclosingNamespaceContext();
5393     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5394
5395     // The previous declaration is in a different namespace, so it
5396     // isn't the same function.
5397     if (!OuterContext->Equals(PrevOuterContext))
5398       return false;
5399   }
5400
5401   return true;
5402 }
5403
5404 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5405   CXXScopeSpec &SS = D.getCXXScopeSpec();
5406   if (!SS.isSet()) return;
5407   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5408 }
5409
5410 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5411   QualType type = decl->getType();
5412   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5413   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5414     // Various kinds of declaration aren't allowed to be __autoreleasing.
5415     unsigned kind = -1U;
5416     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5417       if (var->hasAttr<BlocksAttr>())
5418         kind = 0; // __block
5419       else if (!var->hasLocalStorage())
5420         kind = 1; // global
5421     } else if (isa<ObjCIvarDecl>(decl)) {
5422       kind = 3; // ivar
5423     } else if (isa<FieldDecl>(decl)) {
5424       kind = 2; // field
5425     }
5426
5427     if (kind != -1U) {
5428       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5429         << kind;
5430     }
5431   } else if (lifetime == Qualifiers::OCL_None) {
5432     // Try to infer lifetime.
5433     if (!type->isObjCLifetimeType())
5434       return false;
5435
5436     lifetime = type->getObjCARCImplicitLifetime();
5437     type = Context.getLifetimeQualifiedType(type, lifetime);
5438     decl->setType(type);
5439   }
5440
5441   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5442     // Thread-local variables cannot have lifetime.
5443     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5444         var->getTLSKind()) {
5445       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5446         << var->getType();
5447       return true;
5448     }
5449   }
5450
5451   return false;
5452 }
5453
5454 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5455   // Ensure that an auto decl is deduced otherwise the checks below might cache
5456   // the wrong linkage.
5457   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5458
5459   // 'weak' only applies to declarations with external linkage.
5460   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5461     if (!ND.isExternallyVisible()) {
5462       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5463       ND.dropAttr<WeakAttr>();
5464     }
5465   }
5466   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5467     if (ND.isExternallyVisible()) {
5468       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5469       ND.dropAttr<WeakRefAttr>();
5470       ND.dropAttr<AliasAttr>();
5471     }
5472   }
5473
5474   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5475     if (VD->hasInit()) {
5476       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5477         assert(VD->isThisDeclarationADefinition() &&
5478                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5479         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5480         VD->dropAttr<AliasAttr>();
5481       }
5482     }
5483   }
5484
5485   // 'selectany' only applies to externally visible variable declarations.
5486   // It does not apply to functions.
5487   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5488     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5489       S.Diag(Attr->getLocation(),
5490              diag::err_attribute_selectany_non_extern_data);
5491       ND.dropAttr<SelectAnyAttr>();
5492     }
5493   }
5494
5495   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5496     // dll attributes require external linkage. Static locals may have external
5497     // linkage but still cannot be explicitly imported or exported.
5498     auto *VD = dyn_cast<VarDecl>(&ND);
5499     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5500       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5501         << &ND << Attr;
5502       ND.setInvalidDecl();
5503     }
5504   }
5505
5506   // Virtual functions cannot be marked as 'notail'.
5507   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5508     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5509       if (MD->isVirtual()) {
5510         S.Diag(ND.getLocation(),
5511                diag::err_invalid_attribute_on_virtual_function)
5512             << Attr;
5513         ND.dropAttr<NotTailCalledAttr>();
5514       }
5515 }
5516
5517 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5518                                            NamedDecl *NewDecl,
5519                                            bool IsSpecialization) {
5520   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5521     OldDecl = OldTD->getTemplatedDecl();
5522   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5523     NewDecl = NewTD->getTemplatedDecl();
5524
5525   if (!OldDecl || !NewDecl)
5526     return;
5527
5528   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5529   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5530   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5531   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5532
5533   // dllimport and dllexport are inheritable attributes so we have to exclude
5534   // inherited attribute instances.
5535   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5536                     (NewExportAttr && !NewExportAttr->isInherited());
5537
5538   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5539   // the only exception being explicit specializations.
5540   // Implicitly generated declarations are also excluded for now because there
5541   // is no other way to switch these to use dllimport or dllexport.
5542   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5543
5544   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5545     // Allow with a warning for free functions and global variables.
5546     bool JustWarn = false;
5547     if (!OldDecl->isCXXClassMember()) {
5548       auto *VD = dyn_cast<VarDecl>(OldDecl);
5549       if (VD && !VD->getDescribedVarTemplate())
5550         JustWarn = true;
5551       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5552       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5553         JustWarn = true;
5554     }
5555
5556     // We cannot change a declaration that's been used because IR has already
5557     // been emitted. Dllimported functions will still work though (modulo
5558     // address equality) as they can use the thunk.
5559     if (OldDecl->isUsed())
5560       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5561         JustWarn = false;
5562
5563     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5564                                : diag::err_attribute_dll_redeclaration;
5565     S.Diag(NewDecl->getLocation(), DiagID)
5566         << NewDecl
5567         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5568     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5569     if (!JustWarn) {
5570       NewDecl->setInvalidDecl();
5571       return;
5572     }
5573   }
5574
5575   // A redeclaration is not allowed to drop a dllimport attribute, the only
5576   // exceptions being inline function definitions, local extern declarations,
5577   // and qualified friend declarations.
5578   // NB: MSVC converts such a declaration to dllexport.
5579   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5580   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5581     // Ignore static data because out-of-line definitions are diagnosed
5582     // separately.
5583     IsStaticDataMember = VD->isStaticDataMember();
5584   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5585     IsInline = FD->isInlined();
5586     IsQualifiedFriend = FD->getQualifier() &&
5587                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5588   }
5589
5590   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5591       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5592     S.Diag(NewDecl->getLocation(),
5593            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5594       << NewDecl << OldImportAttr;
5595     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5596     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5597     OldDecl->dropAttr<DLLImportAttr>();
5598     NewDecl->dropAttr<DLLImportAttr>();
5599   } else if (IsInline && OldImportAttr &&
5600              !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5601     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5602     OldDecl->dropAttr<DLLImportAttr>();
5603     NewDecl->dropAttr<DLLImportAttr>();
5604     S.Diag(NewDecl->getLocation(),
5605            diag::warn_dllimport_dropped_from_inline_function)
5606         << NewDecl << OldImportAttr;
5607   }
5608 }
5609
5610 /// Given that we are within the definition of the given function,
5611 /// will that definition behave like C99's 'inline', where the
5612 /// definition is discarded except for optimization purposes?
5613 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5614   // Try to avoid calling GetGVALinkageForFunction.
5615
5616   // All cases of this require the 'inline' keyword.
5617   if (!FD->isInlined()) return false;
5618
5619   // This is only possible in C++ with the gnu_inline attribute.
5620   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5621     return false;
5622
5623   // Okay, go ahead and call the relatively-more-expensive function.
5624
5625 #ifndef NDEBUG
5626   // AST quite reasonably asserts that it's working on a function
5627   // definition.  We don't really have a way to tell it that we're
5628   // currently defining the function, so just lie to it in +Asserts
5629   // builds.  This is an awful hack.
5630   FD->setLazyBody(1);
5631 #endif
5632
5633   bool isC99Inline =
5634       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5635
5636 #ifndef NDEBUG
5637   FD->setLazyBody(0);
5638 #endif
5639
5640   return isC99Inline;
5641 }
5642
5643 /// Determine whether a variable is extern "C" prior to attaching
5644 /// an initializer. We can't just call isExternC() here, because that
5645 /// will also compute and cache whether the declaration is externally
5646 /// visible, which might change when we attach the initializer.
5647 ///
5648 /// This can only be used if the declaration is known to not be a
5649 /// redeclaration of an internal linkage declaration.
5650 ///
5651 /// For instance:
5652 ///
5653 ///   auto x = []{};
5654 ///
5655 /// Attaching the initializer here makes this declaration not externally
5656 /// visible, because its type has internal linkage.
5657 ///
5658 /// FIXME: This is a hack.
5659 template<typename T>
5660 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5661   if (S.getLangOpts().CPlusPlus) {
5662     // In C++, the overloadable attribute negates the effects of extern "C".
5663     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5664       return false;
5665
5666     // So do CUDA's host/device attributes.
5667     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5668                                  D->template hasAttr<CUDAHostAttr>()))
5669       return false;
5670   }
5671   return D->isExternC();
5672 }
5673
5674 static bool shouldConsiderLinkage(const VarDecl *VD) {
5675   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5676   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5677     return VD->hasExternalStorage();
5678   if (DC->isFileContext())
5679     return true;
5680   if (DC->isRecord())
5681     return false;
5682   llvm_unreachable("Unexpected context");
5683 }
5684
5685 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5686   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5687   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5688       isa<OMPDeclareReductionDecl>(DC))
5689     return true;
5690   if (DC->isRecord())
5691     return false;
5692   llvm_unreachable("Unexpected context");
5693 }
5694
5695 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5696                           AttributeList::Kind Kind) {
5697   for (const AttributeList *L = AttrList; L; L = L->getNext())
5698     if (L->getKind() == Kind)
5699       return true;
5700   return false;
5701 }
5702
5703 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5704                           AttributeList::Kind Kind) {
5705   // Check decl attributes on the DeclSpec.
5706   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5707     return true;
5708
5709   // Walk the declarator structure, checking decl attributes that were in a type
5710   // position to the decl itself.
5711   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5712     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5713       return true;
5714   }
5715
5716   // Finally, check attributes on the decl itself.
5717   return hasParsedAttr(S, PD.getAttributes(), Kind);
5718 }
5719
5720 /// Adjust the \c DeclContext for a function or variable that might be a
5721 /// function-local external declaration.
5722 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5723   if (!DC->isFunctionOrMethod())
5724     return false;
5725
5726   // If this is a local extern function or variable declared within a function
5727   // template, don't add it into the enclosing namespace scope until it is
5728   // instantiated; it might have a dependent type right now.
5729   if (DC->isDependentContext())
5730     return true;
5731
5732   // C++11 [basic.link]p7:
5733   //   When a block scope declaration of an entity with linkage is not found to
5734   //   refer to some other declaration, then that entity is a member of the
5735   //   innermost enclosing namespace.
5736   //
5737   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5738   // semantically-enclosing namespace, not a lexically-enclosing one.
5739   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5740     DC = DC->getParent();
5741   return true;
5742 }
5743
5744 /// \brief Returns true if given declaration has external C language linkage.
5745 static bool isDeclExternC(const Decl *D) {
5746   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5747     return FD->isExternC();
5748   if (const auto *VD = dyn_cast<VarDecl>(D))
5749     return VD->isExternC();
5750
5751   llvm_unreachable("Unknown type of decl!");
5752 }
5753
5754 NamedDecl *
5755 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5756                               TypeSourceInfo *TInfo, LookupResult &Previous,
5757                               MultiTemplateParamsArg TemplateParamLists,
5758                               bool &AddToScope) {
5759   QualType R = TInfo->getType();
5760   DeclarationName Name = GetNameForDeclarator(D).getName();
5761
5762   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5763   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5764   // argument.
5765   if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) {
5766     Diag(D.getIdentifierLoc(),
5767          diag::err_opencl_type_can_only_be_used_as_function_parameter)
5768         << R;
5769     D.setInvalidType();
5770     return nullptr;
5771   }
5772
5773   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5774   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5775
5776   // dllimport globals without explicit storage class are treated as extern. We
5777   // have to change the storage class this early to get the right DeclContext.
5778   if (SC == SC_None && !DC->isRecord() &&
5779       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5780       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5781     SC = SC_Extern;
5782
5783   DeclContext *OriginalDC = DC;
5784   bool IsLocalExternDecl = SC == SC_Extern &&
5785                            adjustContextForLocalExternDecl(DC);
5786
5787   if (getLangOpts().OpenCL) {
5788     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5789     QualType NR = R;
5790     while (NR->isPointerType()) {
5791       if (NR->isFunctionPointerType()) {
5792         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5793         D.setInvalidType();
5794         break;
5795       }
5796       NR = NR->getPointeeType();
5797     }
5798
5799     if (!getOpenCLOptions().cl_khr_fp16) {
5800       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5801       // half array type (unless the cl_khr_fp16 extension is enabled).
5802       if (Context.getBaseElementType(R)->isHalfType()) {
5803         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5804         D.setInvalidType();
5805       }
5806     }
5807   }
5808
5809   if (SCSpec == DeclSpec::SCS_mutable) {
5810     // mutable can only appear on non-static class members, so it's always
5811     // an error here
5812     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5813     D.setInvalidType();
5814     SC = SC_None;
5815   }
5816
5817   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5818       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5819                               D.getDeclSpec().getStorageClassSpecLoc())) {
5820     // In C++11, the 'register' storage class specifier is deprecated.
5821     // Suppress the warning in system macros, it's used in macros in some
5822     // popular C system headers, such as in glibc's htonl() macro.
5823     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5824          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5825                                    : diag::warn_deprecated_register)
5826       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5827   }
5828
5829   IdentifierInfo *II = Name.getAsIdentifierInfo();
5830   if (!II) {
5831     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5832       << Name;
5833     return nullptr;
5834   }
5835
5836   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5837
5838   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5839     // C99 6.9p2: The storage-class specifiers auto and register shall not
5840     // appear in the declaration specifiers in an external declaration.
5841     // Global Register+Asm is a GNU extension we support.
5842     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5843       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5844       D.setInvalidType();
5845     }
5846   }
5847
5848   if (getLangOpts().OpenCL) {
5849     // OpenCL v1.2 s6.9.b p4:
5850     // The sampler type cannot be used with the __local and __global address
5851     // space qualifiers.
5852     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5853       R.getAddressSpace() == LangAS::opencl_global)) {
5854       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5855     }
5856
5857     // OpenCL 1.2 spec, p6.9 r:
5858     // The event type cannot be used to declare a program scope variable.
5859     // The event type cannot be used with the __local, __constant and __global
5860     // address space qualifiers.
5861     if (R->isEventT()) {
5862       if (S->getParent() == nullptr) {
5863         Diag(D.getLocStart(), diag::err_event_t_global_var);
5864         D.setInvalidType();
5865       }
5866
5867       if (R.getAddressSpace()) {
5868         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5869         D.setInvalidType();
5870       }
5871     }
5872   }
5873
5874   bool IsExplicitSpecialization = false;
5875   bool IsVariableTemplateSpecialization = false;
5876   bool IsPartialSpecialization = false;
5877   bool IsVariableTemplate = false;
5878   VarDecl *NewVD = nullptr;
5879   VarTemplateDecl *NewTemplate = nullptr;
5880   TemplateParameterList *TemplateParams = nullptr;
5881   if (!getLangOpts().CPlusPlus) {
5882     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5883                             D.getIdentifierLoc(), II,
5884                             R, TInfo, SC);
5885
5886     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5887       ParsingInitForAutoVars.insert(NewVD);
5888
5889     if (D.isInvalidType())
5890       NewVD->setInvalidDecl();
5891   } else {
5892     bool Invalid = false;
5893
5894     if (DC->isRecord() && !CurContext->isRecord()) {
5895       // This is an out-of-line definition of a static data member.
5896       switch (SC) {
5897       case SC_None:
5898         break;
5899       case SC_Static:
5900         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5901              diag::err_static_out_of_line)
5902           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5903         break;
5904       case SC_Auto:
5905       case SC_Register:
5906       case SC_Extern:
5907         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5908         // to names of variables declared in a block or to function parameters.
5909         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5910         // of class members
5911
5912         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5913              diag::err_storage_class_for_static_member)
5914           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5915         break;
5916       case SC_PrivateExtern:
5917         llvm_unreachable("C storage class in c++!");
5918       }
5919     }
5920
5921     if (SC == SC_Static && CurContext->isRecord()) {
5922       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5923         if (RD->isLocalClass())
5924           Diag(D.getIdentifierLoc(),
5925                diag::err_static_data_member_not_allowed_in_local_class)
5926             << Name << RD->getDeclName();
5927
5928         // C++98 [class.union]p1: If a union contains a static data member,
5929         // the program is ill-formed. C++11 drops this restriction.
5930         if (RD->isUnion())
5931           Diag(D.getIdentifierLoc(),
5932                getLangOpts().CPlusPlus11
5933                  ? diag::warn_cxx98_compat_static_data_member_in_union
5934                  : diag::ext_static_data_member_in_union) << Name;
5935         // We conservatively disallow static data members in anonymous structs.
5936         else if (!RD->getDeclName())
5937           Diag(D.getIdentifierLoc(),
5938                diag::err_static_data_member_not_allowed_in_anon_struct)
5939             << Name << RD->isUnion();
5940       }
5941     }
5942
5943     // Match up the template parameter lists with the scope specifier, then
5944     // determine whether we have a template or a template specialization.
5945     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5946         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5947         D.getCXXScopeSpec(),
5948         D.getName().getKind() == UnqualifiedId::IK_TemplateId
5949             ? D.getName().TemplateId
5950             : nullptr,
5951         TemplateParamLists,
5952         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5953
5954     if (TemplateParams) {
5955       if (!TemplateParams->size() &&
5956           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5957         // There is an extraneous 'template<>' for this variable. Complain
5958         // about it, but allow the declaration of the variable.
5959         Diag(TemplateParams->getTemplateLoc(),
5960              diag::err_template_variable_noparams)
5961           << II
5962           << SourceRange(TemplateParams->getTemplateLoc(),
5963                          TemplateParams->getRAngleLoc());
5964         TemplateParams = nullptr;
5965       } else {
5966         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5967           // This is an explicit specialization or a partial specialization.
5968           // FIXME: Check that we can declare a specialization here.
5969           IsVariableTemplateSpecialization = true;
5970           IsPartialSpecialization = TemplateParams->size() > 0;
5971         } else { // if (TemplateParams->size() > 0)
5972           // This is a template declaration.
5973           IsVariableTemplate = true;
5974
5975           // Check that we can declare a template here.
5976           if (CheckTemplateDeclScope(S, TemplateParams))
5977             return nullptr;
5978
5979           // Only C++1y supports variable templates (N3651).
5980           Diag(D.getIdentifierLoc(),
5981                getLangOpts().CPlusPlus14
5982                    ? diag::warn_cxx11_compat_variable_template
5983                    : diag::ext_variable_template);
5984         }
5985       }
5986     } else {
5987       assert(
5988           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5989           "should have a 'template<>' for this decl");
5990     }
5991
5992     if (IsVariableTemplateSpecialization) {
5993       SourceLocation TemplateKWLoc =
5994           TemplateParamLists.size() > 0
5995               ? TemplateParamLists[0]->getTemplateLoc()
5996               : SourceLocation();
5997       DeclResult Res = ActOnVarTemplateSpecialization(
5998           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5999           IsPartialSpecialization);
6000       if (Res.isInvalid())
6001         return nullptr;
6002       NewVD = cast<VarDecl>(Res.get());
6003       AddToScope = false;
6004     } else
6005       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6006                               D.getIdentifierLoc(), II, R, TInfo, SC);
6007
6008     // If this is supposed to be a variable template, create it as such.
6009     if (IsVariableTemplate) {
6010       NewTemplate =
6011           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6012                                   TemplateParams, NewVD);
6013       NewVD->setDescribedVarTemplate(NewTemplate);
6014     }
6015
6016     // If this decl has an auto type in need of deduction, make a note of the
6017     // Decl so we can diagnose uses of it in its own initializer.
6018     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6019       ParsingInitForAutoVars.insert(NewVD);
6020
6021     if (D.isInvalidType() || Invalid) {
6022       NewVD->setInvalidDecl();
6023       if (NewTemplate)
6024         NewTemplate->setInvalidDecl();
6025     }
6026
6027     SetNestedNameSpecifier(NewVD, D);
6028
6029     // If we have any template parameter lists that don't directly belong to
6030     // the variable (matching the scope specifier), store them.
6031     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6032     if (TemplateParamLists.size() > VDTemplateParamLists)
6033       NewVD->setTemplateParameterListsInfo(
6034           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6035
6036     if (D.getDeclSpec().isConstexprSpecified())
6037       NewVD->setConstexpr(true);
6038
6039     if (D.getDeclSpec().isConceptSpecified()) {
6040       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6041         VTD->setConcept();
6042
6043       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6044       // be declared with the thread_local, inline, friend, or constexpr
6045       // specifiers, [...]
6046       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6047         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6048              diag::err_concept_decl_invalid_specifiers)
6049             << 0 << 0;
6050         NewVD->setInvalidDecl(true);
6051       }
6052
6053       if (D.getDeclSpec().isConstexprSpecified()) {
6054         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6055              diag::err_concept_decl_invalid_specifiers)
6056             << 0 << 3;
6057         NewVD->setInvalidDecl(true);
6058       }
6059
6060       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6061       // applied only to the definition of a function template or variable
6062       // template, declared in namespace scope.
6063       if (IsVariableTemplateSpecialization) {
6064         Diag(D.getDeclSpec().getConceptSpecLoc(),
6065              diag::err_concept_specified_specialization)
6066             << (IsPartialSpecialization ? 2 : 1);
6067       }
6068
6069       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6070       // following restrictions:
6071       // - The declared type shall have the type bool.
6072       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6073           !NewVD->isInvalidDecl()) {
6074         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6075         NewVD->setInvalidDecl(true);
6076       }
6077     }
6078   }
6079
6080   // Set the lexical context. If the declarator has a C++ scope specifier, the
6081   // lexical context will be different from the semantic context.
6082   NewVD->setLexicalDeclContext(CurContext);
6083   if (NewTemplate)
6084     NewTemplate->setLexicalDeclContext(CurContext);
6085
6086   if (IsLocalExternDecl)
6087     NewVD->setLocalExternDecl();
6088
6089   bool EmitTLSUnsupportedError = false;
6090   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6091     // C++11 [dcl.stc]p4:
6092     //   When thread_local is applied to a variable of block scope the
6093     //   storage-class-specifier static is implied if it does not appear
6094     //   explicitly.
6095     // Core issue: 'static' is not implied if the variable is declared
6096     //   'extern'.
6097     if (NewVD->hasLocalStorage() &&
6098         (SCSpec != DeclSpec::SCS_unspecified ||
6099          TSCS != DeclSpec::TSCS_thread_local ||
6100          !DC->isFunctionOrMethod()))
6101       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6102            diag::err_thread_non_global)
6103         << DeclSpec::getSpecifierName(TSCS);
6104     else if (!Context.getTargetInfo().isTLSSupported()) {
6105       if (getLangOpts().CUDA) {
6106         // Postpone error emission until we've collected attributes required to
6107         // figure out whether it's a host or device variable and whether the
6108         // error should be ignored.
6109         EmitTLSUnsupportedError = true;
6110         // We still need to mark the variable as TLS so it shows up in AST with
6111         // proper storage class for other tools to use even if we're not going
6112         // to emit any code for it.
6113         NewVD->setTSCSpec(TSCS);
6114       } else
6115         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6116              diag::err_thread_unsupported);
6117     } else
6118       NewVD->setTSCSpec(TSCS);
6119   }
6120
6121   // C99 6.7.4p3
6122   //   An inline definition of a function with external linkage shall
6123   //   not contain a definition of a modifiable object with static or
6124   //   thread storage duration...
6125   // We only apply this when the function is required to be defined
6126   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6127   // that a local variable with thread storage duration still has to
6128   // be marked 'static'.  Also note that it's possible to get these
6129   // semantics in C++ using __attribute__((gnu_inline)).
6130   if (SC == SC_Static && S->getFnParent() != nullptr &&
6131       !NewVD->getType().isConstQualified()) {
6132     FunctionDecl *CurFD = getCurFunctionDecl();
6133     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6134       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6135            diag::warn_static_local_in_extern_inline);
6136       MaybeSuggestAddingStaticToDecl(CurFD);
6137     }
6138   }
6139
6140   if (D.getDeclSpec().isModulePrivateSpecified()) {
6141     if (IsVariableTemplateSpecialization)
6142       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6143           << (IsPartialSpecialization ? 1 : 0)
6144           << FixItHint::CreateRemoval(
6145                  D.getDeclSpec().getModulePrivateSpecLoc());
6146     else if (IsExplicitSpecialization)
6147       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6148         << 2
6149         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6150     else if (NewVD->hasLocalStorage())
6151       Diag(NewVD->getLocation(), diag::err_module_private_local)
6152         << 0 << NewVD->getDeclName()
6153         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6154         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6155     else {
6156       NewVD->setModulePrivate();
6157       if (NewTemplate)
6158         NewTemplate->setModulePrivate();
6159     }
6160   }
6161
6162   // Handle attributes prior to checking for duplicates in MergeVarDecl
6163   ProcessDeclAttributes(S, NewVD, D);
6164
6165   if (getLangOpts().CUDA) {
6166     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6167       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6168            diag::err_thread_unsupported);
6169     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6170     // storage [duration]."
6171     if (SC == SC_None && S->getFnParent() != nullptr &&
6172         (NewVD->hasAttr<CUDASharedAttr>() ||
6173          NewVD->hasAttr<CUDAConstantAttr>())) {
6174       NewVD->setStorageClass(SC_Static);
6175     }
6176   }
6177
6178   // Ensure that dllimport globals without explicit storage class are treated as
6179   // extern. The storage class is set above using parsed attributes. Now we can
6180   // check the VarDecl itself.
6181   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6182          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6183          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6184
6185   // In auto-retain/release, infer strong retension for variables of
6186   // retainable type.
6187   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6188     NewVD->setInvalidDecl();
6189
6190   // Handle GNU asm-label extension (encoded as an attribute).
6191   if (Expr *E = (Expr*)D.getAsmLabel()) {
6192     // The parser guarantees this is a string.
6193     StringLiteral *SE = cast<StringLiteral>(E);
6194     StringRef Label = SE->getString();
6195     if (S->getFnParent() != nullptr) {
6196       switch (SC) {
6197       case SC_None:
6198       case SC_Auto:
6199         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6200         break;
6201       case SC_Register:
6202         // Local Named register
6203         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6204             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6205           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6206         break;
6207       case SC_Static:
6208       case SC_Extern:
6209       case SC_PrivateExtern:
6210         break;
6211       }
6212     } else if (SC == SC_Register) {
6213       // Global Named register
6214       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6215         const auto &TI = Context.getTargetInfo();
6216         bool HasSizeMismatch;
6217
6218         if (!TI.isValidGCCRegisterName(Label))
6219           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6220         else if (!TI.validateGlobalRegisterVariable(Label,
6221                                                     Context.getTypeSize(R),
6222                                                     HasSizeMismatch))
6223           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6224         else if (HasSizeMismatch)
6225           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6226       }
6227
6228       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6229         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6230         NewVD->setInvalidDecl(true);
6231       }
6232     }
6233
6234     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6235                                                 Context, Label, 0));
6236   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6237     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6238       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6239     if (I != ExtnameUndeclaredIdentifiers.end()) {
6240       if (isDeclExternC(NewVD)) {
6241         NewVD->addAttr(I->second);
6242         ExtnameUndeclaredIdentifiers.erase(I);
6243       } else
6244         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6245             << /*Variable*/1 << NewVD;
6246     }
6247   }
6248
6249   // Diagnose shadowed variables before filtering for scope.
6250   if (D.getCXXScopeSpec().isEmpty())
6251     CheckShadow(S, NewVD, Previous);
6252
6253   // Don't consider existing declarations that are in a different
6254   // scope and are out-of-semantic-context declarations (if the new
6255   // declaration has linkage).
6256   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6257                        D.getCXXScopeSpec().isNotEmpty() ||
6258                        IsExplicitSpecialization ||
6259                        IsVariableTemplateSpecialization);
6260
6261   // Check whether the previous declaration is in the same block scope. This
6262   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6263   if (getLangOpts().CPlusPlus &&
6264       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6265     NewVD->setPreviousDeclInSameBlockScope(
6266         Previous.isSingleResult() && !Previous.isShadowed() &&
6267         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6268
6269   if (!getLangOpts().CPlusPlus) {
6270     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6271   } else {
6272     // If this is an explicit specialization of a static data member, check it.
6273     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6274         CheckMemberSpecialization(NewVD, Previous))
6275       NewVD->setInvalidDecl();
6276
6277     // Merge the decl with the existing one if appropriate.
6278     if (!Previous.empty()) {
6279       if (Previous.isSingleResult() &&
6280           isa<FieldDecl>(Previous.getFoundDecl()) &&
6281           D.getCXXScopeSpec().isSet()) {
6282         // The user tried to define a non-static data member
6283         // out-of-line (C++ [dcl.meaning]p1).
6284         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6285           << D.getCXXScopeSpec().getRange();
6286         Previous.clear();
6287         NewVD->setInvalidDecl();
6288       }
6289     } else if (D.getCXXScopeSpec().isSet()) {
6290       // No previous declaration in the qualifying scope.
6291       Diag(D.getIdentifierLoc(), diag::err_no_member)
6292         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6293         << D.getCXXScopeSpec().getRange();
6294       NewVD->setInvalidDecl();
6295     }
6296
6297     if (!IsVariableTemplateSpecialization)
6298       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6299
6300     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6301     // an explicit specialization (14.8.3) or a partial specialization of a
6302     // concept definition.
6303     if (IsVariableTemplateSpecialization &&
6304         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6305         Previous.isSingleResult()) {
6306       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6307       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6308         if (VarTmpl->isConcept()) {
6309           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6310               << 1                            /*variable*/
6311               << (IsPartialSpecialization ? 2 /*partially specialized*/
6312                                           : 1 /*explicitly specialized*/);
6313           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6314           NewVD->setInvalidDecl();
6315         }
6316       }
6317     }
6318
6319     if (NewTemplate) {
6320       VarTemplateDecl *PrevVarTemplate =
6321           NewVD->getPreviousDecl()
6322               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6323               : nullptr;
6324
6325       // Check the template parameter list of this declaration, possibly
6326       // merging in the template parameter list from the previous variable
6327       // template declaration.
6328       if (CheckTemplateParameterList(
6329               TemplateParams,
6330               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6331                               : nullptr,
6332               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6333                DC->isDependentContext())
6334                   ? TPC_ClassTemplateMember
6335                   : TPC_VarTemplate))
6336         NewVD->setInvalidDecl();
6337
6338       // If we are providing an explicit specialization of a static variable
6339       // template, make a note of that.
6340       if (PrevVarTemplate &&
6341           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6342         PrevVarTemplate->setMemberSpecialization();
6343     }
6344   }
6345
6346   ProcessPragmaWeak(S, NewVD);
6347
6348   // If this is the first declaration of an extern C variable, update
6349   // the map of such variables.
6350   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6351       isIncompleteDeclExternC(*this, NewVD))
6352     RegisterLocallyScopedExternCDecl(NewVD, S);
6353
6354   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6355     Decl *ManglingContextDecl;
6356     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6357             NewVD->getDeclContext(), ManglingContextDecl)) {
6358       Context.setManglingNumber(
6359           NewVD, MCtx->getManglingNumber(
6360                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6361       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6362     }
6363   }
6364
6365   // Special handling of variable named 'main'.
6366   if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6367       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6368       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6369
6370     // C++ [basic.start.main]p3
6371     // A program that declares a variable main at global scope is ill-formed.
6372     if (getLangOpts().CPlusPlus)
6373       Diag(D.getLocStart(), diag::err_main_global_variable);
6374
6375     // In C, and external-linkage variable named main results in undefined
6376     // behavior.
6377     else if (NewVD->hasExternalFormalLinkage())
6378       Diag(D.getLocStart(), diag::warn_main_redefined);
6379   }
6380
6381   if (D.isRedeclaration() && !Previous.empty()) {
6382     checkDLLAttributeRedeclaration(
6383         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6384         IsExplicitSpecialization);
6385   }
6386
6387   if (NewTemplate) {
6388     if (NewVD->isInvalidDecl())
6389       NewTemplate->setInvalidDecl();
6390     ActOnDocumentableDecl(NewTemplate);
6391     return NewTemplate;
6392   }
6393
6394   return NewVD;
6395 }
6396
6397 /// Enum describing the %select options in diag::warn_decl_shadow.
6398 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
6399
6400 /// Determine what kind of declaration we're shadowing.
6401 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6402                                                 const DeclContext *OldDC) {
6403   if (isa<RecordDecl>(OldDC))
6404     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6405   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6406 }
6407
6408 /// \brief Diagnose variable or built-in function shadowing.  Implements
6409 /// -Wshadow.
6410 ///
6411 /// This method is called whenever a VarDecl is added to a "useful"
6412 /// scope.
6413 ///
6414 /// \param S the scope in which the shadowing name is being declared
6415 /// \param R the lookup of the name
6416 ///
6417 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6418   // Return if warning is ignored.
6419   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6420     return;
6421
6422   // Don't diagnose declarations at file scope.
6423   if (D->hasGlobalStorage())
6424     return;
6425
6426   DeclContext *NewDC = D->getDeclContext();
6427
6428   // Only diagnose if we're shadowing an unambiguous field or variable.
6429   if (R.getResultKind() != LookupResult::Found)
6430     return;
6431
6432   NamedDecl* ShadowedDecl = R.getFoundDecl();
6433   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6434     return;
6435
6436   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6437     // Fields are not shadowed by variables in C++ static methods.
6438     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6439       if (MD->isStatic())
6440         return;
6441
6442     // Fields shadowed by constructor parameters are a special case. Usually
6443     // the constructor initializes the field with the parameter.
6444     if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
6445       // Remember that this was shadowed so we can either warn about its
6446       // modification or its existence depending on warning settings.
6447       D = D->getCanonicalDecl();
6448       ShadowingDecls.insert({D, FD});
6449       return;
6450     }
6451   }
6452
6453   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6454     if (shadowedVar->isExternC()) {
6455       // For shadowing external vars, make sure that we point to the global
6456       // declaration, not a locally scoped extern declaration.
6457       for (auto I : shadowedVar->redecls())
6458         if (I->isFileVarDecl()) {
6459           ShadowedDecl = I;
6460           break;
6461         }
6462     }
6463
6464   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6465
6466   // Only warn about certain kinds of shadowing for class members.
6467   if (NewDC && NewDC->isRecord()) {
6468     // In particular, don't warn about shadowing non-class members.
6469     if (!OldDC->isRecord())
6470       return;
6471
6472     // TODO: should we warn about static data members shadowing
6473     // static data members from base classes?
6474
6475     // TODO: don't diagnose for inaccessible shadowed members.
6476     // This is hard to do perfectly because we might friend the
6477     // shadowing context, but that's just a false negative.
6478   }
6479
6480
6481   DeclarationName Name = R.getLookupName();
6482
6483   // Emit warning and note.
6484   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6485     return;
6486   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6487   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6488   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6489 }
6490
6491 /// \brief Check -Wshadow without the advantage of a previous lookup.
6492 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6493   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6494     return;
6495
6496   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6497                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6498   LookupName(R, S);
6499   CheckShadow(S, D, R);
6500 }
6501
6502 /// Check if 'E', which is an expression that is about to be modified, refers
6503 /// to a constructor parameter that shadows a field.
6504 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6505   // Quickly ignore expressions that can't be shadowing ctor parameters.
6506   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6507     return;
6508   E = E->IgnoreParenImpCasts();
6509   auto *DRE = dyn_cast<DeclRefExpr>(E);
6510   if (!DRE)
6511     return;
6512   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6513   auto I = ShadowingDecls.find(D);
6514   if (I == ShadowingDecls.end())
6515     return;
6516   const NamedDecl *ShadowedDecl = I->second;
6517   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6518   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6519   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6520   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6521
6522   // Avoid issuing multiple warnings about the same decl.
6523   ShadowingDecls.erase(I);
6524 }
6525
6526 /// Check for conflict between this global or extern "C" declaration and
6527 /// previous global or extern "C" declarations. This is only used in C++.
6528 template<typename T>
6529 static bool checkGlobalOrExternCConflict(
6530     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6531   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6532   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6533
6534   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6535     // The common case: this global doesn't conflict with any extern "C"
6536     // declaration.
6537     return false;
6538   }
6539
6540   if (Prev) {
6541     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6542       // Both the old and new declarations have C language linkage. This is a
6543       // redeclaration.
6544       Previous.clear();
6545       Previous.addDecl(Prev);
6546       return true;
6547     }
6548
6549     // This is a global, non-extern "C" declaration, and there is a previous
6550     // non-global extern "C" declaration. Diagnose if this is a variable
6551     // declaration.
6552     if (!isa<VarDecl>(ND))
6553       return false;
6554   } else {
6555     // The declaration is extern "C". Check for any declaration in the
6556     // translation unit which might conflict.
6557     if (IsGlobal) {
6558       // We have already performed the lookup into the translation unit.
6559       IsGlobal = false;
6560       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6561            I != E; ++I) {
6562         if (isa<VarDecl>(*I)) {
6563           Prev = *I;
6564           break;
6565         }
6566       }
6567     } else {
6568       DeclContext::lookup_result R =
6569           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6570       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6571            I != E; ++I) {
6572         if (isa<VarDecl>(*I)) {
6573           Prev = *I;
6574           break;
6575         }
6576         // FIXME: If we have any other entity with this name in global scope,
6577         // the declaration is ill-formed, but that is a defect: it breaks the
6578         // 'stat' hack, for instance. Only variables can have mangled name
6579         // clashes with extern "C" declarations, so only they deserve a
6580         // diagnostic.
6581       }
6582     }
6583
6584     if (!Prev)
6585       return false;
6586   }
6587
6588   // Use the first declaration's location to ensure we point at something which
6589   // is lexically inside an extern "C" linkage-spec.
6590   assert(Prev && "should have found a previous declaration to diagnose");
6591   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6592     Prev = FD->getFirstDecl();
6593   else
6594     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6595
6596   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6597     << IsGlobal << ND;
6598   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6599     << IsGlobal;
6600   return false;
6601 }
6602
6603 /// Apply special rules for handling extern "C" declarations. Returns \c true
6604 /// if we have found that this is a redeclaration of some prior entity.
6605 ///
6606 /// Per C++ [dcl.link]p6:
6607 ///   Two declarations [for a function or variable] with C language linkage
6608 ///   with the same name that appear in different scopes refer to the same
6609 ///   [entity]. An entity with C language linkage shall not be declared with
6610 ///   the same name as an entity in global scope.
6611 template<typename T>
6612 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6613                                                   LookupResult &Previous) {
6614   if (!S.getLangOpts().CPlusPlus) {
6615     // In C, when declaring a global variable, look for a corresponding 'extern'
6616     // variable declared in function scope. We don't need this in C++, because
6617     // we find local extern decls in the surrounding file-scope DeclContext.
6618     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6619       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6620         Previous.clear();
6621         Previous.addDecl(Prev);
6622         return true;
6623       }
6624     }
6625     return false;
6626   }
6627
6628   // A declaration in the translation unit can conflict with an extern "C"
6629   // declaration.
6630   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6631     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6632
6633   // An extern "C" declaration can conflict with a declaration in the
6634   // translation unit or can be a redeclaration of an extern "C" declaration
6635   // in another scope.
6636   if (isIncompleteDeclExternC(S,ND))
6637     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6638
6639   // Neither global nor extern "C": nothing to do.
6640   return false;
6641 }
6642
6643 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6644   // If the decl is already known invalid, don't check it.
6645   if (NewVD->isInvalidDecl())
6646     return;
6647
6648   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6649   QualType T = TInfo->getType();
6650
6651   // Defer checking an 'auto' type until its initializer is attached.
6652   if (T->isUndeducedType())
6653     return;
6654
6655   if (NewVD->hasAttrs())
6656     CheckAlignasUnderalignment(NewVD);
6657
6658   if (T->isObjCObjectType()) {
6659     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6660       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6661     T = Context.getObjCObjectPointerType(T);
6662     NewVD->setType(T);
6663   }
6664
6665   // Emit an error if an address space was applied to decl with local storage.
6666   // This includes arrays of objects with address space qualifiers, but not
6667   // automatic variables that point to other address spaces.
6668   // ISO/IEC TR 18037 S5.1.2
6669   if (!getLangOpts().OpenCL
6670       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6671     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6672     NewVD->setInvalidDecl();
6673     return;
6674   }
6675
6676   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
6677   // scope.
6678   if (getLangOpts().OpenCLVersion == 120 &&
6679       !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6680       NewVD->isStaticLocal()) {
6681     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6682     NewVD->setInvalidDecl();
6683     return;
6684   }
6685
6686   if (getLangOpts().OpenCL) {
6687     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
6688     if (NewVD->hasAttr<BlocksAttr>()) {
6689       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
6690       return;
6691     }
6692
6693     if (T->isBlockPointerType()) {
6694       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
6695       // can't use 'extern' storage class.
6696       if (!T.isConstQualified()) {
6697         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
6698             << 0 /*const*/;
6699         NewVD->setInvalidDecl();
6700         return;
6701       }
6702       if (NewVD->hasExternalStorage()) {
6703         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
6704         NewVD->setInvalidDecl();
6705         return;
6706       }
6707       // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported.
6708       // TODO: this check is not enough as it doesn't diagnose the typedef
6709       const BlockPointerType *BlkTy = T->getAs<BlockPointerType>();
6710       const FunctionProtoType *FTy =
6711           BlkTy->getPointeeType()->getAs<FunctionProtoType>();
6712       if (FTy && FTy->isVariadic()) {
6713         Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic)
6714             << T << NewVD->getSourceRange();
6715         NewVD->setInvalidDecl();
6716         return;
6717       }
6718     }
6719     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6720     // __constant address space.
6721     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6722     // variables inside a function can also be declared in the global
6723     // address space.
6724     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
6725         NewVD->hasExternalStorage()) {
6726       if (!T->isSamplerT() &&
6727           !(T.getAddressSpace() == LangAS::opencl_constant ||
6728             (T.getAddressSpace() == LangAS::opencl_global &&
6729              getLangOpts().OpenCLVersion == 200))) {
6730         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
6731         if (getLangOpts().OpenCLVersion == 200)
6732           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6733               << Scope << "global or constant";
6734         else
6735           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6736               << Scope << "constant";
6737         NewVD->setInvalidDecl();
6738         return;
6739       }
6740     } else {
6741       if (T.getAddressSpace() == LangAS::opencl_global) {
6742         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6743             << 1 /*is any function*/ << "global";
6744         NewVD->setInvalidDecl();
6745         return;
6746       }
6747       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6748       // in functions.
6749       if (T.getAddressSpace() == LangAS::opencl_constant ||
6750           T.getAddressSpace() == LangAS::opencl_local) {
6751         FunctionDecl *FD = getCurFunctionDecl();
6752         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6753           if (T.getAddressSpace() == LangAS::opencl_constant)
6754             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6755                 << 0 /*non-kernel only*/ << "constant";
6756           else
6757             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6758                 << 0 /*non-kernel only*/ << "local";
6759           NewVD->setInvalidDecl();
6760           return;
6761         }
6762       }
6763     }
6764   }
6765
6766   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6767       && !NewVD->hasAttr<BlocksAttr>()) {
6768     if (getLangOpts().getGC() != LangOptions::NonGC)
6769       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6770     else {
6771       assert(!getLangOpts().ObjCAutoRefCount);
6772       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6773     }
6774   }
6775
6776   bool isVM = T->isVariablyModifiedType();
6777   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6778       NewVD->hasAttr<BlocksAttr>())
6779     getCurFunction()->setHasBranchProtectedScope();
6780
6781   if ((isVM && NewVD->hasLinkage()) ||
6782       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6783     bool SizeIsNegative;
6784     llvm::APSInt Oversized;
6785     TypeSourceInfo *FixedTInfo =
6786       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6787                                                     SizeIsNegative, Oversized);
6788     if (!FixedTInfo && T->isVariableArrayType()) {
6789       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6790       // FIXME: This won't give the correct result for
6791       // int a[10][n];
6792       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6793
6794       if (NewVD->isFileVarDecl())
6795         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6796         << SizeRange;
6797       else if (NewVD->isStaticLocal())
6798         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6799         << SizeRange;
6800       else
6801         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6802         << SizeRange;
6803       NewVD->setInvalidDecl();
6804       return;
6805     }
6806
6807     if (!FixedTInfo) {
6808       if (NewVD->isFileVarDecl())
6809         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6810       else
6811         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6812       NewVD->setInvalidDecl();
6813       return;
6814     }
6815
6816     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6817     NewVD->setType(FixedTInfo->getType());
6818     NewVD->setTypeSourceInfo(FixedTInfo);
6819   }
6820
6821   if (T->isVoidType()) {
6822     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6823     //                    of objects and functions.
6824     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6825       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6826         << T;
6827       NewVD->setInvalidDecl();
6828       return;
6829     }
6830   }
6831
6832   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6833     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6834     NewVD->setInvalidDecl();
6835     return;
6836   }
6837
6838   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6839     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6840     NewVD->setInvalidDecl();
6841     return;
6842   }
6843
6844   if (NewVD->isConstexpr() && !T->isDependentType() &&
6845       RequireLiteralType(NewVD->getLocation(), T,
6846                          diag::err_constexpr_var_non_literal)) {
6847     NewVD->setInvalidDecl();
6848     return;
6849   }
6850 }
6851
6852 /// \brief Perform semantic checking on a newly-created variable
6853 /// declaration.
6854 ///
6855 /// This routine performs all of the type-checking required for a
6856 /// variable declaration once it has been built. It is used both to
6857 /// check variables after they have been parsed and their declarators
6858 /// have been translated into a declaration, and to check variables
6859 /// that have been instantiated from a template.
6860 ///
6861 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6862 ///
6863 /// Returns true if the variable declaration is a redeclaration.
6864 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6865   CheckVariableDeclarationType(NewVD);
6866
6867   // If the decl is already known invalid, don't check it.
6868   if (NewVD->isInvalidDecl())
6869     return false;
6870
6871   // If we did not find anything by this name, look for a non-visible
6872   // extern "C" declaration with the same name.
6873   if (Previous.empty() &&
6874       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6875     Previous.setShadowed();
6876
6877   if (!Previous.empty()) {
6878     MergeVarDecl(NewVD, Previous);
6879     return true;
6880   }
6881   return false;
6882 }
6883
6884 namespace {
6885 struct FindOverriddenMethod {
6886   Sema *S;
6887   CXXMethodDecl *Method;
6888
6889   /// Member lookup function that determines whether a given C++
6890   /// method overrides a method in a base class, to be used with
6891   /// CXXRecordDecl::lookupInBases().
6892   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6893     RecordDecl *BaseRecord =
6894         Specifier->getType()->getAs<RecordType>()->getDecl();
6895
6896     DeclarationName Name = Method->getDeclName();
6897
6898     // FIXME: Do we care about other names here too?
6899     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6900       // We really want to find the base class destructor here.
6901       QualType T = S->Context.getTypeDeclType(BaseRecord);
6902       CanQualType CT = S->Context.getCanonicalType(T);
6903
6904       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
6905     }
6906
6907     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6908          Path.Decls = Path.Decls.slice(1)) {
6909       NamedDecl *D = Path.Decls.front();
6910       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6911         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
6912           return true;
6913       }
6914     }
6915
6916     return false;
6917   }
6918 };
6919
6920 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6921 } // end anonymous namespace
6922
6923 /// \brief Report an error regarding overriding, along with any relevant
6924 /// overriden methods.
6925 ///
6926 /// \param DiagID the primary error to report.
6927 /// \param MD the overriding method.
6928 /// \param OEK which overrides to include as notes.
6929 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6930                             OverrideErrorKind OEK = OEK_All) {
6931   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6932   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6933                                       E = MD->end_overridden_methods();
6934        I != E; ++I) {
6935     // This check (& the OEK parameter) could be replaced by a predicate, but
6936     // without lambdas that would be overkill. This is still nicer than writing
6937     // out the diag loop 3 times.
6938     if ((OEK == OEK_All) ||
6939         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6940         (OEK == OEK_Deleted && (*I)->isDeleted()))
6941       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6942   }
6943 }
6944
6945 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6946 /// and if so, check that it's a valid override and remember it.
6947 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6948   // Look for methods in base classes that this method might override.
6949   CXXBasePaths Paths;
6950   FindOverriddenMethod FOM;
6951   FOM.Method = MD;
6952   FOM.S = this;
6953   bool hasDeletedOverridenMethods = false;
6954   bool hasNonDeletedOverridenMethods = false;
6955   bool AddedAny = false;
6956   if (DC->lookupInBases(FOM, Paths)) {
6957     for (auto *I : Paths.found_decls()) {
6958       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6959         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6960         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6961             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6962             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6963             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6964           hasDeletedOverridenMethods |= OldMD->isDeleted();
6965           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6966           AddedAny = true;
6967         }
6968       }
6969     }
6970   }
6971
6972   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6973     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6974   }
6975   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6976     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6977   }
6978
6979   return AddedAny;
6980 }
6981
6982 namespace {
6983   // Struct for holding all of the extra arguments needed by
6984   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6985   struct ActOnFDArgs {
6986     Scope *S;
6987     Declarator &D;
6988     MultiTemplateParamsArg TemplateParamLists;
6989     bool AddToScope;
6990   };
6991 } // end anonymous namespace
6992
6993 namespace {
6994
6995 // Callback to only accept typo corrections that have a non-zero edit distance.
6996 // Also only accept corrections that have the same parent decl.
6997 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6998  public:
6999   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7000                             CXXRecordDecl *Parent)
7001       : Context(Context), OriginalFD(TypoFD),
7002         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7003
7004   bool ValidateCandidate(const TypoCorrection &candidate) override {
7005     if (candidate.getEditDistance() == 0)
7006       return false;
7007
7008     SmallVector<unsigned, 1> MismatchedParams;
7009     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7010                                           CDeclEnd = candidate.end();
7011          CDecl != CDeclEnd; ++CDecl) {
7012       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7013
7014       if (FD && !FD->hasBody() &&
7015           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7016         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7017           CXXRecordDecl *Parent = MD->getParent();
7018           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7019             return true;
7020         } else if (!ExpectedParent) {
7021           return true;
7022         }
7023       }
7024     }
7025
7026     return false;
7027   }
7028
7029  private:
7030   ASTContext &Context;
7031   FunctionDecl *OriginalFD;
7032   CXXRecordDecl *ExpectedParent;
7033 };
7034
7035 } // end anonymous namespace
7036
7037 /// \brief Generate diagnostics for an invalid function redeclaration.
7038 ///
7039 /// This routine handles generating the diagnostic messages for an invalid
7040 /// function redeclaration, including finding possible similar declarations
7041 /// or performing typo correction if there are no previous declarations with
7042 /// the same name.
7043 ///
7044 /// Returns a NamedDecl iff typo correction was performed and substituting in
7045 /// the new declaration name does not cause new errors.
7046 static NamedDecl *DiagnoseInvalidRedeclaration(
7047     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7048     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7049   DeclarationName Name = NewFD->getDeclName();
7050   DeclContext *NewDC = NewFD->getDeclContext();
7051   SmallVector<unsigned, 1> MismatchedParams;
7052   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7053   TypoCorrection Correction;
7054   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7055   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7056                                    : diag::err_member_decl_does_not_match;
7057   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7058                     IsLocalFriend ? Sema::LookupLocalFriendName
7059                                   : Sema::LookupOrdinaryName,
7060                     Sema::ForRedeclaration);
7061
7062   NewFD->setInvalidDecl();
7063   if (IsLocalFriend)
7064     SemaRef.LookupName(Prev, S);
7065   else
7066     SemaRef.LookupQualifiedName(Prev, NewDC);
7067   assert(!Prev.isAmbiguous() &&
7068          "Cannot have an ambiguity in previous-declaration lookup");
7069   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7070   if (!Prev.empty()) {
7071     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7072          Func != FuncEnd; ++Func) {
7073       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7074       if (FD &&
7075           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7076         // Add 1 to the index so that 0 can mean the mismatch didn't
7077         // involve a parameter
7078         unsigned ParamNum =
7079             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7080         NearMatches.push_back(std::make_pair(FD, ParamNum));
7081       }
7082     }
7083   // If the qualified name lookup yielded nothing, try typo correction
7084   } else if ((Correction = SemaRef.CorrectTypo(
7085                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7086                   &ExtraArgs.D.getCXXScopeSpec(),
7087                   llvm::make_unique<DifferentNameValidatorCCC>(
7088                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7089                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7090     // Set up everything for the call to ActOnFunctionDeclarator
7091     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7092                               ExtraArgs.D.getIdentifierLoc());
7093     Previous.clear();
7094     Previous.setLookupName(Correction.getCorrection());
7095     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7096                                     CDeclEnd = Correction.end();
7097          CDecl != CDeclEnd; ++CDecl) {
7098       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7099       if (FD && !FD->hasBody() &&
7100           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7101         Previous.addDecl(FD);
7102       }
7103     }
7104     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7105
7106     NamedDecl *Result;
7107     // Retry building the function declaration with the new previous
7108     // declarations, and with errors suppressed.
7109     {
7110       // Trap errors.
7111       Sema::SFINAETrap Trap(SemaRef);
7112
7113       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7114       // pieces need to verify the typo-corrected C++ declaration and hopefully
7115       // eliminate the need for the parameter pack ExtraArgs.
7116       Result = SemaRef.ActOnFunctionDeclarator(
7117           ExtraArgs.S, ExtraArgs.D,
7118           Correction.getCorrectionDecl()->getDeclContext(),
7119           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7120           ExtraArgs.AddToScope);
7121
7122       if (Trap.hasErrorOccurred())
7123         Result = nullptr;
7124     }
7125
7126     if (Result) {
7127       // Determine which correction we picked.
7128       Decl *Canonical = Result->getCanonicalDecl();
7129       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7130            I != E; ++I)
7131         if ((*I)->getCanonicalDecl() == Canonical)
7132           Correction.setCorrectionDecl(*I);
7133
7134       SemaRef.diagnoseTypo(
7135           Correction,
7136           SemaRef.PDiag(IsLocalFriend
7137                           ? diag::err_no_matching_local_friend_suggest
7138                           : diag::err_member_decl_does_not_match_suggest)
7139             << Name << NewDC << IsDefinition);
7140       return Result;
7141     }
7142
7143     // Pretend the typo correction never occurred
7144     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7145                               ExtraArgs.D.getIdentifierLoc());
7146     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7147     Previous.clear();
7148     Previous.setLookupName(Name);
7149   }
7150
7151   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7152       << Name << NewDC << IsDefinition << NewFD->getLocation();
7153
7154   bool NewFDisConst = false;
7155   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7156     NewFDisConst = NewMD->isConst();
7157
7158   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7159        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7160        NearMatch != NearMatchEnd; ++NearMatch) {
7161     FunctionDecl *FD = NearMatch->first;
7162     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7163     bool FDisConst = MD && MD->isConst();
7164     bool IsMember = MD || !IsLocalFriend;
7165
7166     // FIXME: These notes are poorly worded for the local friend case.
7167     if (unsigned Idx = NearMatch->second) {
7168       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7169       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7170       if (Loc.isInvalid()) Loc = FD->getLocation();
7171       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7172                                  : diag::note_local_decl_close_param_match)
7173         << Idx << FDParam->getType()
7174         << NewFD->getParamDecl(Idx - 1)->getType();
7175     } else if (FDisConst != NewFDisConst) {
7176       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7177           << NewFDisConst << FD->getSourceRange().getEnd();
7178     } else
7179       SemaRef.Diag(FD->getLocation(),
7180                    IsMember ? diag::note_member_def_close_match
7181                             : diag::note_local_decl_close_match);
7182   }
7183   return nullptr;
7184 }
7185
7186 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7187   switch (D.getDeclSpec().getStorageClassSpec()) {
7188   default: llvm_unreachable("Unknown storage class!");
7189   case DeclSpec::SCS_auto:
7190   case DeclSpec::SCS_register:
7191   case DeclSpec::SCS_mutable:
7192     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7193                  diag::err_typecheck_sclass_func);
7194     D.setInvalidType();
7195     break;
7196   case DeclSpec::SCS_unspecified: break;
7197   case DeclSpec::SCS_extern:
7198     if (D.getDeclSpec().isExternInLinkageSpec())
7199       return SC_None;
7200     return SC_Extern;
7201   case DeclSpec::SCS_static: {
7202     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7203       // C99 6.7.1p5:
7204       //   The declaration of an identifier for a function that has
7205       //   block scope shall have no explicit storage-class specifier
7206       //   other than extern
7207       // See also (C++ [dcl.stc]p4).
7208       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7209                    diag::err_static_block_func);
7210       break;
7211     } else
7212       return SC_Static;
7213   }
7214   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7215   }
7216
7217   // No explicit storage class has already been returned
7218   return SC_None;
7219 }
7220
7221 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7222                                            DeclContext *DC, QualType &R,
7223                                            TypeSourceInfo *TInfo,
7224                                            StorageClass SC,
7225                                            bool &IsVirtualOkay) {
7226   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7227   DeclarationName Name = NameInfo.getName();
7228
7229   FunctionDecl *NewFD = nullptr;
7230   bool isInline = D.getDeclSpec().isInlineSpecified();
7231
7232   if (!SemaRef.getLangOpts().CPlusPlus) {
7233     // Determine whether the function was written with a
7234     // prototype. This true when:
7235     //   - there is a prototype in the declarator, or
7236     //   - the type R of the function is some kind of typedef or other reference
7237     //     to a type name (which eventually refers to a function type).
7238     bool HasPrototype =
7239       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7240       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7241
7242     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7243                                  D.getLocStart(), NameInfo, R,
7244                                  TInfo, SC, isInline,
7245                                  HasPrototype, false);
7246     if (D.isInvalidType())
7247       NewFD->setInvalidDecl();
7248
7249     return NewFD;
7250   }
7251
7252   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7253   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7254
7255   // Check that the return type is not an abstract class type.
7256   // For record types, this is done by the AbstractClassUsageDiagnoser once
7257   // the class has been completely parsed.
7258   if (!DC->isRecord() &&
7259       SemaRef.RequireNonAbstractType(
7260           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7261           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7262     D.setInvalidType();
7263
7264   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7265     // This is a C++ constructor declaration.
7266     assert(DC->isRecord() &&
7267            "Constructors can only be declared in a member context");
7268
7269     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7270     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7271                                       D.getLocStart(), NameInfo,
7272                                       R, TInfo, isExplicit, isInline,
7273                                       /*isImplicitlyDeclared=*/false,
7274                                       isConstexpr);
7275
7276   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7277     // This is a C++ destructor declaration.
7278     if (DC->isRecord()) {
7279       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7280       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7281       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7282                                         SemaRef.Context, Record,
7283                                         D.getLocStart(),
7284                                         NameInfo, R, TInfo, isInline,
7285                                         /*isImplicitlyDeclared=*/false);
7286
7287       // If the class is complete, then we now create the implicit exception
7288       // specification. If the class is incomplete or dependent, we can't do
7289       // it yet.
7290       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7291           Record->getDefinition() && !Record->isBeingDefined() &&
7292           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7293         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7294       }
7295
7296       IsVirtualOkay = true;
7297       return NewDD;
7298
7299     } else {
7300       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7301       D.setInvalidType();
7302
7303       // Create a FunctionDecl to satisfy the function definition parsing
7304       // code path.
7305       return FunctionDecl::Create(SemaRef.Context, DC,
7306                                   D.getLocStart(),
7307                                   D.getIdentifierLoc(), Name, R, TInfo,
7308                                   SC, isInline,
7309                                   /*hasPrototype=*/true, isConstexpr);
7310     }
7311
7312   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7313     if (!DC->isRecord()) {
7314       SemaRef.Diag(D.getIdentifierLoc(),
7315            diag::err_conv_function_not_member);
7316       return nullptr;
7317     }
7318
7319     SemaRef.CheckConversionDeclarator(D, R, SC);
7320     IsVirtualOkay = true;
7321     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7322                                      D.getLocStart(), NameInfo,
7323                                      R, TInfo, isInline, isExplicit,
7324                                      isConstexpr, SourceLocation());
7325
7326   } else if (DC->isRecord()) {
7327     // If the name of the function is the same as the name of the record,
7328     // then this must be an invalid constructor that has a return type.
7329     // (The parser checks for a return type and makes the declarator a
7330     // constructor if it has no return type).
7331     if (Name.getAsIdentifierInfo() &&
7332         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7333       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7334         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7335         << SourceRange(D.getIdentifierLoc());
7336       return nullptr;
7337     }
7338
7339     // This is a C++ method declaration.
7340     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7341                                                cast<CXXRecordDecl>(DC),
7342                                                D.getLocStart(), NameInfo, R,
7343                                                TInfo, SC, isInline,
7344                                                isConstexpr, SourceLocation());
7345     IsVirtualOkay = !Ret->isStatic();
7346     return Ret;
7347   } else {
7348     bool isFriend =
7349         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7350     if (!isFriend && SemaRef.CurContext->isRecord())
7351       return nullptr;
7352
7353     // Determine whether the function was written with a
7354     // prototype. This true when:
7355     //   - we're in C++ (where every function has a prototype),
7356     return FunctionDecl::Create(SemaRef.Context, DC,
7357                                 D.getLocStart(),
7358                                 NameInfo, R, TInfo, SC, isInline,
7359                                 true/*HasPrototype*/, isConstexpr);
7360   }
7361 }
7362
7363 enum OpenCLParamType {
7364   ValidKernelParam,
7365   PtrPtrKernelParam,
7366   PtrKernelParam,
7367   PrivatePtrKernelParam,
7368   InvalidKernelParam,
7369   RecordKernelParam
7370 };
7371
7372 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7373   if (PT->isPointerType()) {
7374     QualType PointeeType = PT->getPointeeType();
7375     if (PointeeType->isPointerType())
7376       return PtrPtrKernelParam;
7377     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7378                                               : PtrKernelParam;
7379   }
7380
7381   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7382   // be used as builtin types.
7383
7384   if (PT->isImageType())
7385     return PtrKernelParam;
7386
7387   if (PT->isBooleanType())
7388     return InvalidKernelParam;
7389
7390   if (PT->isEventT())
7391     return InvalidKernelParam;
7392
7393   if (PT->isHalfType())
7394     return InvalidKernelParam;
7395
7396   if (PT->isRecordType())
7397     return RecordKernelParam;
7398
7399   return ValidKernelParam;
7400 }
7401
7402 static void checkIsValidOpenCLKernelParameter(
7403   Sema &S,
7404   Declarator &D,
7405   ParmVarDecl *Param,
7406   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7407   QualType PT = Param->getType();
7408
7409   // Cache the valid types we encounter to avoid rechecking structs that are
7410   // used again
7411   if (ValidTypes.count(PT.getTypePtr()))
7412     return;
7413
7414   switch (getOpenCLKernelParameterType(PT)) {
7415   case PtrPtrKernelParam:
7416     // OpenCL v1.2 s6.9.a:
7417     // A kernel function argument cannot be declared as a
7418     // pointer to a pointer type.
7419     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7420     D.setInvalidType();
7421     return;
7422
7423   case PrivatePtrKernelParam:
7424     // OpenCL v1.2 s6.9.a:
7425     // A kernel function argument cannot be declared as a
7426     // pointer to the private address space.
7427     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7428     D.setInvalidType();
7429     return;
7430
7431     // OpenCL v1.2 s6.9.k:
7432     // Arguments to kernel functions in a program cannot be declared with the
7433     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7434     // uintptr_t or a struct and/or union that contain fields declared to be
7435     // one of these built-in scalar types.
7436
7437   case InvalidKernelParam:
7438     // OpenCL v1.2 s6.8 n:
7439     // A kernel function argument cannot be declared
7440     // of event_t type.
7441     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7442     D.setInvalidType();
7443     return;
7444
7445   case PtrKernelParam:
7446   case ValidKernelParam:
7447     ValidTypes.insert(PT.getTypePtr());
7448     return;
7449
7450   case RecordKernelParam:
7451     break;
7452   }
7453
7454   // Track nested structs we will inspect
7455   SmallVector<const Decl *, 4> VisitStack;
7456
7457   // Track where we are in the nested structs. Items will migrate from
7458   // VisitStack to HistoryStack as we do the DFS for bad field.
7459   SmallVector<const FieldDecl *, 4> HistoryStack;
7460   HistoryStack.push_back(nullptr);
7461
7462   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7463   VisitStack.push_back(PD);
7464
7465   assert(VisitStack.back() && "First decl null?");
7466
7467   do {
7468     const Decl *Next = VisitStack.pop_back_val();
7469     if (!Next) {
7470       assert(!HistoryStack.empty());
7471       // Found a marker, we have gone up a level
7472       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7473         ValidTypes.insert(Hist->getType().getTypePtr());
7474
7475       continue;
7476     }
7477
7478     // Adds everything except the original parameter declaration (which is not a
7479     // field itself) to the history stack.
7480     const RecordDecl *RD;
7481     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7482       HistoryStack.push_back(Field);
7483       RD = Field->getType()->castAs<RecordType>()->getDecl();
7484     } else {
7485       RD = cast<RecordDecl>(Next);
7486     }
7487
7488     // Add a null marker so we know when we've gone back up a level
7489     VisitStack.push_back(nullptr);
7490
7491     for (const auto *FD : RD->fields()) {
7492       QualType QT = FD->getType();
7493
7494       if (ValidTypes.count(QT.getTypePtr()))
7495         continue;
7496
7497       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7498       if (ParamType == ValidKernelParam)
7499         continue;
7500
7501       if (ParamType == RecordKernelParam) {
7502         VisitStack.push_back(FD);
7503         continue;
7504       }
7505
7506       // OpenCL v1.2 s6.9.p:
7507       // Arguments to kernel functions that are declared to be a struct or union
7508       // do not allow OpenCL objects to be passed as elements of the struct or
7509       // union.
7510       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7511           ParamType == PrivatePtrKernelParam) {
7512         S.Diag(Param->getLocation(),
7513                diag::err_record_with_pointers_kernel_param)
7514           << PT->isUnionType()
7515           << PT;
7516       } else {
7517         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7518       }
7519
7520       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7521         << PD->getDeclName();
7522
7523       // We have an error, now let's go back up through history and show where
7524       // the offending field came from
7525       for (ArrayRef<const FieldDecl *>::const_iterator
7526                I = HistoryStack.begin() + 1,
7527                E = HistoryStack.end();
7528            I != E; ++I) {
7529         const FieldDecl *OuterField = *I;
7530         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7531           << OuterField->getType();
7532       }
7533
7534       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7535         << QT->isPointerType()
7536         << QT;
7537       D.setInvalidType();
7538       return;
7539     }
7540   } while (!VisitStack.empty());
7541 }
7542
7543 NamedDecl*
7544 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7545                               TypeSourceInfo *TInfo, LookupResult &Previous,
7546                               MultiTemplateParamsArg TemplateParamLists,
7547                               bool &AddToScope) {
7548   QualType R = TInfo->getType();
7549
7550   assert(R.getTypePtr()->isFunctionType());
7551
7552   // TODO: consider using NameInfo for diagnostic.
7553   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7554   DeclarationName Name = NameInfo.getName();
7555   StorageClass SC = getFunctionStorageClass(*this, D);
7556
7557   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7558     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7559          diag::err_invalid_thread)
7560       << DeclSpec::getSpecifierName(TSCS);
7561
7562   if (D.isFirstDeclarationOfMember())
7563     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7564                            D.getIdentifierLoc());
7565
7566   bool isFriend = false;
7567   FunctionTemplateDecl *FunctionTemplate = nullptr;
7568   bool isExplicitSpecialization = false;
7569   bool isFunctionTemplateSpecialization = false;
7570
7571   bool isDependentClassScopeExplicitSpecialization = false;
7572   bool HasExplicitTemplateArgs = false;
7573   TemplateArgumentListInfo TemplateArgs;
7574
7575   bool isVirtualOkay = false;
7576
7577   DeclContext *OriginalDC = DC;
7578   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7579
7580   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7581                                               isVirtualOkay);
7582   if (!NewFD) return nullptr;
7583
7584   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7585     NewFD->setTopLevelDeclInObjCContainer();
7586
7587   // Set the lexical context. If this is a function-scope declaration, or has a
7588   // C++ scope specifier, or is the object of a friend declaration, the lexical
7589   // context will be different from the semantic context.
7590   NewFD->setLexicalDeclContext(CurContext);
7591
7592   if (IsLocalExternDecl)
7593     NewFD->setLocalExternDecl();
7594
7595   if (getLangOpts().CPlusPlus) {
7596     bool isInline = D.getDeclSpec().isInlineSpecified();
7597     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7598     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7599     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7600     bool isConcept = D.getDeclSpec().isConceptSpecified();
7601     isFriend = D.getDeclSpec().isFriendSpecified();
7602     if (isFriend && !isInline && D.isFunctionDefinition()) {
7603       // C++ [class.friend]p5
7604       //   A function can be defined in a friend declaration of a
7605       //   class . . . . Such a function is implicitly inline.
7606       NewFD->setImplicitlyInline();
7607     }
7608
7609     // If this is a method defined in an __interface, and is not a constructor
7610     // or an overloaded operator, then set the pure flag (isVirtual will already
7611     // return true).
7612     if (const CXXRecordDecl *Parent =
7613           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7614       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7615         NewFD->setPure(true);
7616
7617       // C++ [class.union]p2
7618       //   A union can have member functions, but not virtual functions.
7619       if (isVirtual && Parent->isUnion())
7620         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7621     }
7622
7623     SetNestedNameSpecifier(NewFD, D);
7624     isExplicitSpecialization = false;
7625     isFunctionTemplateSpecialization = false;
7626     if (D.isInvalidType())
7627       NewFD->setInvalidDecl();
7628
7629     // Match up the template parameter lists with the scope specifier, then
7630     // determine whether we have a template or a template specialization.
7631     bool Invalid = false;
7632     if (TemplateParameterList *TemplateParams =
7633             MatchTemplateParametersToScopeSpecifier(
7634                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7635                 D.getCXXScopeSpec(),
7636                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7637                     ? D.getName().TemplateId
7638                     : nullptr,
7639                 TemplateParamLists, isFriend, isExplicitSpecialization,
7640                 Invalid)) {
7641       if (TemplateParams->size() > 0) {
7642         // This is a function template
7643
7644         // Check that we can declare a template here.
7645         if (CheckTemplateDeclScope(S, TemplateParams))
7646           NewFD->setInvalidDecl();
7647
7648         // A destructor cannot be a template.
7649         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7650           Diag(NewFD->getLocation(), diag::err_destructor_template);
7651           NewFD->setInvalidDecl();
7652         }
7653
7654         // If we're adding a template to a dependent context, we may need to
7655         // rebuilding some of the types used within the template parameter list,
7656         // now that we know what the current instantiation is.
7657         if (DC->isDependentContext()) {
7658           ContextRAII SavedContext(*this, DC);
7659           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7660             Invalid = true;
7661         }
7662
7663         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7664                                                         NewFD->getLocation(),
7665                                                         Name, TemplateParams,
7666                                                         NewFD);
7667         FunctionTemplate->setLexicalDeclContext(CurContext);
7668         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7669
7670         // For source fidelity, store the other template param lists.
7671         if (TemplateParamLists.size() > 1) {
7672           NewFD->setTemplateParameterListsInfo(Context,
7673                                                TemplateParamLists.drop_back(1));
7674         }
7675       } else {
7676         // This is a function template specialization.
7677         isFunctionTemplateSpecialization = true;
7678         // For source fidelity, store all the template param lists.
7679         if (TemplateParamLists.size() > 0)
7680           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7681
7682         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7683         if (isFriend) {
7684           // We want to remove the "template<>", found here.
7685           SourceRange RemoveRange = TemplateParams->getSourceRange();
7686
7687           // If we remove the template<> and the name is not a
7688           // template-id, we're actually silently creating a problem:
7689           // the friend declaration will refer to an untemplated decl,
7690           // and clearly the user wants a template specialization.  So
7691           // we need to insert '<>' after the name.
7692           SourceLocation InsertLoc;
7693           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7694             InsertLoc = D.getName().getSourceRange().getEnd();
7695             InsertLoc = getLocForEndOfToken(InsertLoc);
7696           }
7697
7698           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7699             << Name << RemoveRange
7700             << FixItHint::CreateRemoval(RemoveRange)
7701             << FixItHint::CreateInsertion(InsertLoc, "<>");
7702         }
7703       }
7704     }
7705     else {
7706       // All template param lists were matched against the scope specifier:
7707       // this is NOT (an explicit specialization of) a template.
7708       if (TemplateParamLists.size() > 0)
7709         // For source fidelity, store all the template param lists.
7710         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7711     }
7712
7713     if (Invalid) {
7714       NewFD->setInvalidDecl();
7715       if (FunctionTemplate)
7716         FunctionTemplate->setInvalidDecl();
7717     }
7718
7719     // C++ [dcl.fct.spec]p5:
7720     //   The virtual specifier shall only be used in declarations of
7721     //   nonstatic class member functions that appear within a
7722     //   member-specification of a class declaration; see 10.3.
7723     //
7724     if (isVirtual && !NewFD->isInvalidDecl()) {
7725       if (!isVirtualOkay) {
7726         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7727              diag::err_virtual_non_function);
7728       } else if (!CurContext->isRecord()) {
7729         // 'virtual' was specified outside of the class.
7730         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7731              diag::err_virtual_out_of_class)
7732           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7733       } else if (NewFD->getDescribedFunctionTemplate()) {
7734         // C++ [temp.mem]p3:
7735         //  A member function template shall not be virtual.
7736         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7737              diag::err_virtual_member_function_template)
7738           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7739       } else {
7740         // Okay: Add virtual to the method.
7741         NewFD->setVirtualAsWritten(true);
7742       }
7743
7744       if (getLangOpts().CPlusPlus14 &&
7745           NewFD->getReturnType()->isUndeducedType())
7746         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7747     }
7748
7749     if (getLangOpts().CPlusPlus14 &&
7750         (NewFD->isDependentContext() ||
7751          (isFriend && CurContext->isDependentContext())) &&
7752         NewFD->getReturnType()->isUndeducedType()) {
7753       // If the function template is referenced directly (for instance, as a
7754       // member of the current instantiation), pretend it has a dependent type.
7755       // This is not really justified by the standard, but is the only sane
7756       // thing to do.
7757       // FIXME: For a friend function, we have not marked the function as being
7758       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7759       const FunctionProtoType *FPT =
7760           NewFD->getType()->castAs<FunctionProtoType>();
7761       QualType Result =
7762           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7763       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7764                                              FPT->getExtProtoInfo()));
7765     }
7766
7767     // C++ [dcl.fct.spec]p3:
7768     //  The inline specifier shall not appear on a block scope function
7769     //  declaration.
7770     if (isInline && !NewFD->isInvalidDecl()) {
7771       if (CurContext->isFunctionOrMethod()) {
7772         // 'inline' is not allowed on block scope function declaration.
7773         Diag(D.getDeclSpec().getInlineSpecLoc(),
7774              diag::err_inline_declaration_block_scope) << Name
7775           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7776       }
7777     }
7778
7779     // C++ [dcl.fct.spec]p6:
7780     //  The explicit specifier shall be used only in the declaration of a
7781     //  constructor or conversion function within its class definition;
7782     //  see 12.3.1 and 12.3.2.
7783     if (isExplicit && !NewFD->isInvalidDecl()) {
7784       if (!CurContext->isRecord()) {
7785         // 'explicit' was specified outside of the class.
7786         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7787              diag::err_explicit_out_of_class)
7788           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7789       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7790                  !isa<CXXConversionDecl>(NewFD)) {
7791         // 'explicit' was specified on a function that wasn't a constructor
7792         // or conversion function.
7793         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7794              diag::err_explicit_non_ctor_or_conv_function)
7795           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7796       }
7797     }
7798
7799     if (isConstexpr) {
7800       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7801       // are implicitly inline.
7802       NewFD->setImplicitlyInline();
7803
7804       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7805       // be either constructors or to return a literal type. Therefore,
7806       // destructors cannot be declared constexpr.
7807       if (isa<CXXDestructorDecl>(NewFD))
7808         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7809     }
7810
7811     if (isConcept) {
7812       // This is a function concept.
7813       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
7814         FTD->setConcept();
7815
7816       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7817       // applied only to the definition of a function template [...]
7818       if (!D.isFunctionDefinition()) {
7819         Diag(D.getDeclSpec().getConceptSpecLoc(),
7820              diag::err_function_concept_not_defined);
7821         NewFD->setInvalidDecl();
7822       }
7823
7824       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7825       // have no exception-specification and is treated as if it were specified
7826       // with noexcept(true) (15.4). [...]
7827       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7828         if (FPT->hasExceptionSpec()) {
7829           SourceRange Range;
7830           if (D.isFunctionDeclarator())
7831             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7832           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7833               << FixItHint::CreateRemoval(Range);
7834           NewFD->setInvalidDecl();
7835         } else {
7836           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7837         }
7838
7839         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7840         // following restrictions:
7841         // - The declared return type shall have the type bool.
7842         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
7843           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
7844           NewFD->setInvalidDecl();
7845         }
7846
7847         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7848         // following restrictions:
7849         // - The declaration's parameter list shall be equivalent to an empty
7850         //   parameter list.
7851         if (FPT->getNumParams() > 0 || FPT->isVariadic())
7852           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7853       }
7854
7855       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7856       // implicity defined to be a constexpr declaration (implicitly inline)
7857       NewFD->setImplicitlyInline();
7858
7859       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7860       // be declared with the thread_local, inline, friend, or constexpr
7861       // specifiers, [...]
7862       if (isInline) {
7863         Diag(D.getDeclSpec().getInlineSpecLoc(),
7864              diag::err_concept_decl_invalid_specifiers)
7865             << 1 << 1;
7866         NewFD->setInvalidDecl(true);
7867       }
7868
7869       if (isFriend) {
7870         Diag(D.getDeclSpec().getFriendSpecLoc(),
7871              diag::err_concept_decl_invalid_specifiers)
7872             << 1 << 2;
7873         NewFD->setInvalidDecl(true);
7874       }
7875
7876       if (isConstexpr) {
7877         Diag(D.getDeclSpec().getConstexprSpecLoc(),
7878              diag::err_concept_decl_invalid_specifiers)
7879             << 1 << 3;
7880         NewFD->setInvalidDecl(true);
7881       }
7882
7883       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7884       // applied only to the definition of a function template or variable
7885       // template, declared in namespace scope.
7886       if (isFunctionTemplateSpecialization) {
7887         Diag(D.getDeclSpec().getConceptSpecLoc(),
7888              diag::err_concept_specified_specialization) << 1;
7889         NewFD->setInvalidDecl(true);
7890         return NewFD;
7891       }
7892     }
7893
7894     // If __module_private__ was specified, mark the function accordingly.
7895     if (D.getDeclSpec().isModulePrivateSpecified()) {
7896       if (isFunctionTemplateSpecialization) {
7897         SourceLocation ModulePrivateLoc
7898           = D.getDeclSpec().getModulePrivateSpecLoc();
7899         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7900           << 0
7901           << FixItHint::CreateRemoval(ModulePrivateLoc);
7902       } else {
7903         NewFD->setModulePrivate();
7904         if (FunctionTemplate)
7905           FunctionTemplate->setModulePrivate();
7906       }
7907     }
7908
7909     if (isFriend) {
7910       if (FunctionTemplate) {
7911         FunctionTemplate->setObjectOfFriendDecl();
7912         FunctionTemplate->setAccess(AS_public);
7913       }
7914       NewFD->setObjectOfFriendDecl();
7915       NewFD->setAccess(AS_public);
7916     }
7917
7918     // If a function is defined as defaulted or deleted, mark it as such now.
7919     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7920     // definition kind to FDK_Definition.
7921     switch (D.getFunctionDefinitionKind()) {
7922       case FDK_Declaration:
7923       case FDK_Definition:
7924         break;
7925
7926       case FDK_Defaulted:
7927         NewFD->setDefaulted();
7928         break;
7929
7930       case FDK_Deleted:
7931         NewFD->setDeletedAsWritten();
7932         break;
7933     }
7934
7935     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7936         D.isFunctionDefinition()) {
7937       // C++ [class.mfct]p2:
7938       //   A member function may be defined (8.4) in its class definition, in
7939       //   which case it is an inline member function (7.1.2)
7940       NewFD->setImplicitlyInline();
7941     }
7942
7943     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7944         !CurContext->isRecord()) {
7945       // C++ [class.static]p1:
7946       //   A data or function member of a class may be declared static
7947       //   in a class definition, in which case it is a static member of
7948       //   the class.
7949
7950       // Complain about the 'static' specifier if it's on an out-of-line
7951       // member function definition.
7952       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7953            diag::err_static_out_of_line)
7954         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7955     }
7956
7957     // C++11 [except.spec]p15:
7958     //   A deallocation function with no exception-specification is treated
7959     //   as if it were specified with noexcept(true).
7960     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7961     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7962          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7963         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7964       NewFD->setType(Context.getFunctionType(
7965           FPT->getReturnType(), FPT->getParamTypes(),
7966           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7967   }
7968
7969   // Filter out previous declarations that don't match the scope.
7970   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7971                        D.getCXXScopeSpec().isNotEmpty() ||
7972                        isExplicitSpecialization ||
7973                        isFunctionTemplateSpecialization);
7974
7975   // Handle GNU asm-label extension (encoded as an attribute).
7976   if (Expr *E = (Expr*) D.getAsmLabel()) {
7977     // The parser guarantees this is a string.
7978     StringLiteral *SE = cast<StringLiteral>(E);
7979     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7980                                                 SE->getString(), 0));
7981   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7982     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7983       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7984     if (I != ExtnameUndeclaredIdentifiers.end()) {
7985       if (isDeclExternC(NewFD)) {
7986         NewFD->addAttr(I->second);
7987         ExtnameUndeclaredIdentifiers.erase(I);
7988       } else
7989         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
7990             << /*Variable*/0 << NewFD;
7991     }
7992   }
7993
7994   // Copy the parameter declarations from the declarator D to the function
7995   // declaration NewFD, if they are available.  First scavenge them into Params.
7996   SmallVector<ParmVarDecl*, 16> Params;
7997   if (D.isFunctionDeclarator()) {
7998     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7999
8000     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8001     // function that takes no arguments, not a function that takes a
8002     // single void argument.
8003     // We let through "const void" here because Sema::GetTypeForDeclarator
8004     // already checks for that case.
8005     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8006       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8007         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8008         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8009         Param->setDeclContext(NewFD);
8010         Params.push_back(Param);
8011
8012         if (Param->isInvalidDecl())
8013           NewFD->setInvalidDecl();
8014       }
8015     }
8016   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8017     // When we're declaring a function with a typedef, typeof, etc as in the
8018     // following example, we'll need to synthesize (unnamed)
8019     // parameters for use in the declaration.
8020     //
8021     // @code
8022     // typedef void fn(int);
8023     // fn f;
8024     // @endcode
8025
8026     // Synthesize a parameter for each argument type.
8027     for (const auto &AI : FT->param_types()) {
8028       ParmVarDecl *Param =
8029           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8030       Param->setScopeInfo(0, Params.size());
8031       Params.push_back(Param);
8032     }
8033   } else {
8034     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8035            "Should not need args for typedef of non-prototype fn");
8036   }
8037
8038   // Finally, we know we have the right number of parameters, install them.
8039   NewFD->setParams(Params);
8040
8041   // Find all anonymous symbols defined during the declaration of this function
8042   // and add to NewFD. This lets us track decls such 'enum Y' in:
8043   //
8044   //   void f(enum Y {AA} x) {}
8045   //
8046   // which would otherwise incorrectly end up in the translation unit scope.
8047   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
8048   DeclsInPrototypeScope.clear();
8049
8050   if (D.getDeclSpec().isNoreturnSpecified())
8051     NewFD->addAttr(
8052         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8053                                        Context, 0));
8054
8055   // Functions returning a variably modified type violate C99 6.7.5.2p2
8056   // because all functions have linkage.
8057   if (!NewFD->isInvalidDecl() &&
8058       NewFD->getReturnType()->isVariablyModifiedType()) {
8059     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8060     NewFD->setInvalidDecl();
8061   }
8062
8063   // Apply an implicit SectionAttr if #pragma code_seg is active.
8064   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8065       !NewFD->hasAttr<SectionAttr>()) {
8066     NewFD->addAttr(
8067         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8068                                     CodeSegStack.CurrentValue->getString(),
8069                                     CodeSegStack.CurrentPragmaLocation));
8070     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8071                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8072                          ASTContext::PSF_Read,
8073                      NewFD))
8074       NewFD->dropAttr<SectionAttr>();
8075   }
8076
8077   // Handle attributes.
8078   ProcessDeclAttributes(S, NewFD, D);
8079
8080   if (getLangOpts().CUDA)
8081     maybeAddCUDAHostDeviceAttrs(S, NewFD, Previous);
8082
8083   if (getLangOpts().OpenCL) {
8084     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8085     // type declaration will generate a compilation error.
8086     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8087     if (AddressSpace == LangAS::opencl_local ||
8088         AddressSpace == LangAS::opencl_global ||
8089         AddressSpace == LangAS::opencl_constant) {
8090       Diag(NewFD->getLocation(),
8091            diag::err_opencl_return_value_with_address_space);
8092       NewFD->setInvalidDecl();
8093     }
8094   }
8095
8096   if (!getLangOpts().CPlusPlus) {
8097     // Perform semantic checking on the function declaration.
8098     bool isExplicitSpecialization=false;
8099     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8100       CheckMain(NewFD, D.getDeclSpec());
8101
8102     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8103       CheckMSVCRTEntryPoint(NewFD);
8104
8105     if (!NewFD->isInvalidDecl())
8106       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8107                                                   isExplicitSpecialization));
8108     else if (!Previous.empty())
8109       // Recover gracefully from an invalid redeclaration.
8110       D.setRedeclaration(true);
8111     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8112             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8113            "previous declaration set still overloaded");
8114
8115     // Diagnose no-prototype function declarations with calling conventions that
8116     // don't support variadic calls. Only do this in C and do it after merging
8117     // possibly prototyped redeclarations.
8118     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8119     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8120       CallingConv CC = FT->getExtInfo().getCC();
8121       if (!supportsVariadicCall(CC)) {
8122         // Windows system headers sometimes accidentally use stdcall without
8123         // (void) parameters, so we relax this to a warning.
8124         int DiagID =
8125             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8126         Diag(NewFD->getLocation(), DiagID)
8127             << FunctionType::getNameForCallConv(CC);
8128       }
8129     }
8130   } else {
8131     // C++11 [replacement.functions]p3:
8132     //  The program's definitions shall not be specified as inline.
8133     //
8134     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8135     //
8136     // Suppress the diagnostic if the function is __attribute__((used)), since
8137     // that forces an external definition to be emitted.
8138     if (D.getDeclSpec().isInlineSpecified() &&
8139         NewFD->isReplaceableGlobalAllocationFunction() &&
8140         !NewFD->hasAttr<UsedAttr>())
8141       Diag(D.getDeclSpec().getInlineSpecLoc(),
8142            diag::ext_operator_new_delete_declared_inline)
8143         << NewFD->getDeclName();
8144
8145     // If the declarator is a template-id, translate the parser's template
8146     // argument list into our AST format.
8147     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8148       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8149       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8150       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8151       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8152                                          TemplateId->NumArgs);
8153       translateTemplateArguments(TemplateArgsPtr,
8154                                  TemplateArgs);
8155
8156       HasExplicitTemplateArgs = true;
8157
8158       if (NewFD->isInvalidDecl()) {
8159         HasExplicitTemplateArgs = false;
8160       } else if (FunctionTemplate) {
8161         // Function template with explicit template arguments.
8162         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8163           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8164
8165         HasExplicitTemplateArgs = false;
8166       } else {
8167         assert((isFunctionTemplateSpecialization ||
8168                 D.getDeclSpec().isFriendSpecified()) &&
8169                "should have a 'template<>' for this decl");
8170         // "friend void foo<>(int);" is an implicit specialization decl.
8171         isFunctionTemplateSpecialization = true;
8172       }
8173     } else if (isFriend && isFunctionTemplateSpecialization) {
8174       // This combination is only possible in a recovery case;  the user
8175       // wrote something like:
8176       //   template <> friend void foo(int);
8177       // which we're recovering from as if the user had written:
8178       //   friend void foo<>(int);
8179       // Go ahead and fake up a template id.
8180       HasExplicitTemplateArgs = true;
8181       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8182       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8183     }
8184
8185     // If it's a friend (and only if it's a friend), it's possible
8186     // that either the specialized function type or the specialized
8187     // template is dependent, and therefore matching will fail.  In
8188     // this case, don't check the specialization yet.
8189     bool InstantiationDependent = false;
8190     if (isFunctionTemplateSpecialization && isFriend &&
8191         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8192          TemplateSpecializationType::anyDependentTemplateArguments(
8193             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
8194             InstantiationDependent))) {
8195       assert(HasExplicitTemplateArgs &&
8196              "friend function specialization without template args");
8197       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8198                                                        Previous))
8199         NewFD->setInvalidDecl();
8200     } else if (isFunctionTemplateSpecialization) {
8201       if (CurContext->isDependentContext() && CurContext->isRecord()
8202           && !isFriend) {
8203         isDependentClassScopeExplicitSpecialization = true;
8204         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8205           diag::ext_function_specialization_in_class :
8206           diag::err_function_specialization_in_class)
8207           << NewFD->getDeclName();
8208       } else if (CheckFunctionTemplateSpecialization(NewFD,
8209                                   (HasExplicitTemplateArgs ? &TemplateArgs
8210                                                            : nullptr),
8211                                                      Previous))
8212         NewFD->setInvalidDecl();
8213
8214       // C++ [dcl.stc]p1:
8215       //   A storage-class-specifier shall not be specified in an explicit
8216       //   specialization (14.7.3)
8217       FunctionTemplateSpecializationInfo *Info =
8218           NewFD->getTemplateSpecializationInfo();
8219       if (Info && SC != SC_None) {
8220         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8221           Diag(NewFD->getLocation(),
8222                diag::err_explicit_specialization_inconsistent_storage_class)
8223             << SC
8224             << FixItHint::CreateRemoval(
8225                                       D.getDeclSpec().getStorageClassSpecLoc());
8226
8227         else
8228           Diag(NewFD->getLocation(),
8229                diag::ext_explicit_specialization_storage_class)
8230             << FixItHint::CreateRemoval(
8231                                       D.getDeclSpec().getStorageClassSpecLoc());
8232       }
8233     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8234       if (CheckMemberSpecialization(NewFD, Previous))
8235           NewFD->setInvalidDecl();
8236     }
8237
8238     // Perform semantic checking on the function declaration.
8239     if (!isDependentClassScopeExplicitSpecialization) {
8240       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8241         CheckMain(NewFD, D.getDeclSpec());
8242
8243       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8244         CheckMSVCRTEntryPoint(NewFD);
8245
8246       if (!NewFD->isInvalidDecl())
8247         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8248                                                     isExplicitSpecialization));
8249       else if (!Previous.empty())
8250         // Recover gracefully from an invalid redeclaration.
8251         D.setRedeclaration(true);
8252     }
8253
8254     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8255             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8256            "previous declaration set still overloaded");
8257
8258     NamedDecl *PrincipalDecl = (FunctionTemplate
8259                                 ? cast<NamedDecl>(FunctionTemplate)
8260                                 : NewFD);
8261
8262     if (isFriend && D.isRedeclaration()) {
8263       AccessSpecifier Access = AS_public;
8264       if (!NewFD->isInvalidDecl())
8265         Access = NewFD->getPreviousDecl()->getAccess();
8266
8267       NewFD->setAccess(Access);
8268       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8269     }
8270
8271     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8272         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8273       PrincipalDecl->setNonMemberOperator();
8274
8275     // If we have a function template, check the template parameter
8276     // list. This will check and merge default template arguments.
8277     if (FunctionTemplate) {
8278       FunctionTemplateDecl *PrevTemplate =
8279                                      FunctionTemplate->getPreviousDecl();
8280       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8281                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8282                                     : nullptr,
8283                             D.getDeclSpec().isFriendSpecified()
8284                               ? (D.isFunctionDefinition()
8285                                    ? TPC_FriendFunctionTemplateDefinition
8286                                    : TPC_FriendFunctionTemplate)
8287                               : (D.getCXXScopeSpec().isSet() &&
8288                                  DC && DC->isRecord() &&
8289                                  DC->isDependentContext())
8290                                   ? TPC_ClassTemplateMember
8291                                   : TPC_FunctionTemplate);
8292     }
8293
8294     if (NewFD->isInvalidDecl()) {
8295       // Ignore all the rest of this.
8296     } else if (!D.isRedeclaration()) {
8297       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8298                                        AddToScope };
8299       // Fake up an access specifier if it's supposed to be a class member.
8300       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8301         NewFD->setAccess(AS_public);
8302
8303       // Qualified decls generally require a previous declaration.
8304       if (D.getCXXScopeSpec().isSet()) {
8305         // ...with the major exception of templated-scope or
8306         // dependent-scope friend declarations.
8307
8308         // TODO: we currently also suppress this check in dependent
8309         // contexts because (1) the parameter depth will be off when
8310         // matching friend templates and (2) we might actually be
8311         // selecting a friend based on a dependent factor.  But there
8312         // are situations where these conditions don't apply and we
8313         // can actually do this check immediately.
8314         if (isFriend &&
8315             (TemplateParamLists.size() ||
8316              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8317              CurContext->isDependentContext())) {
8318           // ignore these
8319         } else {
8320           // The user tried to provide an out-of-line definition for a
8321           // function that is a member of a class or namespace, but there
8322           // was no such member function declared (C++ [class.mfct]p2,
8323           // C++ [namespace.memdef]p2). For example:
8324           //
8325           // class X {
8326           //   void f() const;
8327           // };
8328           //
8329           // void X::f() { } // ill-formed
8330           //
8331           // Complain about this problem, and attempt to suggest close
8332           // matches (e.g., those that differ only in cv-qualifiers and
8333           // whether the parameter types are references).
8334
8335           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8336                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8337             AddToScope = ExtraArgs.AddToScope;
8338             return Result;
8339           }
8340         }
8341
8342         // Unqualified local friend declarations are required to resolve
8343         // to something.
8344       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8345         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8346                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8347           AddToScope = ExtraArgs.AddToScope;
8348           return Result;
8349         }
8350       }
8351     } else if (!D.isFunctionDefinition() &&
8352                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8353                !isFriend && !isFunctionTemplateSpecialization &&
8354                !isExplicitSpecialization) {
8355       // An out-of-line member function declaration must also be a
8356       // definition (C++ [class.mfct]p2).
8357       // Note that this is not the case for explicit specializations of
8358       // function templates or member functions of class templates, per
8359       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8360       // extension for compatibility with old SWIG code which likes to
8361       // generate them.
8362       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8363         << D.getCXXScopeSpec().getRange();
8364     }
8365   }
8366
8367   ProcessPragmaWeak(S, NewFD);
8368   checkAttributesAfterMerging(*this, *NewFD);
8369
8370   AddKnownFunctionAttributes(NewFD);
8371
8372   if (NewFD->hasAttr<OverloadableAttr>() &&
8373       !NewFD->getType()->getAs<FunctionProtoType>()) {
8374     Diag(NewFD->getLocation(),
8375          diag::err_attribute_overloadable_no_prototype)
8376       << NewFD;
8377
8378     // Turn this into a variadic function with no parameters.
8379     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8380     FunctionProtoType::ExtProtoInfo EPI(
8381         Context.getDefaultCallingConvention(true, false));
8382     EPI.Variadic = true;
8383     EPI.ExtInfo = FT->getExtInfo();
8384
8385     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8386     NewFD->setType(R);
8387   }
8388
8389   // If there's a #pragma GCC visibility in scope, and this isn't a class
8390   // member, set the visibility of this function.
8391   if (!DC->isRecord() && NewFD->isExternallyVisible())
8392     AddPushedVisibilityAttribute(NewFD);
8393
8394   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8395   // marking the function.
8396   AddCFAuditedAttribute(NewFD);
8397
8398   // If this is a function definition, check if we have to apply optnone due to
8399   // a pragma.
8400   if(D.isFunctionDefinition())
8401     AddRangeBasedOptnone(NewFD);
8402
8403   // If this is the first declaration of an extern C variable, update
8404   // the map of such variables.
8405   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8406       isIncompleteDeclExternC(*this, NewFD))
8407     RegisterLocallyScopedExternCDecl(NewFD, S);
8408
8409   // Set this FunctionDecl's range up to the right paren.
8410   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8411
8412   if (D.isRedeclaration() && !Previous.empty()) {
8413     checkDLLAttributeRedeclaration(
8414         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8415         isExplicitSpecialization || isFunctionTemplateSpecialization);
8416   }
8417
8418   if (getLangOpts().CUDA) {
8419     IdentifierInfo *II = NewFD->getIdentifier();
8420     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8421         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8422       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8423         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8424
8425       Context.setcudaConfigureCallDecl(NewFD);
8426     }
8427
8428     // Variadic functions, other than a *declaration* of printf, are not allowed
8429     // in device-side CUDA code, unless someone passed
8430     // -fcuda-allow-variadic-functions.
8431     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8432         (NewFD->hasAttr<CUDADeviceAttr>() ||
8433          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8434         !(II && II->isStr("printf") && NewFD->isExternC() &&
8435           !D.isFunctionDefinition())) {
8436       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8437     }
8438   }
8439
8440   if (getLangOpts().CPlusPlus) {
8441     if (FunctionTemplate) {
8442       if (NewFD->isInvalidDecl())
8443         FunctionTemplate->setInvalidDecl();
8444       return FunctionTemplate;
8445     }
8446   }
8447
8448   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8449     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8450     if ((getLangOpts().OpenCLVersion >= 120)
8451         && (SC == SC_Static)) {
8452       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8453       D.setInvalidType();
8454     }
8455
8456     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8457     if (!NewFD->getReturnType()->isVoidType()) {
8458       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8459       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8460           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8461                                 : FixItHint());
8462       D.setInvalidType();
8463     }
8464
8465     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8466     for (auto Param : NewFD->params())
8467       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8468   }
8469   for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
8470        PE = NewFD->param_end(); PI != PE; ++PI) {
8471     ParmVarDecl *Param = *PI;
8472     QualType PT = Param->getType();
8473
8474     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8475     // types.
8476     if (getLangOpts().OpenCLVersion >= 200) {
8477       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8478         QualType ElemTy = PipeTy->getElementType();
8479           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8480             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8481             D.setInvalidType();
8482           }
8483       }
8484     }
8485   }
8486
8487   MarkUnusedFileScopedDecl(NewFD);
8488
8489   // Here we have an function template explicit specialization at class scope.
8490   // The actually specialization will be postponed to template instatiation
8491   // time via the ClassScopeFunctionSpecializationDecl node.
8492   if (isDependentClassScopeExplicitSpecialization) {
8493     ClassScopeFunctionSpecializationDecl *NewSpec =
8494                          ClassScopeFunctionSpecializationDecl::Create(
8495                                 Context, CurContext, SourceLocation(),
8496                                 cast<CXXMethodDecl>(NewFD),
8497                                 HasExplicitTemplateArgs, TemplateArgs);
8498     CurContext->addDecl(NewSpec);
8499     AddToScope = false;
8500   }
8501
8502   return NewFD;
8503 }
8504
8505 /// \brief Perform semantic checking of a new function declaration.
8506 ///
8507 /// Performs semantic analysis of the new function declaration
8508 /// NewFD. This routine performs all semantic checking that does not
8509 /// require the actual declarator involved in the declaration, and is
8510 /// used both for the declaration of functions as they are parsed
8511 /// (called via ActOnDeclarator) and for the declaration of functions
8512 /// that have been instantiated via C++ template instantiation (called
8513 /// via InstantiateDecl).
8514 ///
8515 /// \param IsExplicitSpecialization whether this new function declaration is
8516 /// an explicit specialization of the previous declaration.
8517 ///
8518 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8519 ///
8520 /// \returns true if the function declaration is a redeclaration.
8521 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8522                                     LookupResult &Previous,
8523                                     bool IsExplicitSpecialization) {
8524   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8525          "Variably modified return types are not handled here");
8526
8527   // Determine whether the type of this function should be merged with
8528   // a previous visible declaration. This never happens for functions in C++,
8529   // and always happens in C if the previous declaration was visible.
8530   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8531                                !Previous.isShadowed();
8532
8533   bool Redeclaration = false;
8534   NamedDecl *OldDecl = nullptr;
8535
8536   // Merge or overload the declaration with an existing declaration of
8537   // the same name, if appropriate.
8538   if (!Previous.empty()) {
8539     // Determine whether NewFD is an overload of PrevDecl or
8540     // a declaration that requires merging. If it's an overload,
8541     // there's no more work to do here; we'll just add the new
8542     // function to the scope.
8543     if (!AllowOverloadingOfFunction(Previous, Context)) {
8544       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8545       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8546         Redeclaration = true;
8547         OldDecl = Candidate;
8548       }
8549     } else {
8550       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8551                             /*NewIsUsingDecl*/ false)) {
8552       case Ovl_Match:
8553         Redeclaration = true;
8554         break;
8555
8556       case Ovl_NonFunction:
8557         Redeclaration = true;
8558         break;
8559
8560       case Ovl_Overload:
8561         Redeclaration = false;
8562         break;
8563       }
8564
8565       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8566         // If a function name is overloadable in C, then every function
8567         // with that name must be marked "overloadable".
8568         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8569           << Redeclaration << NewFD;
8570         NamedDecl *OverloadedDecl = nullptr;
8571         if (Redeclaration)
8572           OverloadedDecl = OldDecl;
8573         else if (!Previous.empty())
8574           OverloadedDecl = Previous.getRepresentativeDecl();
8575         if (OverloadedDecl)
8576           Diag(OverloadedDecl->getLocation(),
8577                diag::note_attribute_overloadable_prev_overload);
8578         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8579       }
8580     }
8581   }
8582
8583   // Check for a previous extern "C" declaration with this name.
8584   if (!Redeclaration &&
8585       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8586     if (!Previous.empty()) {
8587       // This is an extern "C" declaration with the same name as a previous
8588       // declaration, and thus redeclares that entity...
8589       Redeclaration = true;
8590       OldDecl = Previous.getFoundDecl();
8591       MergeTypeWithPrevious = false;
8592
8593       // ... except in the presence of __attribute__((overloadable)).
8594       if (OldDecl->hasAttr<OverloadableAttr>()) {
8595         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8596           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8597             << Redeclaration << NewFD;
8598           Diag(Previous.getFoundDecl()->getLocation(),
8599                diag::note_attribute_overloadable_prev_overload);
8600           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8601         }
8602         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8603           Redeclaration = false;
8604           OldDecl = nullptr;
8605         }
8606       }
8607     }
8608   }
8609
8610   // C++11 [dcl.constexpr]p8:
8611   //   A constexpr specifier for a non-static member function that is not
8612   //   a constructor declares that member function to be const.
8613   //
8614   // This needs to be delayed until we know whether this is an out-of-line
8615   // definition of a static member function.
8616   //
8617   // This rule is not present in C++1y, so we produce a backwards
8618   // compatibility warning whenever it happens in C++11.
8619   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8620   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8621       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8622       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8623     CXXMethodDecl *OldMD = nullptr;
8624     if (OldDecl)
8625       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8626     if (!OldMD || !OldMD->isStatic()) {
8627       const FunctionProtoType *FPT =
8628         MD->getType()->castAs<FunctionProtoType>();
8629       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8630       EPI.TypeQuals |= Qualifiers::Const;
8631       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8632                                           FPT->getParamTypes(), EPI));
8633
8634       // Warn that we did this, if we're not performing template instantiation.
8635       // In that case, we'll have warned already when the template was defined.
8636       if (ActiveTemplateInstantiations.empty()) {
8637         SourceLocation AddConstLoc;
8638         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8639                 .IgnoreParens().getAs<FunctionTypeLoc>())
8640           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8641
8642         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8643           << FixItHint::CreateInsertion(AddConstLoc, " const");
8644       }
8645     }
8646   }
8647
8648   if (Redeclaration) {
8649     // NewFD and OldDecl represent declarations that need to be
8650     // merged.
8651     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8652       NewFD->setInvalidDecl();
8653       return Redeclaration;
8654     }
8655
8656     Previous.clear();
8657     Previous.addDecl(OldDecl);
8658
8659     if (FunctionTemplateDecl *OldTemplateDecl
8660                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8661       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8662       FunctionTemplateDecl *NewTemplateDecl
8663         = NewFD->getDescribedFunctionTemplate();
8664       assert(NewTemplateDecl && "Template/non-template mismatch");
8665       if (CXXMethodDecl *Method
8666             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8667         Method->setAccess(OldTemplateDecl->getAccess());
8668         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8669       }
8670
8671       // If this is an explicit specialization of a member that is a function
8672       // template, mark it as a member specialization.
8673       if (IsExplicitSpecialization &&
8674           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8675         NewTemplateDecl->setMemberSpecialization();
8676         assert(OldTemplateDecl->isMemberSpecialization());
8677         // Explicit specializations of a member template do not inherit deleted
8678         // status from the parent member template that they are specializing.
8679         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
8680           FunctionDecl *const OldTemplatedDecl =
8681               OldTemplateDecl->getTemplatedDecl();
8682           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
8683           OldTemplatedDecl->setDeletedAsWritten(false);
8684         }
8685       }
8686
8687     } else {
8688       // This needs to happen first so that 'inline' propagates.
8689       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8690
8691       if (isa<CXXMethodDecl>(NewFD))
8692         NewFD->setAccess(OldDecl->getAccess());
8693     }
8694   }
8695
8696   // Semantic checking for this function declaration (in isolation).
8697
8698   if (getLangOpts().CPlusPlus) {
8699     // C++-specific checks.
8700     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8701       CheckConstructor(Constructor);
8702     } else if (CXXDestructorDecl *Destructor =
8703                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8704       CXXRecordDecl *Record = Destructor->getParent();
8705       QualType ClassType = Context.getTypeDeclType(Record);
8706
8707       // FIXME: Shouldn't we be able to perform this check even when the class
8708       // type is dependent? Both gcc and edg can handle that.
8709       if (!ClassType->isDependentType()) {
8710         DeclarationName Name
8711           = Context.DeclarationNames.getCXXDestructorName(
8712                                         Context.getCanonicalType(ClassType));
8713         if (NewFD->getDeclName() != Name) {
8714           Diag(NewFD->getLocation(), diag::err_destructor_name);
8715           NewFD->setInvalidDecl();
8716           return Redeclaration;
8717         }
8718       }
8719     } else if (CXXConversionDecl *Conversion
8720                = dyn_cast<CXXConversionDecl>(NewFD)) {
8721       ActOnConversionDeclarator(Conversion);
8722     }
8723
8724     // Find any virtual functions that this function overrides.
8725     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8726       if (!Method->isFunctionTemplateSpecialization() &&
8727           !Method->getDescribedFunctionTemplate() &&
8728           Method->isCanonicalDecl()) {
8729         if (AddOverriddenMethods(Method->getParent(), Method)) {
8730           // If the function was marked as "static", we have a problem.
8731           if (NewFD->getStorageClass() == SC_Static) {
8732             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8733           }
8734         }
8735       }
8736
8737       if (Method->isStatic())
8738         checkThisInStaticMemberFunctionType(Method);
8739     }
8740
8741     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8742     if (NewFD->isOverloadedOperator() &&
8743         CheckOverloadedOperatorDeclaration(NewFD)) {
8744       NewFD->setInvalidDecl();
8745       return Redeclaration;
8746     }
8747
8748     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8749     if (NewFD->getLiteralIdentifier() &&
8750         CheckLiteralOperatorDeclaration(NewFD)) {
8751       NewFD->setInvalidDecl();
8752       return Redeclaration;
8753     }
8754
8755     // In C++, check default arguments now that we have merged decls. Unless
8756     // the lexical context is the class, because in this case this is done
8757     // during delayed parsing anyway.
8758     if (!CurContext->isRecord())
8759       CheckCXXDefaultArguments(NewFD);
8760
8761     // If this function declares a builtin function, check the type of this
8762     // declaration against the expected type for the builtin.
8763     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8764       ASTContext::GetBuiltinTypeError Error;
8765       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8766       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8767       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8768         // The type of this function differs from the type of the builtin,
8769         // so forget about the builtin entirely.
8770         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8771       }
8772     }
8773
8774     // If this function is declared as being extern "C", then check to see if
8775     // the function returns a UDT (class, struct, or union type) that is not C
8776     // compatible, and if it does, warn the user.
8777     // But, issue any diagnostic on the first declaration only.
8778     if (Previous.empty() && NewFD->isExternC()) {
8779       QualType R = NewFD->getReturnType();
8780       if (R->isIncompleteType() && !R->isVoidType())
8781         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8782             << NewFD << R;
8783       else if (!R.isPODType(Context) && !R->isVoidType() &&
8784                !R->isObjCObjectPointerType())
8785         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8786     }
8787   }
8788   return Redeclaration;
8789 }
8790
8791 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8792   // C++11 [basic.start.main]p3:
8793   //   A program that [...] declares main to be inline, static or
8794   //   constexpr is ill-formed.
8795   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8796   //   appear in a declaration of main.
8797   // static main is not an error under C99, but we should warn about it.
8798   // We accept _Noreturn main as an extension.
8799   if (FD->getStorageClass() == SC_Static)
8800     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8801          ? diag::err_static_main : diag::warn_static_main)
8802       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8803   if (FD->isInlineSpecified())
8804     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8805       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8806   if (DS.isNoreturnSpecified()) {
8807     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8808     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8809     Diag(NoreturnLoc, diag::ext_noreturn_main);
8810     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8811       << FixItHint::CreateRemoval(NoreturnRange);
8812   }
8813   if (FD->isConstexpr()) {
8814     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8815       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8816     FD->setConstexpr(false);
8817   }
8818
8819   if (getLangOpts().OpenCL) {
8820     Diag(FD->getLocation(), diag::err_opencl_no_main)
8821         << FD->hasAttr<OpenCLKernelAttr>();
8822     FD->setInvalidDecl();
8823     return;
8824   }
8825
8826   QualType T = FD->getType();
8827   assert(T->isFunctionType() && "function decl is not of function type");
8828   const FunctionType* FT = T->castAs<FunctionType>();
8829
8830   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8831     // In C with GNU extensions we allow main() to have non-integer return
8832     // type, but we should warn about the extension, and we disable the
8833     // implicit-return-zero rule.
8834
8835     // GCC in C mode accepts qualified 'int'.
8836     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8837       FD->setHasImplicitReturnZero(true);
8838     else {
8839       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8840       SourceRange RTRange = FD->getReturnTypeSourceRange();
8841       if (RTRange.isValid())
8842         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8843             << FixItHint::CreateReplacement(RTRange, "int");
8844     }
8845   } else {
8846     // In C and C++, main magically returns 0 if you fall off the end;
8847     // set the flag which tells us that.
8848     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8849
8850     // All the standards say that main() should return 'int'.
8851     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8852       FD->setHasImplicitReturnZero(true);
8853     else {
8854       // Otherwise, this is just a flat-out error.
8855       SourceRange RTRange = FD->getReturnTypeSourceRange();
8856       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8857           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8858                                 : FixItHint());
8859       FD->setInvalidDecl(true);
8860     }
8861   }
8862
8863   // Treat protoless main() as nullary.
8864   if (isa<FunctionNoProtoType>(FT)) return;
8865
8866   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8867   unsigned nparams = FTP->getNumParams();
8868   assert(FD->getNumParams() == nparams);
8869
8870   bool HasExtraParameters = (nparams > 3);
8871
8872   if (FTP->isVariadic()) {
8873     Diag(FD->getLocation(), diag::ext_variadic_main);
8874     // FIXME: if we had information about the location of the ellipsis, we
8875     // could add a FixIt hint to remove it as a parameter.
8876   }
8877
8878   // Darwin passes an undocumented fourth argument of type char**.  If
8879   // other platforms start sprouting these, the logic below will start
8880   // getting shifty.
8881   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8882     HasExtraParameters = false;
8883
8884   if (HasExtraParameters) {
8885     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8886     FD->setInvalidDecl(true);
8887     nparams = 3;
8888   }
8889
8890   // FIXME: a lot of the following diagnostics would be improved
8891   // if we had some location information about types.
8892
8893   QualType CharPP =
8894     Context.getPointerType(Context.getPointerType(Context.CharTy));
8895   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8896
8897   for (unsigned i = 0; i < nparams; ++i) {
8898     QualType AT = FTP->getParamType(i);
8899
8900     bool mismatch = true;
8901
8902     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8903       mismatch = false;
8904     else if (Expected[i] == CharPP) {
8905       // As an extension, the following forms are okay:
8906       //   char const **
8907       //   char const * const *
8908       //   char * const *
8909
8910       QualifierCollector qs;
8911       const PointerType* PT;
8912       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8913           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8914           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8915                               Context.CharTy)) {
8916         qs.removeConst();
8917         mismatch = !qs.empty();
8918       }
8919     }
8920
8921     if (mismatch) {
8922       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8923       // TODO: suggest replacing given type with expected type
8924       FD->setInvalidDecl(true);
8925     }
8926   }
8927
8928   if (nparams == 1 && !FD->isInvalidDecl()) {
8929     Diag(FD->getLocation(), diag::warn_main_one_arg);
8930   }
8931
8932   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8933     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8934     FD->setInvalidDecl();
8935   }
8936 }
8937
8938 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8939   QualType T = FD->getType();
8940   assert(T->isFunctionType() && "function decl is not of function type");
8941   const FunctionType *FT = T->castAs<FunctionType>();
8942
8943   // Set an implicit return of 'zero' if the function can return some integral,
8944   // enumeration, pointer or nullptr type.
8945   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8946       FT->getReturnType()->isAnyPointerType() ||
8947       FT->getReturnType()->isNullPtrType())
8948     // DllMain is exempt because a return value of zero means it failed.
8949     if (FD->getName() != "DllMain")
8950       FD->setHasImplicitReturnZero(true);
8951
8952   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8953     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8954     FD->setInvalidDecl();
8955   }
8956 }
8957
8958 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8959   // FIXME: Need strict checking.  In C89, we need to check for
8960   // any assignment, increment, decrement, function-calls, or
8961   // commas outside of a sizeof.  In C99, it's the same list,
8962   // except that the aforementioned are allowed in unevaluated
8963   // expressions.  Everything else falls under the
8964   // "may accept other forms of constant expressions" exception.
8965   // (We never end up here for C++, so the constant expression
8966   // rules there don't matter.)
8967   const Expr *Culprit;
8968   if (Init->isConstantInitializer(Context, false, &Culprit))
8969     return false;
8970   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8971     << Culprit->getSourceRange();
8972   return true;
8973 }
8974
8975 namespace {
8976   // Visits an initialization expression to see if OrigDecl is evaluated in
8977   // its own initialization and throws a warning if it does.
8978   class SelfReferenceChecker
8979       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8980     Sema &S;
8981     Decl *OrigDecl;
8982     bool isRecordType;
8983     bool isPODType;
8984     bool isReferenceType;
8985
8986     bool isInitList;
8987     llvm::SmallVector<unsigned, 4> InitFieldIndex;
8988
8989   public:
8990     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8991
8992     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8993                                                     S(S), OrigDecl(OrigDecl) {
8994       isPODType = false;
8995       isRecordType = false;
8996       isReferenceType = false;
8997       isInitList = false;
8998       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8999         isPODType = VD->getType().isPODType(S.Context);
9000         isRecordType = VD->getType()->isRecordType();
9001         isReferenceType = VD->getType()->isReferenceType();
9002       }
9003     }
9004
9005     // For most expressions, just call the visitor.  For initializer lists,
9006     // track the index of the field being initialized since fields are
9007     // initialized in order allowing use of previously initialized fields.
9008     void CheckExpr(Expr *E) {
9009       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9010       if (!InitList) {
9011         Visit(E);
9012         return;
9013       }
9014
9015       // Track and increment the index here.
9016       isInitList = true;
9017       InitFieldIndex.push_back(0);
9018       for (auto Child : InitList->children()) {
9019         CheckExpr(cast<Expr>(Child));
9020         ++InitFieldIndex.back();
9021       }
9022       InitFieldIndex.pop_back();
9023     }
9024
9025     // Returns true if MemberExpr is checked and no futher checking is needed.
9026     // Returns false if additional checking is required.
9027     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9028       llvm::SmallVector<FieldDecl*, 4> Fields;
9029       Expr *Base = E;
9030       bool ReferenceField = false;
9031
9032       // Get the field memebers used.
9033       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9034         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9035         if (!FD)
9036           return false;
9037         Fields.push_back(FD);
9038         if (FD->getType()->isReferenceType())
9039           ReferenceField = true;
9040         Base = ME->getBase()->IgnoreParenImpCasts();
9041       }
9042
9043       // Keep checking only if the base Decl is the same.
9044       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9045       if (!DRE || DRE->getDecl() != OrigDecl)
9046         return false;
9047
9048       // A reference field can be bound to an unininitialized field.
9049       if (CheckReference && !ReferenceField)
9050         return true;
9051
9052       // Convert FieldDecls to their index number.
9053       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9054       for (const FieldDecl *I : llvm::reverse(Fields))
9055         UsedFieldIndex.push_back(I->getFieldIndex());
9056
9057       // See if a warning is needed by checking the first difference in index
9058       // numbers.  If field being used has index less than the field being
9059       // initialized, then the use is safe.
9060       for (auto UsedIter = UsedFieldIndex.begin(),
9061                 UsedEnd = UsedFieldIndex.end(),
9062                 OrigIter = InitFieldIndex.begin(),
9063                 OrigEnd = InitFieldIndex.end();
9064            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9065         if (*UsedIter < *OrigIter)
9066           return true;
9067         if (*UsedIter > *OrigIter)
9068           break;
9069       }
9070
9071       // TODO: Add a different warning which will print the field names.
9072       HandleDeclRefExpr(DRE);
9073       return true;
9074     }
9075
9076     // For most expressions, the cast is directly above the DeclRefExpr.
9077     // For conditional operators, the cast can be outside the conditional
9078     // operator if both expressions are DeclRefExpr's.
9079     void HandleValue(Expr *E) {
9080       E = E->IgnoreParens();
9081       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9082         HandleDeclRefExpr(DRE);
9083         return;
9084       }
9085
9086       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9087         Visit(CO->getCond());
9088         HandleValue(CO->getTrueExpr());
9089         HandleValue(CO->getFalseExpr());
9090         return;
9091       }
9092
9093       if (BinaryConditionalOperator *BCO =
9094               dyn_cast<BinaryConditionalOperator>(E)) {
9095         Visit(BCO->getCond());
9096         HandleValue(BCO->getFalseExpr());
9097         return;
9098       }
9099
9100       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9101         HandleValue(OVE->getSourceExpr());
9102         return;
9103       }
9104
9105       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9106         if (BO->getOpcode() == BO_Comma) {
9107           Visit(BO->getLHS());
9108           HandleValue(BO->getRHS());
9109           return;
9110         }
9111       }
9112
9113       if (isa<MemberExpr>(E)) {
9114         if (isInitList) {
9115           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9116                                       false /*CheckReference*/))
9117             return;
9118         }
9119
9120         Expr *Base = E->IgnoreParenImpCasts();
9121         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9122           // Check for static member variables and don't warn on them.
9123           if (!isa<FieldDecl>(ME->getMemberDecl()))
9124             return;
9125           Base = ME->getBase()->IgnoreParenImpCasts();
9126         }
9127         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9128           HandleDeclRefExpr(DRE);
9129         return;
9130       }
9131
9132       Visit(E);
9133     }
9134
9135     // Reference types not handled in HandleValue are handled here since all
9136     // uses of references are bad, not just r-value uses.
9137     void VisitDeclRefExpr(DeclRefExpr *E) {
9138       if (isReferenceType)
9139         HandleDeclRefExpr(E);
9140     }
9141
9142     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9143       if (E->getCastKind() == CK_LValueToRValue) {
9144         HandleValue(E->getSubExpr());
9145         return;
9146       }
9147
9148       Inherited::VisitImplicitCastExpr(E);
9149     }
9150
9151     void VisitMemberExpr(MemberExpr *E) {
9152       if (isInitList) {
9153         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9154           return;
9155       }
9156
9157       // Don't warn on arrays since they can be treated as pointers.
9158       if (E->getType()->canDecayToPointerType()) return;
9159
9160       // Warn when a non-static method call is followed by non-static member
9161       // field accesses, which is followed by a DeclRefExpr.
9162       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9163       bool Warn = (MD && !MD->isStatic());
9164       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9165       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9166         if (!isa<FieldDecl>(ME->getMemberDecl()))
9167           Warn = false;
9168         Base = ME->getBase()->IgnoreParenImpCasts();
9169       }
9170
9171       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9172         if (Warn)
9173           HandleDeclRefExpr(DRE);
9174         return;
9175       }
9176
9177       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9178       // Visit that expression.
9179       Visit(Base);
9180     }
9181
9182     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9183       Expr *Callee = E->getCallee();
9184
9185       if (isa<UnresolvedLookupExpr>(Callee))
9186         return Inherited::VisitCXXOperatorCallExpr(E);
9187
9188       Visit(Callee);
9189       for (auto Arg: E->arguments())
9190         HandleValue(Arg->IgnoreParenImpCasts());
9191     }
9192
9193     void VisitUnaryOperator(UnaryOperator *E) {
9194       // For POD record types, addresses of its own members are well-defined.
9195       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9196           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9197         if (!isPODType)
9198           HandleValue(E->getSubExpr());
9199         return;
9200       }
9201
9202       if (E->isIncrementDecrementOp()) {
9203         HandleValue(E->getSubExpr());
9204         return;
9205       }
9206
9207       Inherited::VisitUnaryOperator(E);
9208     }
9209
9210     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9211
9212     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9213       if (E->getConstructor()->isCopyConstructor()) {
9214         Expr *ArgExpr = E->getArg(0);
9215         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9216           if (ILE->getNumInits() == 1)
9217             ArgExpr = ILE->getInit(0);
9218         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9219           if (ICE->getCastKind() == CK_NoOp)
9220             ArgExpr = ICE->getSubExpr();
9221         HandleValue(ArgExpr);
9222         return;
9223       }
9224       Inherited::VisitCXXConstructExpr(E);
9225     }
9226
9227     void VisitCallExpr(CallExpr *E) {
9228       // Treat std::move as a use.
9229       if (E->getNumArgs() == 1) {
9230         if (FunctionDecl *FD = E->getDirectCallee()) {
9231           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9232               FD->getIdentifier()->isStr("move")) {
9233             HandleValue(E->getArg(0));
9234             return;
9235           }
9236         }
9237       }
9238
9239       Inherited::VisitCallExpr(E);
9240     }
9241
9242     void VisitBinaryOperator(BinaryOperator *E) {
9243       if (E->isCompoundAssignmentOp()) {
9244         HandleValue(E->getLHS());
9245         Visit(E->getRHS());
9246         return;
9247       }
9248
9249       Inherited::VisitBinaryOperator(E);
9250     }
9251
9252     // A custom visitor for BinaryConditionalOperator is needed because the
9253     // regular visitor would check the condition and true expression separately
9254     // but both point to the same place giving duplicate diagnostics.
9255     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9256       Visit(E->getCond());
9257       Visit(E->getFalseExpr());
9258     }
9259
9260     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9261       Decl* ReferenceDecl = DRE->getDecl();
9262       if (OrigDecl != ReferenceDecl) return;
9263       unsigned diag;
9264       if (isReferenceType) {
9265         diag = diag::warn_uninit_self_reference_in_reference_init;
9266       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9267         diag = diag::warn_static_self_reference_in_init;
9268       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9269                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9270                  DRE->getDecl()->getType()->isRecordType()) {
9271         diag = diag::warn_uninit_self_reference_in_init;
9272       } else {
9273         // Local variables will be handled by the CFG analysis.
9274         return;
9275       }
9276
9277       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9278                             S.PDiag(diag)
9279                               << DRE->getNameInfo().getName()
9280                               << OrigDecl->getLocation()
9281                               << DRE->getSourceRange());
9282     }
9283   };
9284
9285   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9286   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9287                                  bool DirectInit) {
9288     // Parameters arguments are occassionially constructed with itself,
9289     // for instance, in recursive functions.  Skip them.
9290     if (isa<ParmVarDecl>(OrigDecl))
9291       return;
9292
9293     E = E->IgnoreParens();
9294
9295     // Skip checking T a = a where T is not a record or reference type.
9296     // Doing so is a way to silence uninitialized warnings.
9297     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9298       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9299         if (ICE->getCastKind() == CK_LValueToRValue)
9300           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9301             if (DRE->getDecl() == OrigDecl)
9302               return;
9303
9304     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9305   }
9306 } // end anonymous namespace
9307
9308 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9309                                             DeclarationName Name, QualType Type,
9310                                             TypeSourceInfo *TSI,
9311                                             SourceRange Range, bool DirectInit,
9312                                             Expr *Init) {
9313   bool IsInitCapture = !VDecl;
9314   assert((!VDecl || !VDecl->isInitCapture()) &&
9315          "init captures are expected to be deduced prior to initialization");
9316
9317   ArrayRef<Expr *> DeduceInits = Init;
9318   if (DirectInit) {
9319     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9320       DeduceInits = PL->exprs();
9321     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9322       DeduceInits = IL->inits();
9323   }
9324
9325   // Deduction only works if we have exactly one source expression.
9326   if (DeduceInits.empty()) {
9327     // It isn't possible to write this directly, but it is possible to
9328     // end up in this situation with "auto x(some_pack...);"
9329     Diag(Init->getLocStart(), IsInitCapture
9330                                   ? diag::err_init_capture_no_expression
9331                                   : diag::err_auto_var_init_no_expression)
9332         << Name << Type << Range;
9333     return QualType();
9334   }
9335
9336   if (DeduceInits.size() > 1) {
9337     Diag(DeduceInits[1]->getLocStart(),
9338          IsInitCapture ? diag::err_init_capture_multiple_expressions
9339                        : diag::err_auto_var_init_multiple_expressions)
9340         << Name << Type << Range;
9341     return QualType();
9342   }
9343
9344   Expr *DeduceInit = DeduceInits[0];
9345   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9346     Diag(Init->getLocStart(), IsInitCapture
9347                                   ? diag::err_init_capture_paren_braces
9348                                   : diag::err_auto_var_init_paren_braces)
9349         << isa<InitListExpr>(Init) << Name << Type << Range;
9350     return QualType();
9351   }
9352
9353   // Expressions default to 'id' when we're in a debugger.
9354   bool DefaultedAnyToId = false;
9355   if (getLangOpts().DebuggerCastResultToId &&
9356       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9357     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9358     if (Result.isInvalid()) {
9359       return QualType();
9360     }
9361     Init = Result.get();
9362     DefaultedAnyToId = true;
9363   }
9364
9365   QualType DeducedType;
9366   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9367     if (!IsInitCapture)
9368       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9369     else if (isa<InitListExpr>(Init))
9370       Diag(Range.getBegin(),
9371            diag::err_init_capture_deduction_failure_from_init_list)
9372           << Name
9373           << (DeduceInit->getType().isNull() ? TSI->getType()
9374                                              : DeduceInit->getType())
9375           << DeduceInit->getSourceRange();
9376     else
9377       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9378           << Name << TSI->getType()
9379           << (DeduceInit->getType().isNull() ? TSI->getType()
9380                                              : DeduceInit->getType())
9381           << DeduceInit->getSourceRange();
9382   }
9383
9384   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9385   // 'id' instead of a specific object type prevents most of our usual
9386   // checks.
9387   // We only want to warn outside of template instantiations, though:
9388   // inside a template, the 'id' could have come from a parameter.
9389   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9390       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9391     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9392     Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9393   }
9394
9395   return DeducedType;
9396 }
9397
9398 /// AddInitializerToDecl - Adds the initializer Init to the
9399 /// declaration dcl. If DirectInit is true, this is C++ direct
9400 /// initialization rather than copy initialization.
9401 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9402                                 bool DirectInit, bool TypeMayContainAuto) {
9403   // If there is no declaration, there was an error parsing it.  Just ignore
9404   // the initializer.
9405   if (!RealDecl || RealDecl->isInvalidDecl()) {
9406     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9407     return;
9408   }
9409
9410   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9411     // Pure-specifiers are handled in ActOnPureSpecifier.
9412     Diag(Method->getLocation(), diag::err_member_function_initialization)
9413       << Method->getDeclName() << Init->getSourceRange();
9414     Method->setInvalidDecl();
9415     return;
9416   }
9417
9418   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9419   if (!VDecl) {
9420     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9421     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9422     RealDecl->setInvalidDecl();
9423     return;
9424   }
9425
9426   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9427   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9428     // Attempt typo correction early so that the type of the init expression can
9429     // be deduced based on the chosen correction if the original init contains a
9430     // TypoExpr.
9431     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9432     if (!Res.isUsable()) {
9433       RealDecl->setInvalidDecl();
9434       return;
9435     }
9436     Init = Res.get();
9437
9438     QualType DeducedType = deduceVarTypeFromInitializer(
9439         VDecl, VDecl->getDeclName(), VDecl->getType(),
9440         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9441     if (DeducedType.isNull()) {
9442       RealDecl->setInvalidDecl();
9443       return;
9444     }
9445
9446     VDecl->setType(DeducedType);
9447     assert(VDecl->isLinkageValid());
9448
9449     // In ARC, infer lifetime.
9450     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9451       VDecl->setInvalidDecl();
9452
9453     // If this is a redeclaration, check that the type we just deduced matches
9454     // the previously declared type.
9455     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9456       // We never need to merge the type, because we cannot form an incomplete
9457       // array of auto, nor deduce such a type.
9458       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9459     }
9460
9461     // Check the deduced type is valid for a variable declaration.
9462     CheckVariableDeclarationType(VDecl);
9463     if (VDecl->isInvalidDecl())
9464       return;
9465   }
9466
9467   // dllimport cannot be used on variable definitions.
9468   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9469     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9470     VDecl->setInvalidDecl();
9471     return;
9472   }
9473
9474   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9475     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9476     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9477     VDecl->setInvalidDecl();
9478     return;
9479   }
9480
9481   if (!VDecl->getType()->isDependentType()) {
9482     // A definition must end up with a complete type, which means it must be
9483     // complete with the restriction that an array type might be completed by
9484     // the initializer; note that later code assumes this restriction.
9485     QualType BaseDeclType = VDecl->getType();
9486     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9487       BaseDeclType = Array->getElementType();
9488     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9489                             diag::err_typecheck_decl_incomplete_type)) {
9490       RealDecl->setInvalidDecl();
9491       return;
9492     }
9493
9494     // The variable can not have an abstract class type.
9495     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9496                                diag::err_abstract_type_in_decl,
9497                                AbstractVariableType))
9498       VDecl->setInvalidDecl();
9499   }
9500
9501   VarDecl *Def;
9502   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9503     NamedDecl *Hidden = nullptr;
9504     if (!hasVisibleDefinition(Def, &Hidden) &&
9505         (VDecl->getFormalLinkage() == InternalLinkage ||
9506          VDecl->getDescribedVarTemplate() ||
9507          VDecl->getNumTemplateParameterLists() ||
9508          VDecl->getDeclContext()->isDependentContext())) {
9509       // The previous definition is hidden, and multiple definitions are
9510       // permitted (in separate TUs). Form another definition of it.
9511     } else {
9512       Diag(VDecl->getLocation(), diag::err_redefinition)
9513         << VDecl->getDeclName();
9514       Diag(Def->getLocation(), diag::note_previous_definition);
9515       VDecl->setInvalidDecl();
9516       return;
9517     }
9518   }
9519
9520   if (getLangOpts().CPlusPlus) {
9521     // C++ [class.static.data]p4
9522     //   If a static data member is of const integral or const
9523     //   enumeration type, its declaration in the class definition can
9524     //   specify a constant-initializer which shall be an integral
9525     //   constant expression (5.19). In that case, the member can appear
9526     //   in integral constant expressions. The member shall still be
9527     //   defined in a namespace scope if it is used in the program and the
9528     //   namespace scope definition shall not contain an initializer.
9529     //
9530     // We already performed a redefinition check above, but for static
9531     // data members we also need to check whether there was an in-class
9532     // declaration with an initializer.
9533     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9534       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9535           << VDecl->getDeclName();
9536       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9537            diag::note_previous_initializer)
9538           << 0;
9539       return;
9540     }
9541
9542     if (VDecl->hasLocalStorage())
9543       getCurFunction()->setHasBranchProtectedScope();
9544
9545     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9546       VDecl->setInvalidDecl();
9547       return;
9548     }
9549   }
9550
9551   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9552   // a kernel function cannot be initialized."
9553   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9554     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9555     VDecl->setInvalidDecl();
9556     return;
9557   }
9558
9559   // Get the decls type and save a reference for later, since
9560   // CheckInitializerTypes may change it.
9561   QualType DclT = VDecl->getType(), SavT = DclT;
9562
9563   // Expressions default to 'id' when we're in a debugger
9564   // and we are assigning it to a variable of Objective-C pointer type.
9565   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9566       Init->getType() == Context.UnknownAnyTy) {
9567     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9568     if (Result.isInvalid()) {
9569       VDecl->setInvalidDecl();
9570       return;
9571     }
9572     Init = Result.get();
9573   }
9574
9575   // Perform the initialization.
9576   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9577   if (!VDecl->isInvalidDecl()) {
9578     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9579     InitializationKind Kind =
9580         DirectInit
9581             ? CXXDirectInit
9582                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9583                                                      Init->getLocStart(),
9584                                                      Init->getLocEnd())
9585                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9586             : InitializationKind::CreateCopy(VDecl->getLocation(),
9587                                              Init->getLocStart());
9588
9589     MultiExprArg Args = Init;
9590     if (CXXDirectInit)
9591       Args = MultiExprArg(CXXDirectInit->getExprs(),
9592                           CXXDirectInit->getNumExprs());
9593
9594     // Try to correct any TypoExprs in the initialization arguments.
9595     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9596       ExprResult Res = CorrectDelayedTyposInExpr(
9597           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9598             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9599             return Init.Failed() ? ExprError() : E;
9600           });
9601       if (Res.isInvalid()) {
9602         VDecl->setInvalidDecl();
9603       } else if (Res.get() != Args[Idx]) {
9604         Args[Idx] = Res.get();
9605       }
9606     }
9607     if (VDecl->isInvalidDecl())
9608       return;
9609
9610     InitializationSequence InitSeq(*this, Entity, Kind, Args,
9611                                    /*TopLevelOfInitList=*/false,
9612                                    /*TreatUnavailableAsInvalid=*/false);
9613     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9614     if (Result.isInvalid()) {
9615       VDecl->setInvalidDecl();
9616       return;
9617     }
9618
9619     Init = Result.getAs<Expr>();
9620   }
9621
9622   // Check for self-references within variable initializers.
9623   // Variables declared within a function/method body (except for references)
9624   // are handled by a dataflow analysis.
9625   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9626       VDecl->getType()->isReferenceType()) {
9627     CheckSelfReference(*this, RealDecl, Init, DirectInit);
9628   }
9629
9630   // If the type changed, it means we had an incomplete type that was
9631   // completed by the initializer. For example:
9632   //   int ary[] = { 1, 3, 5 };
9633   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9634   if (!VDecl->isInvalidDecl() && (DclT != SavT))
9635     VDecl->setType(DclT);
9636
9637   if (!VDecl->isInvalidDecl()) {
9638     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9639
9640     if (VDecl->hasAttr<BlocksAttr>())
9641       checkRetainCycles(VDecl, Init);
9642
9643     // It is safe to assign a weak reference into a strong variable.
9644     // Although this code can still have problems:
9645     //   id x = self.weakProp;
9646     //   id y = self.weakProp;
9647     // we do not warn to warn spuriously when 'x' and 'y' are on separate
9648     // paths through the function. This should be revisited if
9649     // -Wrepeated-use-of-weak is made flow-sensitive.
9650     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9651         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9652                          Init->getLocStart()))
9653       getCurFunction()->markSafeWeakUse(Init);
9654   }
9655
9656   // The initialization is usually a full-expression.
9657   //
9658   // FIXME: If this is a braced initialization of an aggregate, it is not
9659   // an expression, and each individual field initializer is a separate
9660   // full-expression. For instance, in:
9661   //
9662   //   struct Temp { ~Temp(); };
9663   //   struct S { S(Temp); };
9664   //   struct T { S a, b; } t = { Temp(), Temp() }
9665   //
9666   // we should destroy the first Temp before constructing the second.
9667   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9668                                           false,
9669                                           VDecl->isConstexpr());
9670   if (Result.isInvalid()) {
9671     VDecl->setInvalidDecl();
9672     return;
9673   }
9674   Init = Result.get();
9675
9676   // Attach the initializer to the decl.
9677   VDecl->setInit(Init);
9678
9679   if (VDecl->isLocalVarDecl()) {
9680     // C99 6.7.8p4: All the expressions in an initializer for an object that has
9681     // static storage duration shall be constant expressions or string literals.
9682     // C++ does not have this restriction.
9683     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9684       const Expr *Culprit;
9685       if (VDecl->getStorageClass() == SC_Static)
9686         CheckForConstantInitializer(Init, DclT);
9687       // C89 is stricter than C99 for non-static aggregate types.
9688       // C89 6.5.7p3: All the expressions [...] in an initializer list
9689       // for an object that has aggregate or union type shall be
9690       // constant expressions.
9691       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9692                isa<InitListExpr>(Init) &&
9693                !Init->isConstantInitializer(Context, false, &Culprit))
9694         Diag(Culprit->getExprLoc(),
9695              diag::ext_aggregate_init_not_constant)
9696           << Culprit->getSourceRange();
9697     }
9698   } else if (VDecl->isStaticDataMember() &&
9699              VDecl->getLexicalDeclContext()->isRecord()) {
9700     // This is an in-class initialization for a static data member, e.g.,
9701     //
9702     // struct S {
9703     //   static const int value = 17;
9704     // };
9705
9706     // C++ [class.mem]p4:
9707     //   A member-declarator can contain a constant-initializer only
9708     //   if it declares a static member (9.4) of const integral or
9709     //   const enumeration type, see 9.4.2.
9710     //
9711     // C++11 [class.static.data]p3:
9712     //   If a non-volatile const static data member is of integral or
9713     //   enumeration type, its declaration in the class definition can
9714     //   specify a brace-or-equal-initializer in which every initalizer-clause
9715     //   that is an assignment-expression is a constant expression. A static
9716     //   data member of literal type can be declared in the class definition
9717     //   with the constexpr specifier; if so, its declaration shall specify a
9718     //   brace-or-equal-initializer in which every initializer-clause that is
9719     //   an assignment-expression is a constant expression.
9720
9721     // Do nothing on dependent types.
9722     if (DclT->isDependentType()) {
9723
9724     // Allow any 'static constexpr' members, whether or not they are of literal
9725     // type. We separately check that every constexpr variable is of literal
9726     // type.
9727     } else if (VDecl->isConstexpr()) {
9728
9729     // Require constness.
9730     } else if (!DclT.isConstQualified()) {
9731       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9732         << Init->getSourceRange();
9733       VDecl->setInvalidDecl();
9734
9735     // We allow integer constant expressions in all cases.
9736     } else if (DclT->isIntegralOrEnumerationType()) {
9737       // Check whether the expression is a constant expression.
9738       SourceLocation Loc;
9739       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9740         // In C++11, a non-constexpr const static data member with an
9741         // in-class initializer cannot be volatile.
9742         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9743       else if (Init->isValueDependent())
9744         ; // Nothing to check.
9745       else if (Init->isIntegerConstantExpr(Context, &Loc))
9746         ; // Ok, it's an ICE!
9747       else if (Init->isEvaluatable(Context)) {
9748         // If we can constant fold the initializer through heroics, accept it,
9749         // but report this as a use of an extension for -pedantic.
9750         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9751           << Init->getSourceRange();
9752       } else {
9753         // Otherwise, this is some crazy unknown case.  Report the issue at the
9754         // location provided by the isIntegerConstantExpr failed check.
9755         Diag(Loc, diag::err_in_class_initializer_non_constant)
9756           << Init->getSourceRange();
9757         VDecl->setInvalidDecl();
9758       }
9759
9760     // We allow foldable floating-point constants as an extension.
9761     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9762       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9763       // it anyway and provide a fixit to add the 'constexpr'.
9764       if (getLangOpts().CPlusPlus11) {
9765         Diag(VDecl->getLocation(),
9766              diag::ext_in_class_initializer_float_type_cxx11)
9767             << DclT << Init->getSourceRange();
9768         Diag(VDecl->getLocStart(),
9769              diag::note_in_class_initializer_float_type_cxx11)
9770             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9771       } else {
9772         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9773           << DclT << Init->getSourceRange();
9774
9775         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9776           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9777             << Init->getSourceRange();
9778           VDecl->setInvalidDecl();
9779         }
9780       }
9781
9782     // Suggest adding 'constexpr' in C++11 for literal types.
9783     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9784       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9785         << DclT << Init->getSourceRange()
9786         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9787       VDecl->setConstexpr(true);
9788
9789     } else {
9790       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9791         << DclT << Init->getSourceRange();
9792       VDecl->setInvalidDecl();
9793     }
9794   } else if (VDecl->isFileVarDecl()) {
9795     if (VDecl->getStorageClass() == SC_Extern &&
9796         (!getLangOpts().CPlusPlus ||
9797          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9798            VDecl->isExternC())) &&
9799         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9800       Diag(VDecl->getLocation(), diag::warn_extern_init);
9801
9802     // C99 6.7.8p4. All file scoped initializers need to be constant.
9803     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9804       CheckForConstantInitializer(Init, DclT);
9805   }
9806
9807   // We will represent direct-initialization similarly to copy-initialization:
9808   //    int x(1);  -as-> int x = 1;
9809   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9810   //
9811   // Clients that want to distinguish between the two forms, can check for
9812   // direct initializer using VarDecl::getInitStyle().
9813   // A major benefit is that clients that don't particularly care about which
9814   // exactly form was it (like the CodeGen) can handle both cases without
9815   // special case code.
9816
9817   // C++ 8.5p11:
9818   // The form of initialization (using parentheses or '=') is generally
9819   // insignificant, but does matter when the entity being initialized has a
9820   // class type.
9821   if (CXXDirectInit) {
9822     assert(DirectInit && "Call-style initializer must be direct init.");
9823     VDecl->setInitStyle(VarDecl::CallInit);
9824   } else if (DirectInit) {
9825     // This must be list-initialization. No other way is direct-initialization.
9826     VDecl->setInitStyle(VarDecl::ListInit);
9827   }
9828
9829   CheckCompleteVariableDeclaration(VDecl);
9830 }
9831
9832 /// ActOnInitializerError - Given that there was an error parsing an
9833 /// initializer for the given declaration, try to return to some form
9834 /// of sanity.
9835 void Sema::ActOnInitializerError(Decl *D) {
9836   // Our main concern here is re-establishing invariants like "a
9837   // variable's type is either dependent or complete".
9838   if (!D || D->isInvalidDecl()) return;
9839
9840   VarDecl *VD = dyn_cast<VarDecl>(D);
9841   if (!VD) return;
9842
9843   // Auto types are meaningless if we can't make sense of the initializer.
9844   if (ParsingInitForAutoVars.count(D)) {
9845     D->setInvalidDecl();
9846     return;
9847   }
9848
9849   QualType Ty = VD->getType();
9850   if (Ty->isDependentType()) return;
9851
9852   // Require a complete type.
9853   if (RequireCompleteType(VD->getLocation(),
9854                           Context.getBaseElementType(Ty),
9855                           diag::err_typecheck_decl_incomplete_type)) {
9856     VD->setInvalidDecl();
9857     return;
9858   }
9859
9860   // Require a non-abstract type.
9861   if (RequireNonAbstractType(VD->getLocation(), Ty,
9862                              diag::err_abstract_type_in_decl,
9863                              AbstractVariableType)) {
9864     VD->setInvalidDecl();
9865     return;
9866   }
9867
9868   // Don't bother complaining about constructors or destructors,
9869   // though.
9870 }
9871
9872 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9873                                   bool TypeMayContainAuto) {
9874   // If there is no declaration, there was an error parsing it. Just ignore it.
9875   if (!RealDecl)
9876     return;
9877
9878   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9879     QualType Type = Var->getType();
9880
9881     // C++11 [dcl.spec.auto]p3
9882     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9883       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9884         << Var->getDeclName() << Type;
9885       Var->setInvalidDecl();
9886       return;
9887     }
9888
9889     // C++11 [class.static.data]p3: A static data member can be declared with
9890     // the constexpr specifier; if so, its declaration shall specify
9891     // a brace-or-equal-initializer.
9892     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9893     // the definition of a variable [...] or the declaration of a static data
9894     // member.
9895     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9896       if (Var->isStaticDataMember())
9897         Diag(Var->getLocation(),
9898              diag::err_constexpr_static_mem_var_requires_init)
9899           << Var->getDeclName();
9900       else
9901         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9902       Var->setInvalidDecl();
9903       return;
9904     }
9905
9906     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
9907     // definition having the concept specifier is called a variable concept. A
9908     // concept definition refers to [...] a variable concept and its initializer.
9909     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
9910       if (VTD->isConcept()) {
9911         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
9912         Var->setInvalidDecl();
9913         return;
9914       }
9915     }
9916
9917     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9918     // be initialized.
9919     if (!Var->isInvalidDecl() &&
9920         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9921         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9922       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9923       Var->setInvalidDecl();
9924       return;
9925     }
9926
9927     switch (Var->isThisDeclarationADefinition()) {
9928     case VarDecl::Definition:
9929       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9930         break;
9931
9932       // We have an out-of-line definition of a static data member
9933       // that has an in-class initializer, so we type-check this like
9934       // a declaration.
9935       //
9936       // Fall through
9937
9938     case VarDecl::DeclarationOnly:
9939       // It's only a declaration.
9940
9941       // Block scope. C99 6.7p7: If an identifier for an object is
9942       // declared with no linkage (C99 6.2.2p6), the type for the
9943       // object shall be complete.
9944       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9945           !Var->hasLinkage() && !Var->isInvalidDecl() &&
9946           RequireCompleteType(Var->getLocation(), Type,
9947                               diag::err_typecheck_decl_incomplete_type))
9948         Var->setInvalidDecl();
9949
9950       // Make sure that the type is not abstract.
9951       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9952           RequireNonAbstractType(Var->getLocation(), Type,
9953                                  diag::err_abstract_type_in_decl,
9954                                  AbstractVariableType))
9955         Var->setInvalidDecl();
9956       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9957           Var->getStorageClass() == SC_PrivateExtern) {
9958         Diag(Var->getLocation(), diag::warn_private_extern);
9959         Diag(Var->getLocation(), diag::note_private_extern);
9960       }
9961
9962       return;
9963
9964     case VarDecl::TentativeDefinition:
9965       // File scope. C99 6.9.2p2: A declaration of an identifier for an
9966       // object that has file scope without an initializer, and without a
9967       // storage-class specifier or with the storage-class specifier "static",
9968       // constitutes a tentative definition. Note: A tentative definition with
9969       // external linkage is valid (C99 6.2.2p5).
9970       if (!Var->isInvalidDecl()) {
9971         if (const IncompleteArrayType *ArrayT
9972                                     = Context.getAsIncompleteArrayType(Type)) {
9973           if (RequireCompleteType(Var->getLocation(),
9974                                   ArrayT->getElementType(),
9975                                   diag::err_illegal_decl_array_incomplete_type))
9976             Var->setInvalidDecl();
9977         } else if (Var->getStorageClass() == SC_Static) {
9978           // C99 6.9.2p3: If the declaration of an identifier for an object is
9979           // a tentative definition and has internal linkage (C99 6.2.2p3), the
9980           // declared type shall not be an incomplete type.
9981           // NOTE: code such as the following
9982           //     static struct s;
9983           //     struct s { int a; };
9984           // is accepted by gcc. Hence here we issue a warning instead of
9985           // an error and we do not invalidate the static declaration.
9986           // NOTE: to avoid multiple warnings, only check the first declaration.
9987           if (Var->isFirstDecl())
9988             RequireCompleteType(Var->getLocation(), Type,
9989                                 diag::ext_typecheck_decl_incomplete_type);
9990         }
9991       }
9992
9993       // Record the tentative definition; we're done.
9994       if (!Var->isInvalidDecl())
9995         TentativeDefinitions.push_back(Var);
9996       return;
9997     }
9998
9999     // Provide a specific diagnostic for uninitialized variable
10000     // definitions with incomplete array type.
10001     if (Type->isIncompleteArrayType()) {
10002       Diag(Var->getLocation(),
10003            diag::err_typecheck_incomplete_array_needs_initializer);
10004       Var->setInvalidDecl();
10005       return;
10006     }
10007
10008     // Provide a specific diagnostic for uninitialized variable
10009     // definitions with reference type.
10010     if (Type->isReferenceType()) {
10011       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10012         << Var->getDeclName()
10013         << SourceRange(Var->getLocation(), Var->getLocation());
10014       Var->setInvalidDecl();
10015       return;
10016     }
10017
10018     // Do not attempt to type-check the default initializer for a
10019     // variable with dependent type.
10020     if (Type->isDependentType())
10021       return;
10022
10023     if (Var->isInvalidDecl())
10024       return;
10025
10026     if (!Var->hasAttr<AliasAttr>()) {
10027       if (RequireCompleteType(Var->getLocation(),
10028                               Context.getBaseElementType(Type),
10029                               diag::err_typecheck_decl_incomplete_type)) {
10030         Var->setInvalidDecl();
10031         return;
10032       }
10033     } else {
10034       return;
10035     }
10036
10037     // The variable can not have an abstract class type.
10038     if (RequireNonAbstractType(Var->getLocation(), Type,
10039                                diag::err_abstract_type_in_decl,
10040                                AbstractVariableType)) {
10041       Var->setInvalidDecl();
10042       return;
10043     }
10044
10045     // Check for jumps past the implicit initializer.  C++0x
10046     // clarifies that this applies to a "variable with automatic
10047     // storage duration", not a "local variable".
10048     // C++11 [stmt.dcl]p3
10049     //   A program that jumps from a point where a variable with automatic
10050     //   storage duration is not in scope to a point where it is in scope is
10051     //   ill-formed unless the variable has scalar type, class type with a
10052     //   trivial default constructor and a trivial destructor, a cv-qualified
10053     //   version of one of these types, or an array of one of the preceding
10054     //   types and is declared without an initializer.
10055     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10056       if (const RecordType *Record
10057             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10058         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10059         // Mark the function for further checking even if the looser rules of
10060         // C++11 do not require such checks, so that we can diagnose
10061         // incompatibilities with C++98.
10062         if (!CXXRecord->isPOD())
10063           getCurFunction()->setHasBranchProtectedScope();
10064       }
10065     }
10066
10067     // C++03 [dcl.init]p9:
10068     //   If no initializer is specified for an object, and the
10069     //   object is of (possibly cv-qualified) non-POD class type (or
10070     //   array thereof), the object shall be default-initialized; if
10071     //   the object is of const-qualified type, the underlying class
10072     //   type shall have a user-declared default
10073     //   constructor. Otherwise, if no initializer is specified for
10074     //   a non- static object, the object and its subobjects, if
10075     //   any, have an indeterminate initial value); if the object
10076     //   or any of its subobjects are of const-qualified type, the
10077     //   program is ill-formed.
10078     // C++0x [dcl.init]p11:
10079     //   If no initializer is specified for an object, the object is
10080     //   default-initialized; [...].
10081     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10082     InitializationKind Kind
10083       = InitializationKind::CreateDefault(Var->getLocation());
10084
10085     InitializationSequence InitSeq(*this, Entity, Kind, None);
10086     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10087     if (Init.isInvalid())
10088       Var->setInvalidDecl();
10089     else if (Init.get()) {
10090       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10091       // This is important for template substitution.
10092       Var->setInitStyle(VarDecl::CallInit);
10093     }
10094
10095     CheckCompleteVariableDeclaration(Var);
10096   }
10097 }
10098
10099 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10100   // If there is no declaration, there was an error parsing it. Ignore it.
10101   if (!D)
10102     return;
10103
10104   VarDecl *VD = dyn_cast<VarDecl>(D);
10105   if (!VD) {
10106     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10107     D->setInvalidDecl();
10108     return;
10109   }
10110
10111   VD->setCXXForRangeDecl(true);
10112
10113   // for-range-declaration cannot be given a storage class specifier.
10114   int Error = -1;
10115   switch (VD->getStorageClass()) {
10116   case SC_None:
10117     break;
10118   case SC_Extern:
10119     Error = 0;
10120     break;
10121   case SC_Static:
10122     Error = 1;
10123     break;
10124   case SC_PrivateExtern:
10125     Error = 2;
10126     break;
10127   case SC_Auto:
10128     Error = 3;
10129     break;
10130   case SC_Register:
10131     Error = 4;
10132     break;
10133   }
10134   if (Error != -1) {
10135     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10136       << VD->getDeclName() << Error;
10137     D->setInvalidDecl();
10138   }
10139 }
10140
10141 StmtResult
10142 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10143                                  IdentifierInfo *Ident,
10144                                  ParsedAttributes &Attrs,
10145                                  SourceLocation AttrEnd) {
10146   // C++1y [stmt.iter]p1:
10147   //   A range-based for statement of the form
10148   //      for ( for-range-identifier : for-range-initializer ) statement
10149   //   is equivalent to
10150   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10151   DeclSpec DS(Attrs.getPool().getFactory());
10152
10153   const char *PrevSpec;
10154   unsigned DiagID;
10155   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10156                      getPrintingPolicy());
10157
10158   Declarator D(DS, Declarator::ForContext);
10159   D.SetIdentifier(Ident, IdentLoc);
10160   D.takeAttributes(Attrs, AttrEnd);
10161
10162   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10163   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10164                 EmptyAttrs, IdentLoc);
10165   Decl *Var = ActOnDeclarator(S, D);
10166   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10167   FinalizeDeclaration(Var);
10168   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10169                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10170 }
10171
10172 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10173   if (var->isInvalidDecl()) return;
10174
10175   if (getLangOpts().OpenCL) {
10176     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10177     // initialiser
10178     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10179         !var->hasInit()) {
10180       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10181           << 1 /*Init*/;
10182       var->setInvalidDecl();
10183       return;
10184     }
10185   }
10186
10187   // In Objective-C, don't allow jumps past the implicit initialization of a
10188   // local retaining variable.
10189   if (getLangOpts().ObjC1 &&
10190       var->hasLocalStorage()) {
10191     switch (var->getType().getObjCLifetime()) {
10192     case Qualifiers::OCL_None:
10193     case Qualifiers::OCL_ExplicitNone:
10194     case Qualifiers::OCL_Autoreleasing:
10195       break;
10196
10197     case Qualifiers::OCL_Weak:
10198     case Qualifiers::OCL_Strong:
10199       getCurFunction()->setHasBranchProtectedScope();
10200       break;
10201     }
10202   }
10203
10204   // Warn about externally-visible variables being defined without a
10205   // prior declaration.  We only want to do this for global
10206   // declarations, but we also specifically need to avoid doing it for
10207   // class members because the linkage of an anonymous class can
10208   // change if it's later given a typedef name.
10209   if (var->isThisDeclarationADefinition() &&
10210       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10211       var->isExternallyVisible() && var->hasLinkage() &&
10212       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10213                                   var->getLocation())) {
10214     // Find a previous declaration that's not a definition.
10215     VarDecl *prev = var->getPreviousDecl();
10216     while (prev && prev->isThisDeclarationADefinition())
10217       prev = prev->getPreviousDecl();
10218
10219     if (!prev)
10220       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10221   }
10222
10223   if (var->getTLSKind() == VarDecl::TLS_Static) {
10224     const Expr *Culprit;
10225     if (var->getType().isDestructedType()) {
10226       // GNU C++98 edits for __thread, [basic.start.term]p3:
10227       //   The type of an object with thread storage duration shall not
10228       //   have a non-trivial destructor.
10229       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10230       if (getLangOpts().CPlusPlus11)
10231         Diag(var->getLocation(), diag::note_use_thread_local);
10232     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
10233                !var->getInit()->isConstantInitializer(
10234                    Context, var->getType()->isReferenceType(), &Culprit)) {
10235       // GNU C++98 edits for __thread, [basic.start.init]p4:
10236       //   An object of thread storage duration shall not require dynamic
10237       //   initialization.
10238       // FIXME: Need strict checking here.
10239       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
10240         << Culprit->getSourceRange();
10241       if (getLangOpts().CPlusPlus11)
10242         Diag(var->getLocation(), diag::note_use_thread_local);
10243     }
10244   }
10245
10246   // Apply section attributes and pragmas to global variables.
10247   bool GlobalStorage = var->hasGlobalStorage();
10248   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10249       ActiveTemplateInstantiations.empty()) {
10250     PragmaStack<StringLiteral *> *Stack = nullptr;
10251     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10252     if (var->getType().isConstQualified())
10253       Stack = &ConstSegStack;
10254     else if (!var->getInit()) {
10255       Stack = &BSSSegStack;
10256       SectionFlags |= ASTContext::PSF_Write;
10257     } else {
10258       Stack = &DataSegStack;
10259       SectionFlags |= ASTContext::PSF_Write;
10260     }
10261     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10262       var->addAttr(SectionAttr::CreateImplicit(
10263           Context, SectionAttr::Declspec_allocate,
10264           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10265     }
10266     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10267       if (UnifySection(SA->getName(), SectionFlags, var))
10268         var->dropAttr<SectionAttr>();
10269
10270     // Apply the init_seg attribute if this has an initializer.  If the
10271     // initializer turns out to not be dynamic, we'll end up ignoring this
10272     // attribute.
10273     if (CurInitSeg && var->getInit())
10274       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10275                                                CurInitSegLoc));
10276   }
10277
10278   // All the following checks are C++ only.
10279   if (!getLangOpts().CPlusPlus) return;
10280
10281   QualType type = var->getType();
10282   if (type->isDependentType()) return;
10283
10284   // __block variables might require us to capture a copy-initializer.
10285   if (var->hasAttr<BlocksAttr>()) {
10286     // It's currently invalid to ever have a __block variable with an
10287     // array type; should we diagnose that here?
10288
10289     // Regardless, we don't want to ignore array nesting when
10290     // constructing this copy.
10291     if (type->isStructureOrClassType()) {
10292       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10293       SourceLocation poi = var->getLocation();
10294       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10295       ExprResult result
10296         = PerformMoveOrCopyInitialization(
10297             InitializedEntity::InitializeBlock(poi, type, false),
10298             var, var->getType(), varRef, /*AllowNRVO=*/true);
10299       if (!result.isInvalid()) {
10300         result = MaybeCreateExprWithCleanups(result);
10301         Expr *init = result.getAs<Expr>();
10302         Context.setBlockVarCopyInits(var, init);
10303       }
10304     }
10305   }
10306
10307   Expr *Init = var->getInit();
10308   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10309   QualType baseType = Context.getBaseElementType(type);
10310
10311   if (!var->getDeclContext()->isDependentContext() &&
10312       Init && !Init->isValueDependent()) {
10313     if (IsGlobal && !var->isConstexpr() &&
10314         !getDiagnostics().isIgnored(diag::warn_global_constructor,
10315                                     var->getLocation())) {
10316       // Warn about globals which don't have a constant initializer.  Don't
10317       // warn about globals with a non-trivial destructor because we already
10318       // warned about them.
10319       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10320       if (!(RD && !RD->hasTrivialDestructor()) &&
10321           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10322         Diag(var->getLocation(), diag::warn_global_constructor)
10323           << Init->getSourceRange();
10324     }
10325
10326     if (var->isConstexpr()) {
10327       SmallVector<PartialDiagnosticAt, 8> Notes;
10328       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10329         SourceLocation DiagLoc = var->getLocation();
10330         // If the note doesn't add any useful information other than a source
10331         // location, fold it into the primary diagnostic.
10332         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10333               diag::note_invalid_subexpr_in_const_expr) {
10334           DiagLoc = Notes[0].first;
10335           Notes.clear();
10336         }
10337         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10338           << var << Init->getSourceRange();
10339         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10340           Diag(Notes[I].first, Notes[I].second);
10341       }
10342     } else if (var->isUsableInConstantExpressions(Context)) {
10343       // Check whether the initializer of a const variable of integral or
10344       // enumeration type is an ICE now, since we can't tell whether it was
10345       // initialized by a constant expression if we check later.
10346       var->checkInitIsICE();
10347     }
10348   }
10349
10350   // Require the destructor.
10351   if (const RecordType *recordType = baseType->getAs<RecordType>())
10352     FinalizeVarWithDestructor(var, recordType);
10353 }
10354
10355 /// \brief Determines if a variable's alignment is dependent.
10356 static bool hasDependentAlignment(VarDecl *VD) {
10357   if (VD->getType()->isDependentType())
10358     return true;
10359   for (auto *I : VD->specific_attrs<AlignedAttr>())
10360     if (I->isAlignmentDependent())
10361       return true;
10362   return false;
10363 }
10364
10365 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10366 /// any semantic actions necessary after any initializer has been attached.
10367 void
10368 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10369   // Note that we are no longer parsing the initializer for this declaration.
10370   ParsingInitForAutoVars.erase(ThisDecl);
10371
10372   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10373   if (!VD)
10374     return;
10375
10376   checkAttributesAfterMerging(*this, *VD);
10377
10378   // Perform TLS alignment check here after attributes attached to the variable
10379   // which may affect the alignment have been processed. Only perform the check
10380   // if the target has a maximum TLS alignment (zero means no constraints).
10381   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10382     // Protect the check so that it's not performed on dependent types and
10383     // dependent alignments (we can't determine the alignment in that case).
10384     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10385       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10386       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10387         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10388           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10389           << (unsigned)MaxAlignChars.getQuantity();
10390       }
10391     }
10392   }
10393
10394   if (VD->isStaticLocal()) {
10395     if (FunctionDecl *FD =
10396             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10397       // Static locals inherit dll attributes from their function.
10398       if (Attr *A = getDLLAttr(FD)) {
10399         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10400         NewAttr->setInherited(true);
10401         VD->addAttr(NewAttr);
10402       }
10403       // CUDA E.2.9.4: Within the body of a __device__ or __global__
10404       // function, only __shared__ variables may be declared with
10405       // static storage class.
10406       if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
10407           (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>()) &&
10408           !VD->hasAttr<CUDASharedAttr>()) {
10409         Diag(VD->getLocation(), diag::err_device_static_local_var);
10410         VD->setInvalidDecl();
10411       }
10412     }
10413   }
10414
10415   // Perform check for initializers of device-side global variables.
10416   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10417   // 7.5). CUDA also allows constant initializers for __constant__ and
10418   // __device__ variables.
10419   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
10420     const Expr *Init = VD->getInit();
10421     const bool IsGlobal = VD->hasGlobalStorage() && !VD->isStaticLocal();
10422     if (Init && IsGlobal &&
10423         (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10424          VD->hasAttr<CUDASharedAttr>())) {
10425       bool AllowedInit = false;
10426       if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10427         AllowedInit =
10428             isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10429       // We'll allow constant initializers even if it's a non-empty
10430       // constructor according to CUDA rules. This deviates from NVCC,
10431       // but allows us to handle things like constexpr constructors.
10432       if (!AllowedInit &&
10433           (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10434         AllowedInit = VD->getInit()->isConstantInitializer(
10435             Context, VD->getType()->isReferenceType());
10436
10437       if (!AllowedInit) {
10438         Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10439                                     ? diag::err_shared_var_init
10440                                     : diag::err_dynamic_var_init)
10441             << Init->getSourceRange();
10442         VD->setInvalidDecl();
10443       }
10444     }
10445   }
10446
10447   // Grab the dllimport or dllexport attribute off of the VarDecl.
10448   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10449
10450   // Imported static data members cannot be defined out-of-line.
10451   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10452     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10453         VD->isThisDeclarationADefinition()) {
10454       // We allow definitions of dllimport class template static data members
10455       // with a warning.
10456       CXXRecordDecl *Context =
10457         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10458       bool IsClassTemplateMember =
10459           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10460           Context->getDescribedClassTemplate();
10461
10462       Diag(VD->getLocation(),
10463            IsClassTemplateMember
10464                ? diag::warn_attribute_dllimport_static_field_definition
10465                : diag::err_attribute_dllimport_static_field_definition);
10466       Diag(IA->getLocation(), diag::note_attribute);
10467       if (!IsClassTemplateMember)
10468         VD->setInvalidDecl();
10469     }
10470   }
10471
10472   // dllimport/dllexport variables cannot be thread local, their TLS index
10473   // isn't exported with the variable.
10474   if (DLLAttr && VD->getTLSKind()) {
10475     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10476     if (F && getDLLAttr(F)) {
10477       assert(VD->isStaticLocal());
10478       // But if this is a static local in a dlimport/dllexport function, the
10479       // function will never be inlined, which means the var would never be
10480       // imported, so having it marked import/export is safe.
10481     } else {
10482       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10483                                                                     << DLLAttr;
10484       VD->setInvalidDecl();
10485     }
10486   }
10487
10488   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10489     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10490       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10491       VD->dropAttr<UsedAttr>();
10492     }
10493   }
10494
10495   const DeclContext *DC = VD->getDeclContext();
10496   // If there's a #pragma GCC visibility in scope, and this isn't a class
10497   // member, set the visibility of this variable.
10498   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10499     AddPushedVisibilityAttribute(VD);
10500
10501   // FIXME: Warn on unused templates.
10502   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10503       !isa<VarTemplatePartialSpecializationDecl>(VD))
10504     MarkUnusedFileScopedDecl(VD);
10505
10506   // Now we have parsed the initializer and can update the table of magic
10507   // tag values.
10508   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10509       !VD->getType()->isIntegralOrEnumerationType())
10510     return;
10511
10512   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10513     const Expr *MagicValueExpr = VD->getInit();
10514     if (!MagicValueExpr) {
10515       continue;
10516     }
10517     llvm::APSInt MagicValueInt;
10518     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10519       Diag(I->getRange().getBegin(),
10520            diag::err_type_tag_for_datatype_not_ice)
10521         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10522       continue;
10523     }
10524     if (MagicValueInt.getActiveBits() > 64) {
10525       Diag(I->getRange().getBegin(),
10526            diag::err_type_tag_for_datatype_too_large)
10527         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10528       continue;
10529     }
10530     uint64_t MagicValue = MagicValueInt.getZExtValue();
10531     RegisterTypeTagForDatatype(I->getArgumentKind(),
10532                                MagicValue,
10533                                I->getMatchingCType(),
10534                                I->getLayoutCompatible(),
10535                                I->getMustBeNull());
10536   }
10537 }
10538
10539 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10540                                                    ArrayRef<Decl *> Group) {
10541   SmallVector<Decl*, 8> Decls;
10542
10543   if (DS.isTypeSpecOwned())
10544     Decls.push_back(DS.getRepAsDecl());
10545
10546   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10547   for (unsigned i = 0, e = Group.size(); i != e; ++i)
10548     if (Decl *D = Group[i]) {
10549       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10550         if (!FirstDeclaratorInGroup)
10551           FirstDeclaratorInGroup = DD;
10552       Decls.push_back(D);
10553     }
10554
10555   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10556     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10557       handleTagNumbering(Tag, S);
10558       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10559           getLangOpts().CPlusPlus)
10560         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10561     }
10562   }
10563
10564   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10565 }
10566
10567 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10568 /// group, performing any necessary semantic checking.
10569 Sema::DeclGroupPtrTy
10570 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10571                            bool TypeMayContainAuto) {
10572   // C++0x [dcl.spec.auto]p7:
10573   //   If the type deduced for the template parameter U is not the same in each
10574   //   deduction, the program is ill-formed.
10575   // FIXME: When initializer-list support is added, a distinction is needed
10576   // between the deduced type U and the deduced type which 'auto' stands for.
10577   //   auto a = 0, b = { 1, 2, 3 };
10578   // is legal because the deduced type U is 'int' in both cases.
10579   if (TypeMayContainAuto && Group.size() > 1) {
10580     QualType Deduced;
10581     CanQualType DeducedCanon;
10582     VarDecl *DeducedDecl = nullptr;
10583     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10584       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10585         AutoType *AT = D->getType()->getContainedAutoType();
10586         // Don't reissue diagnostics when instantiating a template.
10587         if (AT && D->isInvalidDecl())
10588           break;
10589         QualType U = AT ? AT->getDeducedType() : QualType();
10590         if (!U.isNull()) {
10591           CanQualType UCanon = Context.getCanonicalType(U);
10592           if (Deduced.isNull()) {
10593             Deduced = U;
10594             DeducedCanon = UCanon;
10595             DeducedDecl = D;
10596           } else if (DeducedCanon != UCanon) {
10597             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10598                  diag::err_auto_different_deductions)
10599               << (unsigned)AT->getKeyword()
10600               << Deduced << DeducedDecl->getDeclName()
10601               << U << D->getDeclName()
10602               << DeducedDecl->getInit()->getSourceRange()
10603               << D->getInit()->getSourceRange();
10604             D->setInvalidDecl();
10605             break;
10606           }
10607         }
10608       }
10609     }
10610   }
10611
10612   ActOnDocumentableDecls(Group);
10613
10614   return DeclGroupPtrTy::make(
10615       DeclGroupRef::Create(Context, Group.data(), Group.size()));
10616 }
10617
10618 void Sema::ActOnDocumentableDecl(Decl *D) {
10619   ActOnDocumentableDecls(D);
10620 }
10621
10622 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10623   // Don't parse the comment if Doxygen diagnostics are ignored.
10624   if (Group.empty() || !Group[0])
10625     return;
10626
10627   if (Diags.isIgnored(diag::warn_doc_param_not_found,
10628                       Group[0]->getLocation()) &&
10629       Diags.isIgnored(diag::warn_unknown_comment_command_name,
10630                       Group[0]->getLocation()))
10631     return;
10632
10633   if (Group.size() >= 2) {
10634     // This is a decl group.  Normally it will contain only declarations
10635     // produced from declarator list.  But in case we have any definitions or
10636     // additional declaration references:
10637     //   'typedef struct S {} S;'
10638     //   'typedef struct S *S;'
10639     //   'struct S *pS;'
10640     // FinalizeDeclaratorGroup adds these as separate declarations.
10641     Decl *MaybeTagDecl = Group[0];
10642     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10643       Group = Group.slice(1);
10644     }
10645   }
10646
10647   // See if there are any new comments that are not attached to a decl.
10648   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10649   if (!Comments.empty() &&
10650       !Comments.back()->isAttached()) {
10651     // There is at least one comment that not attached to a decl.
10652     // Maybe it should be attached to one of these decls?
10653     //
10654     // Note that this way we pick up not only comments that precede the
10655     // declaration, but also comments that *follow* the declaration -- thanks to
10656     // the lookahead in the lexer: we've consumed the semicolon and looked
10657     // ahead through comments.
10658     for (unsigned i = 0, e = Group.size(); i != e; ++i)
10659       Context.getCommentForDecl(Group[i], &PP);
10660   }
10661 }
10662
10663 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10664 /// to introduce parameters into function prototype scope.
10665 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10666   const DeclSpec &DS = D.getDeclSpec();
10667
10668   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10669
10670   // C++03 [dcl.stc]p2 also permits 'auto'.
10671   StorageClass SC = SC_None;
10672   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10673     SC = SC_Register;
10674   } else if (getLangOpts().CPlusPlus &&
10675              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10676     SC = SC_Auto;
10677   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10678     Diag(DS.getStorageClassSpecLoc(),
10679          diag::err_invalid_storage_class_in_func_decl);
10680     D.getMutableDeclSpec().ClearStorageClassSpecs();
10681   }
10682
10683   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10684     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10685       << DeclSpec::getSpecifierName(TSCS);
10686   if (DS.isConstexprSpecified())
10687     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10688       << 0;
10689   if (DS.isConceptSpecified())
10690     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10691
10692   DiagnoseFunctionSpecifiers(DS);
10693
10694   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10695   QualType parmDeclType = TInfo->getType();
10696
10697   if (getLangOpts().CPlusPlus) {
10698     // Check that there are no default arguments inside the type of this
10699     // parameter.
10700     CheckExtraCXXDefaultArguments(D);
10701
10702     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10703     if (D.getCXXScopeSpec().isSet()) {
10704       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10705         << D.getCXXScopeSpec().getRange();
10706       D.getCXXScopeSpec().clear();
10707     }
10708   }
10709
10710   // Ensure we have a valid name
10711   IdentifierInfo *II = nullptr;
10712   if (D.hasName()) {
10713     II = D.getIdentifier();
10714     if (!II) {
10715       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10716         << GetNameForDeclarator(D).getName();
10717       D.setInvalidType(true);
10718     }
10719   }
10720
10721   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10722   if (II) {
10723     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10724                    ForRedeclaration);
10725     LookupName(R, S);
10726     if (R.isSingleResult()) {
10727       NamedDecl *PrevDecl = R.getFoundDecl();
10728       if (PrevDecl->isTemplateParameter()) {
10729         // Maybe we will complain about the shadowed template parameter.
10730         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10731         // Just pretend that we didn't see the previous declaration.
10732         PrevDecl = nullptr;
10733       } else if (S->isDeclScope(PrevDecl)) {
10734         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10735         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10736
10737         // Recover by removing the name
10738         II = nullptr;
10739         D.SetIdentifier(nullptr, D.getIdentifierLoc());
10740         D.setInvalidType(true);
10741       }
10742     }
10743   }
10744
10745   // Temporarily put parameter variables in the translation unit, not
10746   // the enclosing context.  This prevents them from accidentally
10747   // looking like class members in C++.
10748   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10749                                     D.getLocStart(),
10750                                     D.getIdentifierLoc(), II,
10751                                     parmDeclType, TInfo,
10752                                     SC);
10753
10754   if (D.isInvalidType())
10755     New->setInvalidDecl();
10756
10757   assert(S->isFunctionPrototypeScope());
10758   assert(S->getFunctionPrototypeDepth() >= 1);
10759   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10760                     S->getNextFunctionPrototypeIndex());
10761
10762   // Add the parameter declaration into this scope.
10763   S->AddDecl(New);
10764   if (II)
10765     IdResolver.AddDecl(New);
10766
10767   ProcessDeclAttributes(S, New, D);
10768
10769   if (D.getDeclSpec().isModulePrivateSpecified())
10770     Diag(New->getLocation(), diag::err_module_private_local)
10771       << 1 << New->getDeclName()
10772       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10773       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10774
10775   if (New->hasAttr<BlocksAttr>()) {
10776     Diag(New->getLocation(), diag::err_block_on_nonlocal);
10777   }
10778   return New;
10779 }
10780
10781 /// \brief Synthesizes a variable for a parameter arising from a
10782 /// typedef.
10783 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10784                                               SourceLocation Loc,
10785                                               QualType T) {
10786   /* FIXME: setting StartLoc == Loc.
10787      Would it be worth to modify callers so as to provide proper source
10788      location for the unnamed parameters, embedding the parameter's type? */
10789   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10790                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
10791                                            SC_None, nullptr);
10792   Param->setImplicit();
10793   return Param;
10794 }
10795
10796 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
10797                                     ParmVarDecl * const *ParamEnd) {
10798   // Don't diagnose unused-parameter errors in template instantiations; we
10799   // will already have done so in the template itself.
10800   if (!ActiveTemplateInstantiations.empty())
10801     return;
10802
10803   for (; Param != ParamEnd; ++Param) {
10804     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10805         !(*Param)->hasAttr<UnusedAttr>()) {
10806       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10807         << (*Param)->getDeclName();
10808     }
10809   }
10810 }
10811
10812 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
10813                                                   ParmVarDecl * const *ParamEnd,
10814                                                   QualType ReturnTy,
10815                                                   NamedDecl *D) {
10816   if (LangOpts.NumLargeByValueCopy == 0) // No check.
10817     return;
10818
10819   // Warn if the return value is pass-by-value and larger than the specified
10820   // threshold.
10821   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10822     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10823     if (Size > LangOpts.NumLargeByValueCopy)
10824       Diag(D->getLocation(), diag::warn_return_value_size)
10825           << D->getDeclName() << Size;
10826   }
10827
10828   // Warn if any parameter is pass-by-value and larger than the specified
10829   // threshold.
10830   for (; Param != ParamEnd; ++Param) {
10831     QualType T = (*Param)->getType();
10832     if (T->isDependentType() || !T.isPODType(Context))
10833       continue;
10834     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10835     if (Size > LangOpts.NumLargeByValueCopy)
10836       Diag((*Param)->getLocation(), diag::warn_parameter_size)
10837           << (*Param)->getDeclName() << Size;
10838   }
10839 }
10840
10841 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10842                                   SourceLocation NameLoc, IdentifierInfo *Name,
10843                                   QualType T, TypeSourceInfo *TSInfo,
10844                                   StorageClass SC) {
10845   // In ARC, infer a lifetime qualifier for appropriate parameter types.
10846   if (getLangOpts().ObjCAutoRefCount &&
10847       T.getObjCLifetime() == Qualifiers::OCL_None &&
10848       T->isObjCLifetimeType()) {
10849
10850     Qualifiers::ObjCLifetime lifetime;
10851
10852     // Special cases for arrays:
10853     //   - if it's const, use __unsafe_unretained
10854     //   - otherwise, it's an error
10855     if (T->isArrayType()) {
10856       if (!T.isConstQualified()) {
10857         DelayedDiagnostics.add(
10858             sema::DelayedDiagnostic::makeForbiddenType(
10859             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10860       }
10861       lifetime = Qualifiers::OCL_ExplicitNone;
10862     } else {
10863       lifetime = T->getObjCARCImplicitLifetime();
10864     }
10865     T = Context.getLifetimeQualifiedType(T, lifetime);
10866   }
10867
10868   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10869                                          Context.getAdjustedParameterType(T),
10870                                          TSInfo, SC, nullptr);
10871
10872   // Parameters can not be abstract class types.
10873   // For record types, this is done by the AbstractClassUsageDiagnoser once
10874   // the class has been completely parsed.
10875   if (!CurContext->isRecord() &&
10876       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10877                              AbstractParamType))
10878     New->setInvalidDecl();
10879
10880   // Parameter declarators cannot be interface types. All ObjC objects are
10881   // passed by reference.
10882   if (T->isObjCObjectType()) {
10883     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10884     Diag(NameLoc,
10885          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10886       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10887     T = Context.getObjCObjectPointerType(T);
10888     New->setType(T);
10889   }
10890
10891   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10892   // duration shall not be qualified by an address-space qualifier."
10893   // Since all parameters have automatic store duration, they can not have
10894   // an address space.
10895   if (T.getAddressSpace() != 0) {
10896     // OpenCL allows function arguments declared to be an array of a type
10897     // to be qualified with an address space.
10898     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10899       Diag(NameLoc, diag::err_arg_with_address_space);
10900       New->setInvalidDecl();
10901     }
10902   }
10903
10904   // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
10905   // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
10906   if (getLangOpts().OpenCL && T->isPointerType()) {
10907     const QualType PTy = T->getPointeeType();
10908     if (PTy->isImageType() || PTy->isSamplerT() || PTy->isPipeType()) {
10909       Diag(NameLoc, diag::err_opencl_pointer_to_type) << PTy;
10910       New->setInvalidDecl();
10911     }
10912   }
10913
10914   return New;
10915 }
10916
10917 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10918                                            SourceLocation LocAfterDecls) {
10919   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10920
10921   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10922   // for a K&R function.
10923   if (!FTI.hasPrototype) {
10924     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10925       --i;
10926       if (FTI.Params[i].Param == nullptr) {
10927         SmallString<256> Code;
10928         llvm::raw_svector_ostream(Code)
10929             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10930         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10931             << FTI.Params[i].Ident
10932             << FixItHint::CreateInsertion(LocAfterDecls, Code);
10933
10934         // Implicitly declare the argument as type 'int' for lack of a better
10935         // type.
10936         AttributeFactory attrs;
10937         DeclSpec DS(attrs);
10938         const char* PrevSpec; // unused
10939         unsigned DiagID; // unused
10940         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10941                            DiagID, Context.getPrintingPolicy());
10942         // Use the identifier location for the type source range.
10943         DS.SetRangeStart(FTI.Params[i].IdentLoc);
10944         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10945         Declarator ParamD(DS, Declarator::KNRTypeListContext);
10946         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10947         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10948       }
10949     }
10950   }
10951 }
10952
10953 Decl *
10954 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
10955                               MultiTemplateParamsArg TemplateParameterLists,
10956                               SkipBodyInfo *SkipBody) {
10957   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10958   assert(D.isFunctionDeclarator() && "Not a function declarator!");
10959   Scope *ParentScope = FnBodyScope->getParent();
10960
10961   D.setFunctionDefinitionKind(FDK_Definition);
10962   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
10963   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
10964 }
10965
10966 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
10967   Consumer.HandleInlineFunctionDefinition(D);
10968 }
10969
10970 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10971                              const FunctionDecl*& PossibleZeroParamPrototype) {
10972   // Don't warn about invalid declarations.
10973   if (FD->isInvalidDecl())
10974     return false;
10975
10976   // Or declarations that aren't global.
10977   if (!FD->isGlobal())
10978     return false;
10979
10980   // Don't warn about C++ member functions.
10981   if (isa<CXXMethodDecl>(FD))
10982     return false;
10983
10984   // Don't warn about 'main'.
10985   if (FD->isMain())
10986     return false;
10987
10988   // Don't warn about inline functions.
10989   if (FD->isInlined())
10990     return false;
10991
10992   // Don't warn about function templates.
10993   if (FD->getDescribedFunctionTemplate())
10994     return false;
10995
10996   // Don't warn about function template specializations.
10997   if (FD->isFunctionTemplateSpecialization())
10998     return false;
10999
11000   // Don't warn for OpenCL kernels.
11001   if (FD->hasAttr<OpenCLKernelAttr>())
11002     return false;
11003
11004   // Don't warn on explicitly deleted functions.
11005   if (FD->isDeleted())
11006     return false;
11007
11008   bool MissingPrototype = true;
11009   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11010        Prev; Prev = Prev->getPreviousDecl()) {
11011     // Ignore any declarations that occur in function or method
11012     // scope, because they aren't visible from the header.
11013     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11014       continue;
11015
11016     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11017     if (FD->getNumParams() == 0)
11018       PossibleZeroParamPrototype = Prev;
11019     break;
11020   }
11021
11022   return MissingPrototype;
11023 }
11024
11025 void
11026 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11027                                    const FunctionDecl *EffectiveDefinition,
11028                                    SkipBodyInfo *SkipBody) {
11029   // Don't complain if we're in GNU89 mode and the previous definition
11030   // was an extern inline function.
11031   const FunctionDecl *Definition = EffectiveDefinition;
11032   if (!Definition)
11033     if (!FD->isDefined(Definition))
11034       return;
11035
11036   if (canRedefineFunction(Definition, getLangOpts()))
11037     return;
11038
11039   // If we don't have a visible definition of the function, and it's inline or
11040   // a template, skip the new definition.
11041   if (SkipBody && !hasVisibleDefinition(Definition) &&
11042       (Definition->getFormalLinkage() == InternalLinkage ||
11043        Definition->isInlined() ||
11044        Definition->getDescribedFunctionTemplate() ||
11045        Definition->getNumTemplateParameterLists())) {
11046     SkipBody->ShouldSkip = true;
11047     if (auto *TD = Definition->getDescribedFunctionTemplate())
11048       makeMergedDefinitionVisible(TD, FD->getLocation());
11049     else
11050       makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11051                                   FD->getLocation());
11052     return;
11053   }
11054
11055   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11056       Definition->getStorageClass() == SC_Extern)
11057     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11058         << FD->getDeclName() << getLangOpts().CPlusPlus;
11059   else
11060     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11061
11062   Diag(Definition->getLocation(), diag::note_previous_definition);
11063   FD->setInvalidDecl();
11064 }
11065
11066 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11067                                    Sema &S) {
11068   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11069
11070   LambdaScopeInfo *LSI = S.PushLambdaScope();
11071   LSI->CallOperator = CallOperator;
11072   LSI->Lambda = LambdaClass;
11073   LSI->ReturnType = CallOperator->getReturnType();
11074   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11075
11076   if (LCD == LCD_None)
11077     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11078   else if (LCD == LCD_ByCopy)
11079     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11080   else if (LCD == LCD_ByRef)
11081     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11082   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11083
11084   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11085   LSI->Mutable = !CallOperator->isConst();
11086
11087   // Add the captures to the LSI so they can be noted as already
11088   // captured within tryCaptureVar.
11089   auto I = LambdaClass->field_begin();
11090   for (const auto &C : LambdaClass->captures()) {
11091     if (C.capturesVariable()) {
11092       VarDecl *VD = C.getCapturedVar();
11093       if (VD->isInitCapture())
11094         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11095       QualType CaptureType = VD->getType();
11096       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11097       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11098           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11099           /*EllipsisLoc*/C.isPackExpansion()
11100                          ? C.getEllipsisLoc() : SourceLocation(),
11101           CaptureType, /*Expr*/ nullptr);
11102
11103     } else if (C.capturesThis()) {
11104       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11105                               S.getCurrentThisType(), /*Expr*/ nullptr,
11106                               C.getCaptureKind() == LCK_StarThis);
11107     } else {
11108       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11109     }
11110     ++I;
11111   }
11112 }
11113
11114 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11115                                     SkipBodyInfo *SkipBody) {
11116   // Clear the last template instantiation error context.
11117   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11118
11119   if (!D)
11120     return D;
11121   FunctionDecl *FD = nullptr;
11122
11123   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11124     FD = FunTmpl->getTemplatedDecl();
11125   else
11126     FD = cast<FunctionDecl>(D);
11127
11128   // See if this is a redefinition.
11129   if (!FD->isLateTemplateParsed()) {
11130     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11131
11132     // If we're skipping the body, we're done. Don't enter the scope.
11133     if (SkipBody && SkipBody->ShouldSkip)
11134       return D;
11135   }
11136
11137   // If we are instantiating a generic lambda call operator, push
11138   // a LambdaScopeInfo onto the function stack.  But use the information
11139   // that's already been calculated (ActOnLambdaExpr) to prime the current
11140   // LambdaScopeInfo.
11141   // When the template operator is being specialized, the LambdaScopeInfo,
11142   // has to be properly restored so that tryCaptureVariable doesn't try
11143   // and capture any new variables. In addition when calculating potential
11144   // captures during transformation of nested lambdas, it is necessary to
11145   // have the LSI properly restored.
11146   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11147     assert(ActiveTemplateInstantiations.size() &&
11148       "There should be an active template instantiation on the stack "
11149       "when instantiating a generic lambda!");
11150     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11151   }
11152   else
11153     // Enter a new function scope
11154     PushFunctionScope();
11155
11156   // Builtin functions cannot be defined.
11157   if (unsigned BuiltinID = FD->getBuiltinID()) {
11158     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11159         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11160       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11161       FD->setInvalidDecl();
11162     }
11163   }
11164
11165   // The return type of a function definition must be complete
11166   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11167   QualType ResultType = FD->getReturnType();
11168   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11169       !FD->isInvalidDecl() &&
11170       RequireCompleteType(FD->getLocation(), ResultType,
11171                           diag::err_func_def_incomplete_result))
11172     FD->setInvalidDecl();
11173
11174   if (FnBodyScope)
11175     PushDeclContext(FnBodyScope, FD);
11176
11177   // Check the validity of our function parameters
11178   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
11179                            /*CheckParameterNames=*/true);
11180
11181   // Introduce our parameters into the function scope
11182   for (auto Param : FD->params()) {
11183     Param->setOwningFunction(FD);
11184
11185     // If this has an identifier, add it to the scope stack.
11186     if (Param->getIdentifier() && FnBodyScope) {
11187       CheckShadow(FnBodyScope, Param);
11188
11189       PushOnScopeChains(Param, FnBodyScope);
11190     }
11191   }
11192
11193   // If we had any tags defined in the function prototype,
11194   // introduce them into the function scope.
11195   if (FnBodyScope) {
11196     for (ArrayRef<NamedDecl *>::iterator
11197              I = FD->getDeclsInPrototypeScope().begin(),
11198              E = FD->getDeclsInPrototypeScope().end();
11199          I != E; ++I) {
11200       NamedDecl *D = *I;
11201
11202       // Some of these decls (like enums) may have been pinned to the
11203       // translation unit for lack of a real context earlier. If so, remove
11204       // from the translation unit and reattach to the current context.
11205       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
11206         // Is the decl actually in the context?
11207         if (Context.getTranslationUnitDecl()->containsDecl(D))
11208           Context.getTranslationUnitDecl()->removeDecl(D);
11209         // Either way, reassign the lexical decl context to our FunctionDecl.
11210         D->setLexicalDeclContext(CurContext);
11211       }
11212
11213       // If the decl has a non-null name, make accessible in the current scope.
11214       if (!D->getName().empty())
11215         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
11216
11217       // Similarly, dive into enums and fish their constants out, making them
11218       // accessible in this scope.
11219       if (auto *ED = dyn_cast<EnumDecl>(D)) {
11220         for (auto *EI : ED->enumerators())
11221           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11222       }
11223     }
11224   }
11225
11226   // Ensure that the function's exception specification is instantiated.
11227   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11228     ResolveExceptionSpec(D->getLocation(), FPT);
11229
11230   // dllimport cannot be applied to non-inline function definitions.
11231   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11232       !FD->isTemplateInstantiation()) {
11233     assert(!FD->hasAttr<DLLExportAttr>());
11234     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11235     FD->setInvalidDecl();
11236     return D;
11237   }
11238   // We want to attach documentation to original Decl (which might be
11239   // a function template).
11240   ActOnDocumentableDecl(D);
11241   if (getCurLexicalContext()->isObjCContainer() &&
11242       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11243       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11244     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11245
11246   return D;
11247 }
11248
11249 /// \brief Given the set of return statements within a function body,
11250 /// compute the variables that are subject to the named return value
11251 /// optimization.
11252 ///
11253 /// Each of the variables that is subject to the named return value
11254 /// optimization will be marked as NRVO variables in the AST, and any
11255 /// return statement that has a marked NRVO variable as its NRVO candidate can
11256 /// use the named return value optimization.
11257 ///
11258 /// This function applies a very simplistic algorithm for NRVO: if every return
11259 /// statement in the scope of a variable has the same NRVO candidate, that
11260 /// candidate is an NRVO variable.
11261 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11262   ReturnStmt **Returns = Scope->Returns.data();
11263
11264   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11265     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11266       if (!NRVOCandidate->isNRVOVariable())
11267         Returns[I]->setNRVOCandidate(nullptr);
11268     }
11269   }
11270 }
11271
11272 bool Sema::canDelayFunctionBody(const Declarator &D) {
11273   // We can't delay parsing the body of a constexpr function template (yet).
11274   if (D.getDeclSpec().isConstexprSpecified())
11275     return false;
11276
11277   // We can't delay parsing the body of a function template with a deduced
11278   // return type (yet).
11279   if (D.getDeclSpec().containsPlaceholderType()) {
11280     // If the placeholder introduces a non-deduced trailing return type,
11281     // we can still delay parsing it.
11282     if (D.getNumTypeObjects()) {
11283       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11284       if (Outer.Kind == DeclaratorChunk::Function &&
11285           Outer.Fun.hasTrailingReturnType()) {
11286         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11287         return Ty.isNull() || !Ty->isUndeducedType();
11288       }
11289     }
11290     return false;
11291   }
11292
11293   return true;
11294 }
11295
11296 bool Sema::canSkipFunctionBody(Decl *D) {
11297   // We cannot skip the body of a function (or function template) which is
11298   // constexpr, since we may need to evaluate its body in order to parse the
11299   // rest of the file.
11300   // We cannot skip the body of a function with an undeduced return type,
11301   // because any callers of that function need to know the type.
11302   if (const FunctionDecl *FD = D->getAsFunction())
11303     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11304       return false;
11305   return Consumer.shouldSkipFunctionBody(D);
11306 }
11307
11308 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11309   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11310     FD->setHasSkippedBody();
11311   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11312     MD->setHasSkippedBody();
11313   return ActOnFinishFunctionBody(Decl, nullptr);
11314 }
11315
11316 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11317   return ActOnFinishFunctionBody(D, BodyArg, false);
11318 }
11319
11320 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11321                                     bool IsInstantiation) {
11322   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11323
11324   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11325   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11326
11327   if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
11328     CheckCompletedCoroutineBody(FD, Body);
11329
11330   if (FD) {
11331     FD->setBody(Body);
11332
11333     if (getLangOpts().CPlusPlus14) {
11334       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11335           FD->getReturnType()->isUndeducedType()) {
11336         // If the function has a deduced result type but contains no 'return'
11337         // statements, the result type as written must be exactly 'auto', and
11338         // the deduced result type is 'void'.
11339         if (!FD->getReturnType()->getAs<AutoType>()) {
11340           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11341               << FD->getReturnType();
11342           FD->setInvalidDecl();
11343         } else {
11344           // Substitute 'void' for the 'auto' in the type.
11345           TypeLoc ResultType = getReturnTypeLoc(FD);
11346           Context.adjustDeducedFunctionResultType(
11347               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11348         }
11349       }
11350     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11351       // In C++11, we don't use 'auto' deduction rules for lambda call
11352       // operators because we don't support return type deduction.
11353       auto *LSI = getCurLambda();
11354       if (LSI->HasImplicitReturnType) {
11355         deduceClosureReturnType(*LSI);
11356
11357         // C++11 [expr.prim.lambda]p4:
11358         //   [...] if there are no return statements in the compound-statement
11359         //   [the deduced type is] the type void
11360         QualType RetType =
11361             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11362
11363         // Update the return type to the deduced type.
11364         const FunctionProtoType *Proto =
11365             FD->getType()->getAs<FunctionProtoType>();
11366         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11367                                             Proto->getExtProtoInfo()));
11368       }
11369     }
11370
11371     // The only way to be included in UndefinedButUsed is if there is an
11372     // ODR use before the definition. Avoid the expensive map lookup if this
11373     // is the first declaration.
11374     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11375       if (!FD->isExternallyVisible())
11376         UndefinedButUsed.erase(FD);
11377       else if (FD->isInlined() &&
11378                !LangOpts.GNUInline &&
11379                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11380         UndefinedButUsed.erase(FD);
11381     }
11382
11383     // If the function implicitly returns zero (like 'main') or is naked,
11384     // don't complain about missing return statements.
11385     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11386       WP.disableCheckFallThrough();
11387
11388     // MSVC permits the use of pure specifier (=0) on function definition,
11389     // defined at class scope, warn about this non-standard construct.
11390     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11391       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11392
11393     if (!FD->isInvalidDecl()) {
11394       // Don't diagnose unused parameters of defaulted or deleted functions.
11395       if (!FD->isDeleted() && !FD->isDefaulted())
11396         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
11397       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
11398                                              FD->getReturnType(), FD);
11399
11400       // If this is a structor, we need a vtable.
11401       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11402         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11403       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11404         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11405
11406       // Try to apply the named return value optimization. We have to check
11407       // if we can do this here because lambdas keep return statements around
11408       // to deduce an implicit return type.
11409       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11410           !FD->isDependentContext())
11411         computeNRVO(Body, getCurFunction());
11412     }
11413
11414     // GNU warning -Wmissing-prototypes:
11415     //   Warn if a global function is defined without a previous
11416     //   prototype declaration. This warning is issued even if the
11417     //   definition itself provides a prototype. The aim is to detect
11418     //   global functions that fail to be declared in header files.
11419     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11420     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11421       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11422
11423       if (PossibleZeroParamPrototype) {
11424         // We found a declaration that is not a prototype,
11425         // but that could be a zero-parameter prototype
11426         if (TypeSourceInfo *TI =
11427                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11428           TypeLoc TL = TI->getTypeLoc();
11429           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11430             Diag(PossibleZeroParamPrototype->getLocation(),
11431                  diag::note_declaration_not_a_prototype)
11432                 << PossibleZeroParamPrototype
11433                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11434         }
11435       }
11436     }
11437
11438     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11439       const CXXMethodDecl *KeyFunction;
11440       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11441           MD->isVirtual() &&
11442           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11443           MD == KeyFunction->getCanonicalDecl()) {
11444         // Update the key-function state if necessary for this ABI.
11445         if (FD->isInlined() &&
11446             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11447           Context.setNonKeyFunction(MD);
11448
11449           // If the newly-chosen key function is already defined, then we
11450           // need to mark the vtable as used retroactively.
11451           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11452           const FunctionDecl *Definition;
11453           if (KeyFunction && KeyFunction->isDefined(Definition))
11454             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11455         } else {
11456           // We just defined they key function; mark the vtable as used.
11457           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11458         }
11459       }
11460     }
11461
11462     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11463            "Function parsing confused");
11464   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11465     assert(MD == getCurMethodDecl() && "Method parsing confused");
11466     MD->setBody(Body);
11467     if (!MD->isInvalidDecl()) {
11468       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
11469       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
11470                                              MD->getReturnType(), MD);
11471
11472       if (Body)
11473         computeNRVO(Body, getCurFunction());
11474     }
11475     if (getCurFunction()->ObjCShouldCallSuper) {
11476       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11477         << MD->getSelector().getAsString();
11478       getCurFunction()->ObjCShouldCallSuper = false;
11479     }
11480     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11481       const ObjCMethodDecl *InitMethod = nullptr;
11482       bool isDesignated =
11483           MD->isDesignatedInitializerForTheInterface(&InitMethod);
11484       assert(isDesignated && InitMethod);
11485       (void)isDesignated;
11486
11487       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11488         auto IFace = MD->getClassInterface();
11489         if (!IFace)
11490           return false;
11491         auto SuperD = IFace->getSuperClass();
11492         if (!SuperD)
11493           return false;
11494         return SuperD->getIdentifier() ==
11495             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11496       };
11497       // Don't issue this warning for unavailable inits or direct subclasses
11498       // of NSObject.
11499       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11500         Diag(MD->getLocation(),
11501              diag::warn_objc_designated_init_missing_super_call);
11502         Diag(InitMethod->getLocation(),
11503              diag::note_objc_designated_init_marked_here);
11504       }
11505       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11506     }
11507     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11508       // Don't issue this warning for unavaialable inits.
11509       if (!MD->isUnavailable())
11510         Diag(MD->getLocation(),
11511              diag::warn_objc_secondary_init_missing_init_call);
11512       getCurFunction()->ObjCWarnForNoInitDelegation = false;
11513     }
11514   } else {
11515     return nullptr;
11516   }
11517
11518   assert(!getCurFunction()->ObjCShouldCallSuper &&
11519          "This should only be set for ObjC methods, which should have been "
11520          "handled in the block above.");
11521
11522   // Verify and clean out per-function state.
11523   if (Body && (!FD || !FD->isDefaulted())) {
11524     // C++ constructors that have function-try-blocks can't have return
11525     // statements in the handlers of that block. (C++ [except.handle]p14)
11526     // Verify this.
11527     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11528       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11529
11530     // Verify that gotos and switch cases don't jump into scopes illegally.
11531     if (getCurFunction()->NeedsScopeChecking() &&
11532         !PP.isCodeCompletionEnabled())
11533       DiagnoseInvalidJumps(Body);
11534
11535     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11536       if (!Destructor->getParent()->isDependentType())
11537         CheckDestructor(Destructor);
11538
11539       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11540                                              Destructor->getParent());
11541     }
11542
11543     // If any errors have occurred, clear out any temporaries that may have
11544     // been leftover. This ensures that these temporaries won't be picked up for
11545     // deletion in some later function.
11546     if (getDiagnostics().hasErrorOccurred() ||
11547         getDiagnostics().getSuppressAllDiagnostics()) {
11548       DiscardCleanupsInEvaluationContext();
11549     }
11550     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11551         !isa<FunctionTemplateDecl>(dcl)) {
11552       // Since the body is valid, issue any analysis-based warnings that are
11553       // enabled.
11554       ActivePolicy = &WP;
11555     }
11556
11557     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11558         (!CheckConstexprFunctionDecl(FD) ||
11559          !CheckConstexprFunctionBody(FD, Body)))
11560       FD->setInvalidDecl();
11561
11562     if (FD && FD->hasAttr<NakedAttr>()) {
11563       for (const Stmt *S : Body->children()) {
11564         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11565           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11566           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11567           FD->setInvalidDecl();
11568           break;
11569         }
11570       }
11571     }
11572
11573     assert(ExprCleanupObjects.size() ==
11574                ExprEvalContexts.back().NumCleanupObjects &&
11575            "Leftover temporaries in function");
11576     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
11577     assert(MaybeODRUseExprs.empty() &&
11578            "Leftover expressions for odr-use checking");
11579   }
11580
11581   if (!IsInstantiation)
11582     PopDeclContext();
11583
11584   PopFunctionScopeInfo(ActivePolicy, dcl);
11585   // If any errors have occurred, clear out any temporaries that may have
11586   // been leftover. This ensures that these temporaries won't be picked up for
11587   // deletion in some later function.
11588   if (getDiagnostics().hasErrorOccurred()) {
11589     DiscardCleanupsInEvaluationContext();
11590   }
11591
11592   return dcl;
11593 }
11594
11595 /// When we finish delayed parsing of an attribute, we must attach it to the
11596 /// relevant Decl.
11597 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11598                                        ParsedAttributes &Attrs) {
11599   // Always attach attributes to the underlying decl.
11600   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11601     D = TD->getTemplatedDecl();
11602   ProcessDeclAttributeList(S, D, Attrs.getList());
11603
11604   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11605     if (Method->isStatic())
11606       checkThisInStaticMemberFunctionAttributes(Method);
11607 }
11608
11609 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11610 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11611 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11612                                           IdentifierInfo &II, Scope *S) {
11613   // Before we produce a declaration for an implicitly defined
11614   // function, see whether there was a locally-scoped declaration of
11615   // this name as a function or variable. If so, use that
11616   // (non-visible) declaration, and complain about it.
11617   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11618     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11619     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11620     return ExternCPrev;
11621   }
11622
11623   // Extension in C99.  Legal in C90, but warn about it.
11624   unsigned diag_id;
11625   if (II.getName().startswith("__builtin_"))
11626     diag_id = diag::warn_builtin_unknown;
11627   else if (getLangOpts().C99)
11628     diag_id = diag::ext_implicit_function_decl;
11629   else
11630     diag_id = diag::warn_implicit_function_decl;
11631   Diag(Loc, diag_id) << &II;
11632
11633   // Because typo correction is expensive, only do it if the implicit
11634   // function declaration is going to be treated as an error.
11635   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11636     TypoCorrection Corrected;
11637     if (S &&
11638         (Corrected = CorrectTypo(
11639              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11640              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11641       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11642                    /*ErrorRecovery*/false);
11643   }
11644
11645   // Set a Declarator for the implicit definition: int foo();
11646   const char *Dummy;
11647   AttributeFactory attrFactory;
11648   DeclSpec DS(attrFactory);
11649   unsigned DiagID;
11650   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11651                                   Context.getPrintingPolicy());
11652   (void)Error; // Silence warning.
11653   assert(!Error && "Error setting up implicit decl!");
11654   SourceLocation NoLoc;
11655   Declarator D(DS, Declarator::BlockContext);
11656   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11657                                              /*IsAmbiguous=*/false,
11658                                              /*LParenLoc=*/NoLoc,
11659                                              /*Params=*/nullptr,
11660                                              /*NumParams=*/0,
11661                                              /*EllipsisLoc=*/NoLoc,
11662                                              /*RParenLoc=*/NoLoc,
11663                                              /*TypeQuals=*/0,
11664                                              /*RefQualifierIsLvalueRef=*/true,
11665                                              /*RefQualifierLoc=*/NoLoc,
11666                                              /*ConstQualifierLoc=*/NoLoc,
11667                                              /*VolatileQualifierLoc=*/NoLoc,
11668                                              /*RestrictQualifierLoc=*/NoLoc,
11669                                              /*MutableLoc=*/NoLoc,
11670                                              EST_None,
11671                                              /*ESpecRange=*/SourceRange(),
11672                                              /*Exceptions=*/nullptr,
11673                                              /*ExceptionRanges=*/nullptr,
11674                                              /*NumExceptions=*/0,
11675                                              /*NoexceptExpr=*/nullptr,
11676                                              /*ExceptionSpecTokens=*/nullptr,
11677                                              Loc, Loc, D),
11678                 DS.getAttributes(),
11679                 SourceLocation());
11680   D.SetIdentifier(&II, Loc);
11681
11682   // Insert this function into translation-unit scope.
11683
11684   DeclContext *PrevDC = CurContext;
11685   CurContext = Context.getTranslationUnitDecl();
11686
11687   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11688   FD->setImplicit();
11689
11690   CurContext = PrevDC;
11691
11692   AddKnownFunctionAttributes(FD);
11693
11694   return FD;
11695 }
11696
11697 /// \brief Adds any function attributes that we know a priori based on
11698 /// the declaration of this function.
11699 ///
11700 /// These attributes can apply both to implicitly-declared builtins
11701 /// (like __builtin___printf_chk) or to library-declared functions
11702 /// like NSLog or printf.
11703 ///
11704 /// We need to check for duplicate attributes both here and where user-written
11705 /// attributes are applied to declarations.
11706 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11707   if (FD->isInvalidDecl())
11708     return;
11709
11710   // If this is a built-in function, map its builtin attributes to
11711   // actual attributes.
11712   if (unsigned BuiltinID = FD->getBuiltinID()) {
11713     // Handle printf-formatting attributes.
11714     unsigned FormatIdx;
11715     bool HasVAListArg;
11716     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11717       if (!FD->hasAttr<FormatAttr>()) {
11718         const char *fmt = "printf";
11719         unsigned int NumParams = FD->getNumParams();
11720         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11721             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11722           fmt = "NSString";
11723         FD->addAttr(FormatAttr::CreateImplicit(Context,
11724                                                &Context.Idents.get(fmt),
11725                                                FormatIdx+1,
11726                                                HasVAListArg ? 0 : FormatIdx+2,
11727                                                FD->getLocation()));
11728       }
11729     }
11730     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11731                                              HasVAListArg)) {
11732      if (!FD->hasAttr<FormatAttr>())
11733        FD->addAttr(FormatAttr::CreateImplicit(Context,
11734                                               &Context.Idents.get("scanf"),
11735                                               FormatIdx+1,
11736                                               HasVAListArg ? 0 : FormatIdx+2,
11737                                               FD->getLocation()));
11738     }
11739
11740     // Mark const if we don't care about errno and that is the only
11741     // thing preventing the function from being const. This allows
11742     // IRgen to use LLVM intrinsics for such functions.
11743     if (!getLangOpts().MathErrno &&
11744         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11745       if (!FD->hasAttr<ConstAttr>())
11746         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11747     }
11748
11749     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11750         !FD->hasAttr<ReturnsTwiceAttr>())
11751       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11752                                          FD->getLocation()));
11753     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11754       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11755     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
11756       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
11757     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11758       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11759     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11760         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11761       // Add the appropriate attribute, depending on the CUDA compilation mode
11762       // and which target the builtin belongs to. For example, during host
11763       // compilation, aux builtins are __device__, while the rest are __host__.
11764       if (getLangOpts().CUDAIsDevice !=
11765           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11766         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11767       else
11768         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11769     }
11770   }
11771
11772   // If C++ exceptions are enabled but we are told extern "C" functions cannot
11773   // throw, add an implicit nothrow attribute to any extern "C" function we come
11774   // across.
11775   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
11776       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
11777     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
11778     if (!FPT || FPT->getExceptionSpecType() == EST_None)
11779       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11780   }
11781
11782   IdentifierInfo *Name = FD->getIdentifier();
11783   if (!Name)
11784     return;
11785   if ((!getLangOpts().CPlusPlus &&
11786        FD->getDeclContext()->isTranslationUnit()) ||
11787       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11788        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11789        LinkageSpecDecl::lang_c)) {
11790     // Okay: this could be a libc/libm/Objective-C function we know
11791     // about.
11792   } else
11793     return;
11794
11795   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11796     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11797     // target-specific builtins, perhaps?
11798     if (!FD->hasAttr<FormatAttr>())
11799       FD->addAttr(FormatAttr::CreateImplicit(Context,
11800                                              &Context.Idents.get("printf"), 2,
11801                                              Name->isStr("vasprintf") ? 0 : 3,
11802                                              FD->getLocation()));
11803   }
11804
11805   if (Name->isStr("__CFStringMakeConstantString")) {
11806     // We already have a __builtin___CFStringMakeConstantString,
11807     // but builds that use -fno-constant-cfstrings don't go through that.
11808     if (!FD->hasAttr<FormatArgAttr>())
11809       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11810                                                 FD->getLocation()));
11811   }
11812 }
11813
11814 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11815                                     TypeSourceInfo *TInfo) {
11816   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11817   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11818
11819   if (!TInfo) {
11820     assert(D.isInvalidType() && "no declarator info for valid type");
11821     TInfo = Context.getTrivialTypeSourceInfo(T);
11822   }
11823
11824   // Scope manipulation handled by caller.
11825   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11826                                            D.getLocStart(),
11827                                            D.getIdentifierLoc(),
11828                                            D.getIdentifier(),
11829                                            TInfo);
11830
11831   // Bail out immediately if we have an invalid declaration.
11832   if (D.isInvalidType()) {
11833     NewTD->setInvalidDecl();
11834     return NewTD;
11835   }
11836
11837   if (D.getDeclSpec().isModulePrivateSpecified()) {
11838     if (CurContext->isFunctionOrMethod())
11839       Diag(NewTD->getLocation(), diag::err_module_private_local)
11840         << 2 << NewTD->getDeclName()
11841         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11842         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11843     else
11844       NewTD->setModulePrivate();
11845   }
11846
11847   // C++ [dcl.typedef]p8:
11848   //   If the typedef declaration defines an unnamed class (or
11849   //   enum), the first typedef-name declared by the declaration
11850   //   to be that class type (or enum type) is used to denote the
11851   //   class type (or enum type) for linkage purposes only.
11852   // We need to check whether the type was declared in the declaration.
11853   switch (D.getDeclSpec().getTypeSpecType()) {
11854   case TST_enum:
11855   case TST_struct:
11856   case TST_interface:
11857   case TST_union:
11858   case TST_class: {
11859     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11860     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11861     break;
11862   }
11863
11864   default:
11865     break;
11866   }
11867
11868   return NewTD;
11869 }
11870
11871 /// \brief Check that this is a valid underlying type for an enum declaration.
11872 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11873   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11874   QualType T = TI->getType();
11875
11876   if (T->isDependentType())
11877     return false;
11878
11879   if (const BuiltinType *BT = T->getAs<BuiltinType>())
11880     if (BT->isInteger())
11881       return false;
11882
11883   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11884   return true;
11885 }
11886
11887 /// Check whether this is a valid redeclaration of a previous enumeration.
11888 /// \return true if the redeclaration was invalid.
11889 bool Sema::CheckEnumRedeclaration(
11890     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
11891     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
11892   bool IsFixed = !EnumUnderlyingTy.isNull();
11893
11894   if (IsScoped != Prev->isScoped()) {
11895     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11896       << Prev->isScoped();
11897     Diag(Prev->getLocation(), diag::note_previous_declaration);
11898     return true;
11899   }
11900
11901   if (IsFixed && Prev->isFixed()) {
11902     if (!EnumUnderlyingTy->isDependentType() &&
11903         !Prev->getIntegerType()->isDependentType() &&
11904         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11905                                         Prev->getIntegerType())) {
11906       // TODO: Highlight the underlying type of the redeclaration.
11907       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11908         << EnumUnderlyingTy << Prev->getIntegerType();
11909       Diag(Prev->getLocation(), diag::note_previous_declaration)
11910           << Prev->getIntegerTypeRange();
11911       return true;
11912     }
11913   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
11914     ;
11915   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
11916     ;
11917   } else if (IsFixed != Prev->isFixed()) {
11918     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11919       << Prev->isFixed();
11920     Diag(Prev->getLocation(), diag::note_previous_declaration);
11921     return true;
11922   }
11923
11924   return false;
11925 }
11926
11927 /// \brief Get diagnostic %select index for tag kind for
11928 /// redeclaration diagnostic message.
11929 /// WARNING: Indexes apply to particular diagnostics only!
11930 ///
11931 /// \returns diagnostic %select index.
11932 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
11933   switch (Tag) {
11934   case TTK_Struct: return 0;
11935   case TTK_Interface: return 1;
11936   case TTK_Class:  return 2;
11937   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11938   }
11939 }
11940
11941 /// \brief Determine if tag kind is a class-key compatible with
11942 /// class for redeclaration (class, struct, or __interface).
11943 ///
11944 /// \returns true iff the tag kind is compatible.
11945 static bool isClassCompatTagKind(TagTypeKind Tag)
11946 {
11947   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11948 }
11949
11950 /// \brief Determine whether a tag with a given kind is acceptable
11951 /// as a redeclaration of the given tag declaration.
11952 ///
11953 /// \returns true if the new tag kind is acceptable, false otherwise.
11954 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11955                                         TagTypeKind NewTag, bool isDefinition,
11956                                         SourceLocation NewTagLoc,
11957                                         const IdentifierInfo *Name) {
11958   // C++ [dcl.type.elab]p3:
11959   //   The class-key or enum keyword present in the
11960   //   elaborated-type-specifier shall agree in kind with the
11961   //   declaration to which the name in the elaborated-type-specifier
11962   //   refers. This rule also applies to the form of
11963   //   elaborated-type-specifier that declares a class-name or
11964   //   friend class since it can be construed as referring to the
11965   //   definition of the class. Thus, in any
11966   //   elaborated-type-specifier, the enum keyword shall be used to
11967   //   refer to an enumeration (7.2), the union class-key shall be
11968   //   used to refer to a union (clause 9), and either the class or
11969   //   struct class-key shall be used to refer to a class (clause 9)
11970   //   declared using the class or struct class-key.
11971   TagTypeKind OldTag = Previous->getTagKind();
11972   if (!isDefinition || !isClassCompatTagKind(NewTag))
11973     if (OldTag == NewTag)
11974       return true;
11975
11976   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11977     // Warn about the struct/class tag mismatch.
11978     bool isTemplate = false;
11979     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11980       isTemplate = Record->getDescribedClassTemplate();
11981
11982     if (!ActiveTemplateInstantiations.empty()) {
11983       // In a template instantiation, do not offer fix-its for tag mismatches
11984       // since they usually mess up the template instead of fixing the problem.
11985       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11986         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11987         << getRedeclDiagFromTagKind(OldTag);
11988       return true;
11989     }
11990
11991     if (isDefinition) {
11992       // On definitions, check previous tags and issue a fix-it for each
11993       // one that doesn't match the current tag.
11994       if (Previous->getDefinition()) {
11995         // Don't suggest fix-its for redefinitions.
11996         return true;
11997       }
11998
11999       bool previousMismatch = false;
12000       for (auto I : Previous->redecls()) {
12001         if (I->getTagKind() != NewTag) {
12002           if (!previousMismatch) {
12003             previousMismatch = true;
12004             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12005               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12006               << getRedeclDiagFromTagKind(I->getTagKind());
12007           }
12008           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12009             << getRedeclDiagFromTagKind(NewTag)
12010             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12011                  TypeWithKeyword::getTagTypeKindName(NewTag));
12012         }
12013       }
12014       return true;
12015     }
12016
12017     // Check for a previous definition.  If current tag and definition
12018     // are same type, do nothing.  If no definition, but disagree with
12019     // with previous tag type, give a warning, but no fix-it.
12020     const TagDecl *Redecl = Previous->getDefinition() ?
12021                             Previous->getDefinition() : Previous;
12022     if (Redecl->getTagKind() == NewTag) {
12023       return true;
12024     }
12025
12026     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12027       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12028       << getRedeclDiagFromTagKind(OldTag);
12029     Diag(Redecl->getLocation(), diag::note_previous_use);
12030
12031     // If there is a previous definition, suggest a fix-it.
12032     if (Previous->getDefinition()) {
12033         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12034           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12035           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12036                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12037     }
12038
12039     return true;
12040   }
12041   return false;
12042 }
12043
12044 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12045 /// from an outer enclosing namespace or file scope inside a friend declaration.
12046 /// This should provide the commented out code in the following snippet:
12047 ///   namespace N {
12048 ///     struct X;
12049 ///     namespace M {
12050 ///       struct Y { friend struct /*N::*/ X; };
12051 ///     }
12052 ///   }
12053 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12054                                          SourceLocation NameLoc) {
12055   // While the decl is in a namespace, do repeated lookup of that name and see
12056   // if we get the same namespace back.  If we do not, continue until
12057   // translation unit scope, at which point we have a fully qualified NNS.
12058   SmallVector<IdentifierInfo *, 4> Namespaces;
12059   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12060   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12061     // This tag should be declared in a namespace, which can only be enclosed by
12062     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12063     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12064     if (!Namespace || Namespace->isAnonymousNamespace())
12065       return FixItHint();
12066     IdentifierInfo *II = Namespace->getIdentifier();
12067     Namespaces.push_back(II);
12068     NamedDecl *Lookup = SemaRef.LookupSingleName(
12069         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12070     if (Lookup == Namespace)
12071       break;
12072   }
12073
12074   // Once we have all the namespaces, reverse them to go outermost first, and
12075   // build an NNS.
12076   SmallString<64> Insertion;
12077   llvm::raw_svector_ostream OS(Insertion);
12078   if (DC->isTranslationUnit())
12079     OS << "::";
12080   std::reverse(Namespaces.begin(), Namespaces.end());
12081   for (auto *II : Namespaces)
12082     OS << II->getName() << "::";
12083   return FixItHint::CreateInsertion(NameLoc, Insertion);
12084 }
12085
12086 /// \brief Determine whether a tag originally declared in context \p OldDC can
12087 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12088 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12089 /// using-declaration).
12090 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12091                                          DeclContext *NewDC) {
12092   OldDC = OldDC->getRedeclContext();
12093   NewDC = NewDC->getRedeclContext();
12094
12095   if (OldDC->Equals(NewDC))
12096     return true;
12097
12098   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12099   // encloses the other).
12100   if (S.getLangOpts().MSVCCompat &&
12101       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12102     return true;
12103
12104   return false;
12105 }
12106
12107 /// Find the DeclContext in which a tag is implicitly declared if we see an
12108 /// elaborated type specifier in the specified context, and lookup finds
12109 /// nothing.
12110 static DeclContext *getTagInjectionContext(DeclContext *DC) {
12111   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
12112     DC = DC->getParent();
12113   return DC;
12114 }
12115
12116 /// Find the Scope in which a tag is implicitly declared if we see an
12117 /// elaborated type specifier in the specified context, and lookup finds
12118 /// nothing.
12119 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
12120   while (S->isClassScope() ||
12121          (LangOpts.CPlusPlus &&
12122           S->isFunctionPrototypeScope()) ||
12123          ((S->getFlags() & Scope::DeclScope) == 0) ||
12124          (S->getEntity() && S->getEntity()->isTransparentContext()))
12125     S = S->getParent();
12126   return S;
12127 }
12128
12129 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12130 /// former case, Name will be non-null.  In the later case, Name will be null.
12131 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12132 /// reference/declaration/definition of a tag.
12133 ///
12134 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12135 /// trailing-type-specifier) other than one in an alias-declaration.
12136 ///
12137 /// \param SkipBody If non-null, will be set to indicate if the caller should
12138 /// skip the definition of this tag and treat it as if it were a declaration.
12139 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12140                      SourceLocation KWLoc, CXXScopeSpec &SS,
12141                      IdentifierInfo *Name, SourceLocation NameLoc,
12142                      AttributeList *Attr, AccessSpecifier AS,
12143                      SourceLocation ModulePrivateLoc,
12144                      MultiTemplateParamsArg TemplateParameterLists,
12145                      bool &OwnedDecl, bool &IsDependent,
12146                      SourceLocation ScopedEnumKWLoc,
12147                      bool ScopedEnumUsesClassTag,
12148                      TypeResult UnderlyingType,
12149                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12150   // If this is not a definition, it must have a name.
12151   IdentifierInfo *OrigName = Name;
12152   assert((Name != nullptr || TUK == TUK_Definition) &&
12153          "Nameless record must be a definition!");
12154   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12155
12156   OwnedDecl = false;
12157   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12158   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12159
12160   // FIXME: Check explicit specializations more carefully.
12161   bool isExplicitSpecialization = false;
12162   bool Invalid = false;
12163
12164   // We only need to do this matching if we have template parameters
12165   // or a scope specifier, which also conveniently avoids this work
12166   // for non-C++ cases.
12167   if (TemplateParameterLists.size() > 0 ||
12168       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12169     if (TemplateParameterList *TemplateParams =
12170             MatchTemplateParametersToScopeSpecifier(
12171                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12172                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12173       if (Kind == TTK_Enum) {
12174         Diag(KWLoc, diag::err_enum_template);
12175         return nullptr;
12176       }
12177
12178       if (TemplateParams->size() > 0) {
12179         // This is a declaration or definition of a class template (which may
12180         // be a member of another template).
12181
12182         if (Invalid)
12183           return nullptr;
12184
12185         OwnedDecl = false;
12186         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12187                                                SS, Name, NameLoc, Attr,
12188                                                TemplateParams, AS,
12189                                                ModulePrivateLoc,
12190                                                /*FriendLoc*/SourceLocation(),
12191                                                TemplateParameterLists.size()-1,
12192                                                TemplateParameterLists.data(),
12193                                                SkipBody);
12194         return Result.get();
12195       } else {
12196         // The "template<>" header is extraneous.
12197         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12198           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12199         isExplicitSpecialization = true;
12200       }
12201     }
12202   }
12203
12204   // Figure out the underlying type if this a enum declaration. We need to do
12205   // this early, because it's needed to detect if this is an incompatible
12206   // redeclaration.
12207   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12208   bool EnumUnderlyingIsImplicit = false;
12209
12210   if (Kind == TTK_Enum) {
12211     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12212       // No underlying type explicitly specified, or we failed to parse the
12213       // type, default to int.
12214       EnumUnderlying = Context.IntTy.getTypePtr();
12215     else if (UnderlyingType.get()) {
12216       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12217       // integral type; any cv-qualification is ignored.
12218       TypeSourceInfo *TI = nullptr;
12219       GetTypeFromParser(UnderlyingType.get(), &TI);
12220       EnumUnderlying = TI;
12221
12222       if (CheckEnumUnderlyingType(TI))
12223         // Recover by falling back to int.
12224         EnumUnderlying = Context.IntTy.getTypePtr();
12225
12226       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12227                                           UPPC_FixedUnderlyingType))
12228         EnumUnderlying = Context.IntTy.getTypePtr();
12229
12230     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12231       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12232         // Microsoft enums are always of int type.
12233         EnumUnderlying = Context.IntTy.getTypePtr();
12234         EnumUnderlyingIsImplicit = true;
12235       }
12236     }
12237   }
12238
12239   DeclContext *SearchDC = CurContext;
12240   DeclContext *DC = CurContext;
12241   bool isStdBadAlloc = false;
12242
12243   RedeclarationKind Redecl = ForRedeclaration;
12244   if (TUK == TUK_Friend || TUK == TUK_Reference)
12245     Redecl = NotForRedeclaration;
12246
12247   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12248   if (Name && SS.isNotEmpty()) {
12249     // We have a nested-name tag ('struct foo::bar').
12250
12251     // Check for invalid 'foo::'.
12252     if (SS.isInvalid()) {
12253       Name = nullptr;
12254       goto CreateNewDecl;
12255     }
12256
12257     // If this is a friend or a reference to a class in a dependent
12258     // context, don't try to make a decl for it.
12259     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12260       DC = computeDeclContext(SS, false);
12261       if (!DC) {
12262         IsDependent = true;
12263         return nullptr;
12264       }
12265     } else {
12266       DC = computeDeclContext(SS, true);
12267       if (!DC) {
12268         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12269           << SS.getRange();
12270         return nullptr;
12271       }
12272     }
12273
12274     if (RequireCompleteDeclContext(SS, DC))
12275       return nullptr;
12276
12277     SearchDC = DC;
12278     // Look-up name inside 'foo::'.
12279     LookupQualifiedName(Previous, DC);
12280
12281     if (Previous.isAmbiguous())
12282       return nullptr;
12283
12284     if (Previous.empty()) {
12285       // Name lookup did not find anything. However, if the
12286       // nested-name-specifier refers to the current instantiation,
12287       // and that current instantiation has any dependent base
12288       // classes, we might find something at instantiation time: treat
12289       // this as a dependent elaborated-type-specifier.
12290       // But this only makes any sense for reference-like lookups.
12291       if (Previous.wasNotFoundInCurrentInstantiation() &&
12292           (TUK == TUK_Reference || TUK == TUK_Friend)) {
12293         IsDependent = true;
12294         return nullptr;
12295       }
12296
12297       // A tag 'foo::bar' must already exist.
12298       Diag(NameLoc, diag::err_not_tag_in_scope)
12299         << Kind << Name << DC << SS.getRange();
12300       Name = nullptr;
12301       Invalid = true;
12302       goto CreateNewDecl;
12303     }
12304   } else if (Name) {
12305     // C++14 [class.mem]p14:
12306     //   If T is the name of a class, then each of the following shall have a
12307     //   name different from T:
12308     //    -- every member of class T that is itself a type
12309     if (TUK != TUK_Reference && TUK != TUK_Friend &&
12310         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12311       return nullptr;
12312
12313     // If this is a named struct, check to see if there was a previous forward
12314     // declaration or definition.
12315     // FIXME: We're looking into outer scopes here, even when we
12316     // shouldn't be. Doing so can result in ambiguities that we
12317     // shouldn't be diagnosing.
12318     LookupName(Previous, S);
12319
12320     // When declaring or defining a tag, ignore ambiguities introduced
12321     // by types using'ed into this scope.
12322     if (Previous.isAmbiguous() &&
12323         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12324       LookupResult::Filter F = Previous.makeFilter();
12325       while (F.hasNext()) {
12326         NamedDecl *ND = F.next();
12327         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
12328           F.erase();
12329       }
12330       F.done();
12331     }
12332
12333     // C++11 [namespace.memdef]p3:
12334     //   If the name in a friend declaration is neither qualified nor
12335     //   a template-id and the declaration is a function or an
12336     //   elaborated-type-specifier, the lookup to determine whether
12337     //   the entity has been previously declared shall not consider
12338     //   any scopes outside the innermost enclosing namespace.
12339     //
12340     // MSVC doesn't implement the above rule for types, so a friend tag
12341     // declaration may be a redeclaration of a type declared in an enclosing
12342     // scope.  They do implement this rule for friend functions.
12343     //
12344     // Does it matter that this should be by scope instead of by
12345     // semantic context?
12346     if (!Previous.empty() && TUK == TUK_Friend) {
12347       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12348       LookupResult::Filter F = Previous.makeFilter();
12349       bool FriendSawTagOutsideEnclosingNamespace = false;
12350       while (F.hasNext()) {
12351         NamedDecl *ND = F.next();
12352         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12353         if (DC->isFileContext() &&
12354             !EnclosingNS->Encloses(ND->getDeclContext())) {
12355           if (getLangOpts().MSVCCompat)
12356             FriendSawTagOutsideEnclosingNamespace = true;
12357           else
12358             F.erase();
12359         }
12360       }
12361       F.done();
12362
12363       // Diagnose this MSVC extension in the easy case where lookup would have
12364       // unambiguously found something outside the enclosing namespace.
12365       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12366         NamedDecl *ND = Previous.getFoundDecl();
12367         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12368             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12369       }
12370     }
12371
12372     // Note:  there used to be some attempt at recovery here.
12373     if (Previous.isAmbiguous())
12374       return nullptr;
12375
12376     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12377       // FIXME: This makes sure that we ignore the contexts associated
12378       // with C structs, unions, and enums when looking for a matching
12379       // tag declaration or definition. See the similar lookup tweak
12380       // in Sema::LookupName; is there a better way to deal with this?
12381       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12382         SearchDC = SearchDC->getParent();
12383     }
12384   }
12385
12386   if (Previous.isSingleResult() &&
12387       Previous.getFoundDecl()->isTemplateParameter()) {
12388     // Maybe we will complain about the shadowed template parameter.
12389     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12390     // Just pretend that we didn't see the previous declaration.
12391     Previous.clear();
12392   }
12393
12394   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12395       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12396     // This is a declaration of or a reference to "std::bad_alloc".
12397     isStdBadAlloc = true;
12398
12399     if (Previous.empty() && StdBadAlloc) {
12400       // std::bad_alloc has been implicitly declared (but made invisible to
12401       // name lookup). Fill in this implicit declaration as the previous
12402       // declaration, so that the declarations get chained appropriately.
12403       Previous.addDecl(getStdBadAlloc());
12404     }
12405   }
12406
12407   // If we didn't find a previous declaration, and this is a reference
12408   // (or friend reference), move to the correct scope.  In C++, we
12409   // also need to do a redeclaration lookup there, just in case
12410   // there's a shadow friend decl.
12411   if (Name && Previous.empty() &&
12412       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12413     if (Invalid) goto CreateNewDecl;
12414     assert(SS.isEmpty());
12415
12416     if (TUK == TUK_Reference) {
12417       // C++ [basic.scope.pdecl]p5:
12418       //   -- for an elaborated-type-specifier of the form
12419       //
12420       //          class-key identifier
12421       //
12422       //      if the elaborated-type-specifier is used in the
12423       //      decl-specifier-seq or parameter-declaration-clause of a
12424       //      function defined in namespace scope, the identifier is
12425       //      declared as a class-name in the namespace that contains
12426       //      the declaration; otherwise, except as a friend
12427       //      declaration, the identifier is declared in the smallest
12428       //      non-class, non-function-prototype scope that contains the
12429       //      declaration.
12430       //
12431       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12432       // C structs and unions.
12433       //
12434       // It is an error in C++ to declare (rather than define) an enum
12435       // type, including via an elaborated type specifier.  We'll
12436       // diagnose that later; for now, declare the enum in the same
12437       // scope as we would have picked for any other tag type.
12438       //
12439       // GNU C also supports this behavior as part of its incomplete
12440       // enum types extension, while GNU C++ does not.
12441       //
12442       // Find the context where we'll be declaring the tag.
12443       // FIXME: We would like to maintain the current DeclContext as the
12444       // lexical context,
12445       SearchDC = getTagInjectionContext(SearchDC);
12446
12447       // Find the scope where we'll be declaring the tag.
12448       S = getTagInjectionScope(S, getLangOpts());
12449     } else {
12450       assert(TUK == TUK_Friend);
12451       // C++ [namespace.memdef]p3:
12452       //   If a friend declaration in a non-local class first declares a
12453       //   class or function, the friend class or function is a member of
12454       //   the innermost enclosing namespace.
12455       SearchDC = SearchDC->getEnclosingNamespaceContext();
12456     }
12457
12458     // In C++, we need to do a redeclaration lookup to properly
12459     // diagnose some problems.
12460     // FIXME: redeclaration lookup is also used (with and without C++) to find a
12461     // hidden declaration so that we don't get ambiguity errors when using a
12462     // type declared by an elaborated-type-specifier.  In C that is not correct
12463     // and we should instead merge compatible types found by lookup.
12464     if (getLangOpts().CPlusPlus) {
12465       Previous.setRedeclarationKind(ForRedeclaration);
12466       LookupQualifiedName(Previous, SearchDC);
12467     } else {
12468       Previous.setRedeclarationKind(ForRedeclaration);
12469       LookupName(Previous, S);
12470     }
12471   }
12472
12473   // If we have a known previous declaration to use, then use it.
12474   if (Previous.empty() && SkipBody && SkipBody->Previous)
12475     Previous.addDecl(SkipBody->Previous);
12476
12477   if (!Previous.empty()) {
12478     NamedDecl *PrevDecl = Previous.getFoundDecl();
12479     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12480
12481     // It's okay to have a tag decl in the same scope as a typedef
12482     // which hides a tag decl in the same scope.  Finding this
12483     // insanity with a redeclaration lookup can only actually happen
12484     // in C++.
12485     //
12486     // This is also okay for elaborated-type-specifiers, which is
12487     // technically forbidden by the current standard but which is
12488     // okay according to the likely resolution of an open issue;
12489     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12490     if (getLangOpts().CPlusPlus) {
12491       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12492         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12493           TagDecl *Tag = TT->getDecl();
12494           if (Tag->getDeclName() == Name &&
12495               Tag->getDeclContext()->getRedeclContext()
12496                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
12497             PrevDecl = Tag;
12498             Previous.clear();
12499             Previous.addDecl(Tag);
12500             Previous.resolveKind();
12501           }
12502         }
12503       }
12504     }
12505
12506     // If this is a redeclaration of a using shadow declaration, it must
12507     // declare a tag in the same context. In MSVC mode, we allow a
12508     // redefinition if either context is within the other.
12509     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12510       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12511       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12512           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12513           !(OldTag && isAcceptableTagRedeclContext(
12514                           *this, OldTag->getDeclContext(), SearchDC))) {
12515         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12516         Diag(Shadow->getTargetDecl()->getLocation(),
12517              diag::note_using_decl_target);
12518         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12519             << 0;
12520         // Recover by ignoring the old declaration.
12521         Previous.clear();
12522         goto CreateNewDecl;
12523       }
12524     }
12525
12526     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12527       // If this is a use of a previous tag, or if the tag is already declared
12528       // in the same scope (so that the definition/declaration completes or
12529       // rementions the tag), reuse the decl.
12530       if (TUK == TUK_Reference || TUK == TUK_Friend ||
12531           isDeclInScope(DirectPrevDecl, SearchDC, S,
12532                         SS.isNotEmpty() || isExplicitSpecialization)) {
12533         // Make sure that this wasn't declared as an enum and now used as a
12534         // struct or something similar.
12535         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12536                                           TUK == TUK_Definition, KWLoc,
12537                                           Name)) {
12538           bool SafeToContinue
12539             = (PrevTagDecl->getTagKind() != TTK_Enum &&
12540                Kind != TTK_Enum);
12541           if (SafeToContinue)
12542             Diag(KWLoc, diag::err_use_with_wrong_tag)
12543               << Name
12544               << FixItHint::CreateReplacement(SourceRange(KWLoc),
12545                                               PrevTagDecl->getKindName());
12546           else
12547             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12548           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12549
12550           if (SafeToContinue)
12551             Kind = PrevTagDecl->getTagKind();
12552           else {
12553             // Recover by making this an anonymous redefinition.
12554             Name = nullptr;
12555             Previous.clear();
12556             Invalid = true;
12557           }
12558         }
12559
12560         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12561           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12562
12563           // If this is an elaborated-type-specifier for a scoped enumeration,
12564           // the 'class' keyword is not necessary and not permitted.
12565           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12566             if (ScopedEnum)
12567               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12568                 << PrevEnum->isScoped()
12569                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12570             return PrevTagDecl;
12571           }
12572
12573           QualType EnumUnderlyingTy;
12574           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12575             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12576           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12577             EnumUnderlyingTy = QualType(T, 0);
12578
12579           // All conflicts with previous declarations are recovered by
12580           // returning the previous declaration, unless this is a definition,
12581           // in which case we want the caller to bail out.
12582           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12583                                      ScopedEnum, EnumUnderlyingTy,
12584                                      EnumUnderlyingIsImplicit, PrevEnum))
12585             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12586         }
12587
12588         // C++11 [class.mem]p1:
12589         //   A member shall not be declared twice in the member-specification,
12590         //   except that a nested class or member class template can be declared
12591         //   and then later defined.
12592         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12593             S->isDeclScope(PrevDecl)) {
12594           Diag(NameLoc, diag::ext_member_redeclared);
12595           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12596         }
12597
12598         if (!Invalid) {
12599           // If this is a use, just return the declaration we found, unless
12600           // we have attributes.
12601           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12602             if (Attr) {
12603               // FIXME: Diagnose these attributes. For now, we create a new
12604               // declaration to hold them.
12605             } else if (TUK == TUK_Reference &&
12606                        (PrevTagDecl->getFriendObjectKind() ==
12607                             Decl::FOK_Undeclared ||
12608                         PP.getModuleContainingLocation(
12609                             PrevDecl->getLocation()) !=
12610                             PP.getModuleContainingLocation(KWLoc)) &&
12611                        SS.isEmpty()) {
12612               // This declaration is a reference to an existing entity, but
12613               // has different visibility from that entity: it either makes
12614               // a friend visible or it makes a type visible in a new module.
12615               // In either case, create a new declaration. We only do this if
12616               // the declaration would have meant the same thing if no prior
12617               // declaration were found, that is, if it was found in the same
12618               // scope where we would have injected a declaration.
12619               if (!getTagInjectionContext(CurContext)->getRedeclContext()
12620                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
12621                 return PrevTagDecl;
12622               // This is in the injected scope, create a new declaration in
12623               // that scope.
12624               S = getTagInjectionScope(S, getLangOpts());
12625             } else {
12626               return PrevTagDecl;
12627             }
12628           }
12629
12630           // Diagnose attempts to redefine a tag.
12631           if (TUK == TUK_Definition) {
12632             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12633               // If we're defining a specialization and the previous definition
12634               // is from an implicit instantiation, don't emit an error
12635               // here; we'll catch this in the general case below.
12636               bool IsExplicitSpecializationAfterInstantiation = false;
12637               if (isExplicitSpecialization) {
12638                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12639                   IsExplicitSpecializationAfterInstantiation =
12640                     RD->getTemplateSpecializationKind() !=
12641                     TSK_ExplicitSpecialization;
12642                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12643                   IsExplicitSpecializationAfterInstantiation =
12644                     ED->getTemplateSpecializationKind() !=
12645                     TSK_ExplicitSpecialization;
12646               }
12647
12648               NamedDecl *Hidden = nullptr;
12649               if (SkipBody && getLangOpts().CPlusPlus &&
12650                   !hasVisibleDefinition(Def, &Hidden)) {
12651                 // There is a definition of this tag, but it is not visible. We
12652                 // explicitly make use of C++'s one definition rule here, and
12653                 // assume that this definition is identical to the hidden one
12654                 // we already have. Make the existing definition visible and
12655                 // use it in place of this one.
12656                 SkipBody->ShouldSkip = true;
12657                 makeMergedDefinitionVisible(Hidden, KWLoc);
12658                 return Def;
12659               } else if (!IsExplicitSpecializationAfterInstantiation) {
12660                 // A redeclaration in function prototype scope in C isn't
12661                 // visible elsewhere, so merely issue a warning.
12662                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12663                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12664                 else
12665                   Diag(NameLoc, diag::err_redefinition) << Name;
12666                 Diag(Def->getLocation(), diag::note_previous_definition);
12667                 // If this is a redefinition, recover by making this
12668                 // struct be anonymous, which will make any later
12669                 // references get the previous definition.
12670                 Name = nullptr;
12671                 Previous.clear();
12672                 Invalid = true;
12673               }
12674             } else {
12675               // If the type is currently being defined, complain
12676               // about a nested redefinition.
12677               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12678               if (TD->isBeingDefined()) {
12679                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12680                 Diag(PrevTagDecl->getLocation(),
12681                      diag::note_previous_definition);
12682                 Name = nullptr;
12683                 Previous.clear();
12684                 Invalid = true;
12685               }
12686             }
12687
12688             // Okay, this is definition of a previously declared or referenced
12689             // tag. We're going to create a new Decl for it.
12690           }
12691
12692           // Okay, we're going to make a redeclaration.  If this is some kind
12693           // of reference, make sure we build the redeclaration in the same DC
12694           // as the original, and ignore the current access specifier.
12695           if (TUK == TUK_Friend || TUK == TUK_Reference) {
12696             SearchDC = PrevTagDecl->getDeclContext();
12697             AS = AS_none;
12698           }
12699         }
12700         // If we get here we have (another) forward declaration or we
12701         // have a definition.  Just create a new decl.
12702
12703       } else {
12704         // If we get here, this is a definition of a new tag type in a nested
12705         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12706         // new decl/type.  We set PrevDecl to NULL so that the entities
12707         // have distinct types.
12708         Previous.clear();
12709       }
12710       // If we get here, we're going to create a new Decl. If PrevDecl
12711       // is non-NULL, it's a definition of the tag declared by
12712       // PrevDecl. If it's NULL, we have a new definition.
12713
12714     // Otherwise, PrevDecl is not a tag, but was found with tag
12715     // lookup.  This is only actually possible in C++, where a few
12716     // things like templates still live in the tag namespace.
12717     } else {
12718       // Use a better diagnostic if an elaborated-type-specifier
12719       // found the wrong kind of type on the first
12720       // (non-redeclaration) lookup.
12721       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12722           !Previous.isForRedeclaration()) {
12723         unsigned Kind = 0;
12724         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12725         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12726         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12727         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12728         Diag(PrevDecl->getLocation(), diag::note_declared_at);
12729         Invalid = true;
12730
12731       // Otherwise, only diagnose if the declaration is in scope.
12732       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12733                                 SS.isNotEmpty() || isExplicitSpecialization)) {
12734         // do nothing
12735
12736       // Diagnose implicit declarations introduced by elaborated types.
12737       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12738         unsigned Kind = 0;
12739         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12740         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12741         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12742         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12743         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12744         Invalid = true;
12745
12746       // Otherwise it's a declaration.  Call out a particularly common
12747       // case here.
12748       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12749         unsigned Kind = 0;
12750         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12751         Diag(NameLoc, diag::err_tag_definition_of_typedef)
12752           << Name << Kind << TND->getUnderlyingType();
12753         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12754         Invalid = true;
12755
12756       // Otherwise, diagnose.
12757       } else {
12758         // The tag name clashes with something else in the target scope,
12759         // issue an error and recover by making this tag be anonymous.
12760         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12761         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12762         Name = nullptr;
12763         Invalid = true;
12764       }
12765
12766       // The existing declaration isn't relevant to us; we're in a
12767       // new scope, so clear out the previous declaration.
12768       Previous.clear();
12769     }
12770   }
12771
12772 CreateNewDecl:
12773
12774   TagDecl *PrevDecl = nullptr;
12775   if (Previous.isSingleResult())
12776     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12777
12778   // If there is an identifier, use the location of the identifier as the
12779   // location of the decl, otherwise use the location of the struct/union
12780   // keyword.
12781   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12782
12783   // Otherwise, create a new declaration. If there is a previous
12784   // declaration of the same entity, the two will be linked via
12785   // PrevDecl.
12786   TagDecl *New;
12787
12788   bool IsForwardReference = false;
12789   if (Kind == TTK_Enum) {
12790     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12791     // enum X { A, B, C } D;    D should chain to X.
12792     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12793                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12794                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12795     // If this is an undefined enum, warn.
12796     if (TUK != TUK_Definition && !Invalid) {
12797       TagDecl *Def;
12798       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12799           cast<EnumDecl>(New)->isFixed()) {
12800         // C++0x: 7.2p2: opaque-enum-declaration.
12801         // Conflicts are diagnosed above. Do nothing.
12802       }
12803       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12804         Diag(Loc, diag::ext_forward_ref_enum_def)
12805           << New;
12806         Diag(Def->getLocation(), diag::note_previous_definition);
12807       } else {
12808         unsigned DiagID = diag::ext_forward_ref_enum;
12809         if (getLangOpts().MSVCCompat)
12810           DiagID = diag::ext_ms_forward_ref_enum;
12811         else if (getLangOpts().CPlusPlus)
12812           DiagID = diag::err_forward_ref_enum;
12813         Diag(Loc, DiagID);
12814
12815         // If this is a forward-declared reference to an enumeration, make a
12816         // note of it; we won't actually be introducing the declaration into
12817         // the declaration context.
12818         if (TUK == TUK_Reference)
12819           IsForwardReference = true;
12820       }
12821     }
12822
12823     if (EnumUnderlying) {
12824       EnumDecl *ED = cast<EnumDecl>(New);
12825       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12826         ED->setIntegerTypeSourceInfo(TI);
12827       else
12828         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12829       ED->setPromotionType(ED->getIntegerType());
12830     }
12831   } else {
12832     // struct/union/class
12833
12834     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12835     // struct X { int A; } D;    D should chain to X.
12836     if (getLangOpts().CPlusPlus) {
12837       // FIXME: Look for a way to use RecordDecl for simple structs.
12838       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12839                                   cast_or_null<CXXRecordDecl>(PrevDecl));
12840
12841       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12842         StdBadAlloc = cast<CXXRecordDecl>(New);
12843     } else
12844       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12845                                cast_or_null<RecordDecl>(PrevDecl));
12846   }
12847
12848   // C++11 [dcl.type]p3:
12849   //   A type-specifier-seq shall not define a class or enumeration [...].
12850   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12851     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12852       << Context.getTagDeclType(New);
12853     Invalid = true;
12854   }
12855
12856   // Maybe add qualifier info.
12857   if (SS.isNotEmpty()) {
12858     if (SS.isSet()) {
12859       // If this is either a declaration or a definition, check the
12860       // nested-name-specifier against the current context. We don't do this
12861       // for explicit specializations, because they have similar checking
12862       // (with more specific diagnostics) in the call to
12863       // CheckMemberSpecialization, below.
12864       if (!isExplicitSpecialization &&
12865           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12866           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12867         Invalid = true;
12868
12869       New->setQualifierInfo(SS.getWithLocInContext(Context));
12870       if (TemplateParameterLists.size() > 0) {
12871         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12872       }
12873     }
12874     else
12875       Invalid = true;
12876   }
12877
12878   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12879     // Add alignment attributes if necessary; these attributes are checked when
12880     // the ASTContext lays out the structure.
12881     //
12882     // It is important for implementing the correct semantics that this
12883     // happen here (in act on tag decl). The #pragma pack stack is
12884     // maintained as a result of parser callbacks which can occur at
12885     // many points during the parsing of a struct declaration (because
12886     // the #pragma tokens are effectively skipped over during the
12887     // parsing of the struct).
12888     if (TUK == TUK_Definition) {
12889       AddAlignmentAttributesForRecord(RD);
12890       AddMsStructLayoutForRecord(RD);
12891     }
12892   }
12893
12894   if (ModulePrivateLoc.isValid()) {
12895     if (isExplicitSpecialization)
12896       Diag(New->getLocation(), diag::err_module_private_specialization)
12897         << 2
12898         << FixItHint::CreateRemoval(ModulePrivateLoc);
12899     // __module_private__ does not apply to local classes. However, we only
12900     // diagnose this as an error when the declaration specifiers are
12901     // freestanding. Here, we just ignore the __module_private__.
12902     else if (!SearchDC->isFunctionOrMethod())
12903       New->setModulePrivate();
12904   }
12905
12906   // If this is a specialization of a member class (of a class template),
12907   // check the specialization.
12908   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12909     Invalid = true;
12910
12911   // If we're declaring or defining a tag in function prototype scope in C,
12912   // note that this type can only be used within the function and add it to
12913   // the list of decls to inject into the function definition scope.
12914   if ((Name || Kind == TTK_Enum) &&
12915       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12916     if (getLangOpts().CPlusPlus) {
12917       // C++ [dcl.fct]p6:
12918       //   Types shall not be defined in return or parameter types.
12919       if (TUK == TUK_Definition && !IsTypeSpecifier) {
12920         Diag(Loc, diag::err_type_defined_in_param_type)
12921             << Name;
12922         Invalid = true;
12923       }
12924     } else if (!PrevDecl) {
12925       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
12926     }
12927     DeclsInPrototypeScope.push_back(New);
12928   }
12929
12930   if (Invalid)
12931     New->setInvalidDecl();
12932
12933   if (Attr)
12934     ProcessDeclAttributeList(S, New, Attr);
12935
12936   // Set the lexical context. If the tag has a C++ scope specifier, the
12937   // lexical context will be different from the semantic context.
12938   New->setLexicalDeclContext(CurContext);
12939
12940   // Mark this as a friend decl if applicable.
12941   // In Microsoft mode, a friend declaration also acts as a forward
12942   // declaration so we always pass true to setObjectOfFriendDecl to make
12943   // the tag name visible.
12944   if (TUK == TUK_Friend)
12945     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
12946
12947   // Set the access specifier.
12948   if (!Invalid && SearchDC->isRecord())
12949     SetMemberAccessSpecifier(New, PrevDecl, AS);
12950
12951   if (TUK == TUK_Definition)
12952     New->startDefinition();
12953
12954   // If this has an identifier, add it to the scope stack.
12955   if (TUK == TUK_Friend) {
12956     // We might be replacing an existing declaration in the lookup tables;
12957     // if so, borrow its access specifier.
12958     if (PrevDecl)
12959       New->setAccess(PrevDecl->getAccess());
12960
12961     DeclContext *DC = New->getDeclContext()->getRedeclContext();
12962     DC->makeDeclVisibleInContext(New);
12963     if (Name) // can be null along some error paths
12964       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12965         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
12966   } else if (Name) {
12967     S = getNonFieldDeclScope(S);
12968     PushOnScopeChains(New, S, !IsForwardReference);
12969     if (IsForwardReference)
12970       SearchDC->makeDeclVisibleInContext(New);
12971   } else {
12972     CurContext->addDecl(New);
12973   }
12974
12975   // If this is the C FILE type, notify the AST context.
12976   if (IdentifierInfo *II = New->getIdentifier())
12977     if (!New->isInvalidDecl() &&
12978         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
12979         II->isStr("FILE"))
12980       Context.setFILEDecl(New);
12981
12982   if (PrevDecl)
12983     mergeDeclAttributes(New, PrevDecl);
12984
12985   // If there's a #pragma GCC visibility in scope, set the visibility of this
12986   // record.
12987   AddPushedVisibilityAttribute(New);
12988
12989   OwnedDecl = true;
12990   // In C++, don't return an invalid declaration. We can't recover well from
12991   // the cases where we make the type anonymous.
12992   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
12993 }
12994
12995 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
12996   AdjustDeclIfTemplate(TagD);
12997   TagDecl *Tag = cast<TagDecl>(TagD);
12998
12999   // Enter the tag context.
13000   PushDeclContext(S, Tag);
13001
13002   ActOnDocumentableDecl(TagD);
13003
13004   // If there's a #pragma GCC visibility in scope, set the visibility of this
13005   // record.
13006   AddPushedVisibilityAttribute(Tag);
13007 }
13008
13009 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13010   assert(isa<ObjCContainerDecl>(IDecl) &&
13011          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13012   DeclContext *OCD = cast<DeclContext>(IDecl);
13013   assert(getContainingDC(OCD) == CurContext &&
13014       "The next DeclContext should be lexically contained in the current one.");
13015   CurContext = OCD;
13016   return IDecl;
13017 }
13018
13019 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13020                                            SourceLocation FinalLoc,
13021                                            bool IsFinalSpelledSealed,
13022                                            SourceLocation LBraceLoc) {
13023   AdjustDeclIfTemplate(TagD);
13024   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13025
13026   FieldCollector->StartClass();
13027
13028   if (!Record->getIdentifier())
13029     return;
13030
13031   if (FinalLoc.isValid())
13032     Record->addAttr(new (Context)
13033                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13034
13035   // C++ [class]p2:
13036   //   [...] The class-name is also inserted into the scope of the
13037   //   class itself; this is known as the injected-class-name. For
13038   //   purposes of access checking, the injected-class-name is treated
13039   //   as if it were a public member name.
13040   CXXRecordDecl *InjectedClassName
13041     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13042                             Record->getLocStart(), Record->getLocation(),
13043                             Record->getIdentifier(),
13044                             /*PrevDecl=*/nullptr,
13045                             /*DelayTypeCreation=*/true);
13046   Context.getTypeDeclType(InjectedClassName, Record);
13047   InjectedClassName->setImplicit();
13048   InjectedClassName->setAccess(AS_public);
13049   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13050       InjectedClassName->setDescribedClassTemplate(Template);
13051   PushOnScopeChains(InjectedClassName, S);
13052   assert(InjectedClassName->isInjectedClassName() &&
13053          "Broken injected-class-name");
13054 }
13055
13056 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13057                                     SourceLocation RBraceLoc) {
13058   AdjustDeclIfTemplate(TagD);
13059   TagDecl *Tag = cast<TagDecl>(TagD);
13060   Tag->setRBraceLoc(RBraceLoc);
13061
13062   // Make sure we "complete" the definition even it is invalid.
13063   if (Tag->isBeingDefined()) {
13064     assert(Tag->isInvalidDecl() && "We should already have completed it");
13065     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13066       RD->completeDefinition();
13067   }
13068
13069   if (isa<CXXRecordDecl>(Tag))
13070     FieldCollector->FinishClass();
13071
13072   // Exit this scope of this tag's definition.
13073   PopDeclContext();
13074
13075   if (getCurLexicalContext()->isObjCContainer() &&
13076       Tag->getDeclContext()->isFileContext())
13077     Tag->setTopLevelDeclInObjCContainer();
13078
13079   // Notify the consumer that we've defined a tag.
13080   if (!Tag->isInvalidDecl())
13081     Consumer.HandleTagDeclDefinition(Tag);
13082 }
13083
13084 void Sema::ActOnObjCContainerFinishDefinition() {
13085   // Exit this scope of this interface definition.
13086   PopDeclContext();
13087 }
13088
13089 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13090   assert(DC == CurContext && "Mismatch of container contexts");
13091   OriginalLexicalContext = DC;
13092   ActOnObjCContainerFinishDefinition();
13093 }
13094
13095 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13096   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13097   OriginalLexicalContext = nullptr;
13098 }
13099
13100 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13101   AdjustDeclIfTemplate(TagD);
13102   TagDecl *Tag = cast<TagDecl>(TagD);
13103   Tag->setInvalidDecl();
13104
13105   // Make sure we "complete" the definition even it is invalid.
13106   if (Tag->isBeingDefined()) {
13107     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13108       RD->completeDefinition();
13109   }
13110
13111   // We're undoing ActOnTagStartDefinition here, not
13112   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13113   // the FieldCollector.
13114
13115   PopDeclContext();
13116 }
13117
13118 // Note that FieldName may be null for anonymous bitfields.
13119 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13120                                 IdentifierInfo *FieldName,
13121                                 QualType FieldTy, bool IsMsStruct,
13122                                 Expr *BitWidth, bool *ZeroWidth) {
13123   // Default to true; that shouldn't confuse checks for emptiness
13124   if (ZeroWidth)
13125     *ZeroWidth = true;
13126
13127   // C99 6.7.2.1p4 - verify the field type.
13128   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13129   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13130     // Handle incomplete types with specific error.
13131     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13132       return ExprError();
13133     if (FieldName)
13134       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13135         << FieldName << FieldTy << BitWidth->getSourceRange();
13136     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13137       << FieldTy << BitWidth->getSourceRange();
13138   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13139                                              UPPC_BitFieldWidth))
13140     return ExprError();
13141
13142   // If the bit-width is type- or value-dependent, don't try to check
13143   // it now.
13144   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13145     return BitWidth;
13146
13147   llvm::APSInt Value;
13148   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13149   if (ICE.isInvalid())
13150     return ICE;
13151   BitWidth = ICE.get();
13152
13153   if (Value != 0 && ZeroWidth)
13154     *ZeroWidth = false;
13155
13156   // Zero-width bitfield is ok for anonymous field.
13157   if (Value == 0 && FieldName)
13158     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13159
13160   if (Value.isSigned() && Value.isNegative()) {
13161     if (FieldName)
13162       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13163                << FieldName << Value.toString(10);
13164     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13165       << Value.toString(10);
13166   }
13167
13168   if (!FieldTy->isDependentType()) {
13169     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13170     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13171     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13172
13173     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13174     // ABI.
13175     bool CStdConstraintViolation =
13176         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13177     bool MSBitfieldViolation =
13178         Value.ugt(TypeStorageSize) &&
13179         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13180     if (CStdConstraintViolation || MSBitfieldViolation) {
13181       unsigned DiagWidth =
13182           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13183       if (FieldName)
13184         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13185                << FieldName << (unsigned)Value.getZExtValue()
13186                << !CStdConstraintViolation << DiagWidth;
13187
13188       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13189              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13190              << DiagWidth;
13191     }
13192
13193     // Warn on types where the user might conceivably expect to get all
13194     // specified bits as value bits: that's all integral types other than
13195     // 'bool'.
13196     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13197       if (FieldName)
13198         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13199             << FieldName << (unsigned)Value.getZExtValue()
13200             << (unsigned)TypeWidth;
13201       else
13202         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13203             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13204     }
13205   }
13206
13207   return BitWidth;
13208 }
13209
13210 /// ActOnField - Each field of a C struct/union is passed into this in order
13211 /// to create a FieldDecl object for it.
13212 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13213                        Declarator &D, Expr *BitfieldWidth) {
13214   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13215                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13216                                /*InitStyle=*/ICIS_NoInit, AS_public);
13217   return Res;
13218 }
13219
13220 /// HandleField - Analyze a field of a C struct or a C++ data member.
13221 ///
13222 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13223                              SourceLocation DeclStart,
13224                              Declarator &D, Expr *BitWidth,
13225                              InClassInitStyle InitStyle,
13226                              AccessSpecifier AS) {
13227   IdentifierInfo *II = D.getIdentifier();
13228   SourceLocation Loc = DeclStart;
13229   if (II) Loc = D.getIdentifierLoc();
13230
13231   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13232   QualType T = TInfo->getType();
13233   if (getLangOpts().CPlusPlus) {
13234     CheckExtraCXXDefaultArguments(D);
13235
13236     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13237                                         UPPC_DataMemberType)) {
13238       D.setInvalidType();
13239       T = Context.IntTy;
13240       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13241     }
13242   }
13243
13244   // TR 18037 does not allow fields to be declared with address spaces.
13245   if (T.getQualifiers().hasAddressSpace()) {
13246     Diag(Loc, diag::err_field_with_address_space);
13247     D.setInvalidType();
13248   }
13249
13250   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13251   // used as structure or union field: image, sampler, event or block types.
13252   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13253                           T->isSamplerT() || T->isBlockPointerType())) {
13254     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13255     D.setInvalidType();
13256   }
13257
13258   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13259
13260   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13261     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13262          diag::err_invalid_thread)
13263       << DeclSpec::getSpecifierName(TSCS);
13264
13265   // Check to see if this name was declared as a member previously
13266   NamedDecl *PrevDecl = nullptr;
13267   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13268   LookupName(Previous, S);
13269   switch (Previous.getResultKind()) {
13270     case LookupResult::Found:
13271     case LookupResult::FoundUnresolvedValue:
13272       PrevDecl = Previous.getAsSingle<NamedDecl>();
13273       break;
13274
13275     case LookupResult::FoundOverloaded:
13276       PrevDecl = Previous.getRepresentativeDecl();
13277       break;
13278
13279     case LookupResult::NotFound:
13280     case LookupResult::NotFoundInCurrentInstantiation:
13281     case LookupResult::Ambiguous:
13282       break;
13283   }
13284   Previous.suppressDiagnostics();
13285
13286   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13287     // Maybe we will complain about the shadowed template parameter.
13288     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13289     // Just pretend that we didn't see the previous declaration.
13290     PrevDecl = nullptr;
13291   }
13292
13293   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13294     PrevDecl = nullptr;
13295
13296   bool Mutable
13297     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13298   SourceLocation TSSL = D.getLocStart();
13299   FieldDecl *NewFD
13300     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13301                      TSSL, AS, PrevDecl, &D);
13302
13303   if (NewFD->isInvalidDecl())
13304     Record->setInvalidDecl();
13305
13306   if (D.getDeclSpec().isModulePrivateSpecified())
13307     NewFD->setModulePrivate();
13308
13309   if (NewFD->isInvalidDecl() && PrevDecl) {
13310     // Don't introduce NewFD into scope; there's already something
13311     // with the same name in the same scope.
13312   } else if (II) {
13313     PushOnScopeChains(NewFD, S);
13314   } else
13315     Record->addDecl(NewFD);
13316
13317   return NewFD;
13318 }
13319
13320 /// \brief Build a new FieldDecl and check its well-formedness.
13321 ///
13322 /// This routine builds a new FieldDecl given the fields name, type,
13323 /// record, etc. \p PrevDecl should refer to any previous declaration
13324 /// with the same name and in the same scope as the field to be
13325 /// created.
13326 ///
13327 /// \returns a new FieldDecl.
13328 ///
13329 /// \todo The Declarator argument is a hack. It will be removed once
13330 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13331                                 TypeSourceInfo *TInfo,
13332                                 RecordDecl *Record, SourceLocation Loc,
13333                                 bool Mutable, Expr *BitWidth,
13334                                 InClassInitStyle InitStyle,
13335                                 SourceLocation TSSL,
13336                                 AccessSpecifier AS, NamedDecl *PrevDecl,
13337                                 Declarator *D) {
13338   IdentifierInfo *II = Name.getAsIdentifierInfo();
13339   bool InvalidDecl = false;
13340   if (D) InvalidDecl = D->isInvalidType();
13341
13342   // If we receive a broken type, recover by assuming 'int' and
13343   // marking this declaration as invalid.
13344   if (T.isNull()) {
13345     InvalidDecl = true;
13346     T = Context.IntTy;
13347   }
13348
13349   QualType EltTy = Context.getBaseElementType(T);
13350   if (!EltTy->isDependentType()) {
13351     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13352       // Fields of incomplete type force their record to be invalid.
13353       Record->setInvalidDecl();
13354       InvalidDecl = true;
13355     } else {
13356       NamedDecl *Def;
13357       EltTy->isIncompleteType(&Def);
13358       if (Def && Def->isInvalidDecl()) {
13359         Record->setInvalidDecl();
13360         InvalidDecl = true;
13361       }
13362     }
13363   }
13364
13365   // OpenCL v1.2 s6.9.c: bitfields are not supported.
13366   if (BitWidth && getLangOpts().OpenCL) {
13367     Diag(Loc, diag::err_opencl_bitfields);
13368     InvalidDecl = true;
13369   }
13370
13371   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13372   // than a variably modified type.
13373   if (!InvalidDecl && T->isVariablyModifiedType()) {
13374     bool SizeIsNegative;
13375     llvm::APSInt Oversized;
13376
13377     TypeSourceInfo *FixedTInfo =
13378       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13379                                                     SizeIsNegative,
13380                                                     Oversized);
13381     if (FixedTInfo) {
13382       Diag(Loc, diag::warn_illegal_constant_array_size);
13383       TInfo = FixedTInfo;
13384       T = FixedTInfo->getType();
13385     } else {
13386       if (SizeIsNegative)
13387         Diag(Loc, diag::err_typecheck_negative_array_size);
13388       else if (Oversized.getBoolValue())
13389         Diag(Loc, diag::err_array_too_large)
13390           << Oversized.toString(10);
13391       else
13392         Diag(Loc, diag::err_typecheck_field_variable_size);
13393       InvalidDecl = true;
13394     }
13395   }
13396
13397   // Fields can not have abstract class types
13398   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13399                                              diag::err_abstract_type_in_decl,
13400                                              AbstractFieldType))
13401     InvalidDecl = true;
13402
13403   bool ZeroWidth = false;
13404   if (InvalidDecl)
13405     BitWidth = nullptr;
13406   // If this is declared as a bit-field, check the bit-field.
13407   if (BitWidth) {
13408     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13409                               &ZeroWidth).get();
13410     if (!BitWidth) {
13411       InvalidDecl = true;
13412       BitWidth = nullptr;
13413       ZeroWidth = false;
13414     }
13415   }
13416
13417   // Check that 'mutable' is consistent with the type of the declaration.
13418   if (!InvalidDecl && Mutable) {
13419     unsigned DiagID = 0;
13420     if (T->isReferenceType())
13421       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13422                                         : diag::err_mutable_reference;
13423     else if (T.isConstQualified())
13424       DiagID = diag::err_mutable_const;
13425
13426     if (DiagID) {
13427       SourceLocation ErrLoc = Loc;
13428       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13429         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13430       Diag(ErrLoc, DiagID);
13431       if (DiagID != diag::ext_mutable_reference) {
13432         Mutable = false;
13433         InvalidDecl = true;
13434       }
13435     }
13436   }
13437
13438   // C++11 [class.union]p8 (DR1460):
13439   //   At most one variant member of a union may have a
13440   //   brace-or-equal-initializer.
13441   if (InitStyle != ICIS_NoInit)
13442     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13443
13444   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13445                                        BitWidth, Mutable, InitStyle);
13446   if (InvalidDecl)
13447     NewFD->setInvalidDecl();
13448
13449   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13450     Diag(Loc, diag::err_duplicate_member) << II;
13451     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13452     NewFD->setInvalidDecl();
13453   }
13454
13455   if (!InvalidDecl && getLangOpts().CPlusPlus) {
13456     if (Record->isUnion()) {
13457       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13458         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13459         if (RDecl->getDefinition()) {
13460           // C++ [class.union]p1: An object of a class with a non-trivial
13461           // constructor, a non-trivial copy constructor, a non-trivial
13462           // destructor, or a non-trivial copy assignment operator
13463           // cannot be a member of a union, nor can an array of such
13464           // objects.
13465           if (CheckNontrivialField(NewFD))
13466             NewFD->setInvalidDecl();
13467         }
13468       }
13469
13470       // C++ [class.union]p1: If a union contains a member of reference type,
13471       // the program is ill-formed, except when compiling with MSVC extensions
13472       // enabled.
13473       if (EltTy->isReferenceType()) {
13474         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13475                                     diag::ext_union_member_of_reference_type :
13476                                     diag::err_union_member_of_reference_type)
13477           << NewFD->getDeclName() << EltTy;
13478         if (!getLangOpts().MicrosoftExt)
13479           NewFD->setInvalidDecl();
13480       }
13481     }
13482   }
13483
13484   // FIXME: We need to pass in the attributes given an AST
13485   // representation, not a parser representation.
13486   if (D) {
13487     // FIXME: The current scope is almost... but not entirely... correct here.
13488     ProcessDeclAttributes(getCurScope(), NewFD, *D);
13489
13490     if (NewFD->hasAttrs())
13491       CheckAlignasUnderalignment(NewFD);
13492   }
13493
13494   // In auto-retain/release, infer strong retension for fields of
13495   // retainable type.
13496   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13497     NewFD->setInvalidDecl();
13498
13499   if (T.isObjCGCWeak())
13500     Diag(Loc, diag::warn_attribute_weak_on_field);
13501
13502   NewFD->setAccess(AS);
13503   return NewFD;
13504 }
13505
13506 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13507   assert(FD);
13508   assert(getLangOpts().CPlusPlus && "valid check only for C++");
13509
13510   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13511     return false;
13512
13513   QualType EltTy = Context.getBaseElementType(FD->getType());
13514   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13515     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13516     if (RDecl->getDefinition()) {
13517       // We check for copy constructors before constructors
13518       // because otherwise we'll never get complaints about
13519       // copy constructors.
13520
13521       CXXSpecialMember member = CXXInvalid;
13522       // We're required to check for any non-trivial constructors. Since the
13523       // implicit default constructor is suppressed if there are any
13524       // user-declared constructors, we just need to check that there is a
13525       // trivial default constructor and a trivial copy constructor. (We don't
13526       // worry about move constructors here, since this is a C++98 check.)
13527       if (RDecl->hasNonTrivialCopyConstructor())
13528         member = CXXCopyConstructor;
13529       else if (!RDecl->hasTrivialDefaultConstructor())
13530         member = CXXDefaultConstructor;
13531       else if (RDecl->hasNonTrivialCopyAssignment())
13532         member = CXXCopyAssignment;
13533       else if (RDecl->hasNonTrivialDestructor())
13534         member = CXXDestructor;
13535
13536       if (member != CXXInvalid) {
13537         if (!getLangOpts().CPlusPlus11 &&
13538             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13539           // Objective-C++ ARC: it is an error to have a non-trivial field of
13540           // a union. However, system headers in Objective-C programs
13541           // occasionally have Objective-C lifetime objects within unions,
13542           // and rather than cause the program to fail, we make those
13543           // members unavailable.
13544           SourceLocation Loc = FD->getLocation();
13545           if (getSourceManager().isInSystemHeader(Loc)) {
13546             if (!FD->hasAttr<UnavailableAttr>())
13547               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13548                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13549             return false;
13550           }
13551         }
13552
13553         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13554                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13555                diag::err_illegal_union_or_anon_struct_member)
13556           << FD->getParent()->isUnion() << FD->getDeclName() << member;
13557         DiagnoseNontrivial(RDecl, member);
13558         return !getLangOpts().CPlusPlus11;
13559       }
13560     }
13561   }
13562
13563   return false;
13564 }
13565
13566 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13567 ///  AST enum value.
13568 static ObjCIvarDecl::AccessControl
13569 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13570   switch (ivarVisibility) {
13571   default: llvm_unreachable("Unknown visitibility kind");
13572   case tok::objc_private: return ObjCIvarDecl::Private;
13573   case tok::objc_public: return ObjCIvarDecl::Public;
13574   case tok::objc_protected: return ObjCIvarDecl::Protected;
13575   case tok::objc_package: return ObjCIvarDecl::Package;
13576   }
13577 }
13578
13579 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13580 /// in order to create an IvarDecl object for it.
13581 Decl *Sema::ActOnIvar(Scope *S,
13582                                 SourceLocation DeclStart,
13583                                 Declarator &D, Expr *BitfieldWidth,
13584                                 tok::ObjCKeywordKind Visibility) {
13585
13586   IdentifierInfo *II = D.getIdentifier();
13587   Expr *BitWidth = (Expr*)BitfieldWidth;
13588   SourceLocation Loc = DeclStart;
13589   if (II) Loc = D.getIdentifierLoc();
13590
13591   // FIXME: Unnamed fields can be handled in various different ways, for
13592   // example, unnamed unions inject all members into the struct namespace!
13593
13594   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13595   QualType T = TInfo->getType();
13596
13597   if (BitWidth) {
13598     // 6.7.2.1p3, 6.7.2.1p4
13599     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13600     if (!BitWidth)
13601       D.setInvalidType();
13602   } else {
13603     // Not a bitfield.
13604
13605     // validate II.
13606
13607   }
13608   if (T->isReferenceType()) {
13609     Diag(Loc, diag::err_ivar_reference_type);
13610     D.setInvalidType();
13611   }
13612   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13613   // than a variably modified type.
13614   else if (T->isVariablyModifiedType()) {
13615     Diag(Loc, diag::err_typecheck_ivar_variable_size);
13616     D.setInvalidType();
13617   }
13618
13619   // Get the visibility (access control) for this ivar.
13620   ObjCIvarDecl::AccessControl ac =
13621     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13622                                         : ObjCIvarDecl::None;
13623   // Must set ivar's DeclContext to its enclosing interface.
13624   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13625   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13626     return nullptr;
13627   ObjCContainerDecl *EnclosingContext;
13628   if (ObjCImplementationDecl *IMPDecl =
13629       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13630     if (LangOpts.ObjCRuntime.isFragile()) {
13631     // Case of ivar declared in an implementation. Context is that of its class.
13632       EnclosingContext = IMPDecl->getClassInterface();
13633       assert(EnclosingContext && "Implementation has no class interface!");
13634     }
13635     else
13636       EnclosingContext = EnclosingDecl;
13637   } else {
13638     if (ObjCCategoryDecl *CDecl =
13639         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13640       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13641         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13642         return nullptr;
13643       }
13644     }
13645     EnclosingContext = EnclosingDecl;
13646   }
13647
13648   // Construct the decl.
13649   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13650                                              DeclStart, Loc, II, T,
13651                                              TInfo, ac, (Expr *)BitfieldWidth);
13652
13653   if (II) {
13654     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13655                                            ForRedeclaration);
13656     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13657         && !isa<TagDecl>(PrevDecl)) {
13658       Diag(Loc, diag::err_duplicate_member) << II;
13659       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13660       NewID->setInvalidDecl();
13661     }
13662   }
13663
13664   // Process attributes attached to the ivar.
13665   ProcessDeclAttributes(S, NewID, D);
13666
13667   if (D.isInvalidType())
13668     NewID->setInvalidDecl();
13669
13670   // In ARC, infer 'retaining' for ivars of retainable type.
13671   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13672     NewID->setInvalidDecl();
13673
13674   if (D.getDeclSpec().isModulePrivateSpecified())
13675     NewID->setModulePrivate();
13676
13677   if (II) {
13678     // FIXME: When interfaces are DeclContexts, we'll need to add
13679     // these to the interface.
13680     S->AddDecl(NewID);
13681     IdResolver.AddDecl(NewID);
13682   }
13683
13684   if (LangOpts.ObjCRuntime.isNonFragile() &&
13685       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13686     Diag(Loc, diag::warn_ivars_in_interface);
13687
13688   return NewID;
13689 }
13690
13691 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13692 /// class and class extensions. For every class \@interface and class
13693 /// extension \@interface, if the last ivar is a bitfield of any type,
13694 /// then add an implicit `char :0` ivar to the end of that interface.
13695 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13696                              SmallVectorImpl<Decl *> &AllIvarDecls) {
13697   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13698     return;
13699
13700   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13701   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13702
13703   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13704     return;
13705   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13706   if (!ID) {
13707     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13708       if (!CD->IsClassExtension())
13709         return;
13710     }
13711     // No need to add this to end of @implementation.
13712     else
13713       return;
13714   }
13715   // All conditions are met. Add a new bitfield to the tail end of ivars.
13716   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13717   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13718
13719   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13720                               DeclLoc, DeclLoc, nullptr,
13721                               Context.CharTy,
13722                               Context.getTrivialTypeSourceInfo(Context.CharTy,
13723                                                                DeclLoc),
13724                               ObjCIvarDecl::Private, BW,
13725                               true);
13726   AllIvarDecls.push_back(Ivar);
13727 }
13728
13729 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13730                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
13731                        SourceLocation RBrac, AttributeList *Attr) {
13732   assert(EnclosingDecl && "missing record or interface decl");
13733
13734   // If this is an Objective-C @implementation or category and we have
13735   // new fields here we should reset the layout of the interface since
13736   // it will now change.
13737   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13738     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13739     switch (DC->getKind()) {
13740     default: break;
13741     case Decl::ObjCCategory:
13742       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13743       break;
13744     case Decl::ObjCImplementation:
13745       Context.
13746         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13747       break;
13748     }
13749   }
13750
13751   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13752
13753   // Start counting up the number of named members; make sure to include
13754   // members of anonymous structs and unions in the total.
13755   unsigned NumNamedMembers = 0;
13756   if (Record) {
13757     for (const auto *I : Record->decls()) {
13758       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13759         if (IFD->getDeclName())
13760           ++NumNamedMembers;
13761     }
13762   }
13763
13764   // Verify that all the fields are okay.
13765   SmallVector<FieldDecl*, 32> RecFields;
13766
13767   bool ARCErrReported = false;
13768   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13769        i != end; ++i) {
13770     FieldDecl *FD = cast<FieldDecl>(*i);
13771
13772     // Get the type for the field.
13773     const Type *FDTy = FD->getType().getTypePtr();
13774
13775     if (!FD->isAnonymousStructOrUnion()) {
13776       // Remember all fields written by the user.
13777       RecFields.push_back(FD);
13778     }
13779
13780     // If the field is already invalid for some reason, don't emit more
13781     // diagnostics about it.
13782     if (FD->isInvalidDecl()) {
13783       EnclosingDecl->setInvalidDecl();
13784       continue;
13785     }
13786
13787     // C99 6.7.2.1p2:
13788     //   A structure or union shall not contain a member with
13789     //   incomplete or function type (hence, a structure shall not
13790     //   contain an instance of itself, but may contain a pointer to
13791     //   an instance of itself), except that the last member of a
13792     //   structure with more than one named member may have incomplete
13793     //   array type; such a structure (and any union containing,
13794     //   possibly recursively, a member that is such a structure)
13795     //   shall not be a member of a structure or an element of an
13796     //   array.
13797     if (FDTy->isFunctionType()) {
13798       // Field declared as a function.
13799       Diag(FD->getLocation(), diag::err_field_declared_as_function)
13800         << FD->getDeclName();
13801       FD->setInvalidDecl();
13802       EnclosingDecl->setInvalidDecl();
13803       continue;
13804     } else if (FDTy->isIncompleteArrayType() && Record &&
13805                ((i + 1 == Fields.end() && !Record->isUnion()) ||
13806                 ((getLangOpts().MicrosoftExt ||
13807                   getLangOpts().CPlusPlus) &&
13808                  (i + 1 == Fields.end() || Record->isUnion())))) {
13809       // Flexible array member.
13810       // Microsoft and g++ is more permissive regarding flexible array.
13811       // It will accept flexible array in union and also
13812       // as the sole element of a struct/class.
13813       unsigned DiagID = 0;
13814       if (Record->isUnion())
13815         DiagID = getLangOpts().MicrosoftExt
13816                      ? diag::ext_flexible_array_union_ms
13817                      : getLangOpts().CPlusPlus
13818                            ? diag::ext_flexible_array_union_gnu
13819                            : diag::err_flexible_array_union;
13820       else if (Fields.size() == 1)
13821         DiagID = getLangOpts().MicrosoftExt
13822                      ? diag::ext_flexible_array_empty_aggregate_ms
13823                      : getLangOpts().CPlusPlus
13824                            ? diag::ext_flexible_array_empty_aggregate_gnu
13825                            : NumNamedMembers < 1
13826                                  ? diag::err_flexible_array_empty_aggregate
13827                                  : 0;
13828
13829       if (DiagID)
13830         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13831                                         << Record->getTagKind();
13832       // While the layout of types that contain virtual bases is not specified
13833       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13834       // virtual bases after the derived members.  This would make a flexible
13835       // array member declared at the end of an object not adjacent to the end
13836       // of the type.
13837       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13838         if (RD->getNumVBases() != 0)
13839           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13840             << FD->getDeclName() << Record->getTagKind();
13841       if (!getLangOpts().C99)
13842         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13843           << FD->getDeclName() << Record->getTagKind();
13844
13845       // If the element type has a non-trivial destructor, we would not
13846       // implicitly destroy the elements, so disallow it for now.
13847       //
13848       // FIXME: GCC allows this. We should probably either implicitly delete
13849       // the destructor of the containing class, or just allow this.
13850       QualType BaseElem = Context.getBaseElementType(FD->getType());
13851       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13852         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13853           << FD->getDeclName() << FD->getType();
13854         FD->setInvalidDecl();
13855         EnclosingDecl->setInvalidDecl();
13856         continue;
13857       }
13858       // Okay, we have a legal flexible array member at the end of the struct.
13859       Record->setHasFlexibleArrayMember(true);
13860     } else if (!FDTy->isDependentType() &&
13861                RequireCompleteType(FD->getLocation(), FD->getType(),
13862                                    diag::err_field_incomplete)) {
13863       // Incomplete type
13864       FD->setInvalidDecl();
13865       EnclosingDecl->setInvalidDecl();
13866       continue;
13867     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13868       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13869         // A type which contains a flexible array member is considered to be a
13870         // flexible array member.
13871         Record->setHasFlexibleArrayMember(true);
13872         if (!Record->isUnion()) {
13873           // If this is a struct/class and this is not the last element, reject
13874           // it.  Note that GCC supports variable sized arrays in the middle of
13875           // structures.
13876           if (i + 1 != Fields.end())
13877             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13878               << FD->getDeclName() << FD->getType();
13879           else {
13880             // We support flexible arrays at the end of structs in
13881             // other structs as an extension.
13882             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13883               << FD->getDeclName();
13884           }
13885         }
13886       }
13887       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13888           RequireNonAbstractType(FD->getLocation(), FD->getType(),
13889                                  diag::err_abstract_type_in_decl,
13890                                  AbstractIvarType)) {
13891         // Ivars can not have abstract class types
13892         FD->setInvalidDecl();
13893       }
13894       if (Record && FDTTy->getDecl()->hasObjectMember())
13895         Record->setHasObjectMember(true);
13896       if (Record && FDTTy->getDecl()->hasVolatileMember())
13897         Record->setHasVolatileMember(true);
13898     } else if (FDTy->isObjCObjectType()) {
13899       /// A field cannot be an Objective-c object
13900       Diag(FD->getLocation(), diag::err_statically_allocated_object)
13901         << FixItHint::CreateInsertion(FD->getLocation(), "*");
13902       QualType T = Context.getObjCObjectPointerType(FD->getType());
13903       FD->setType(T);
13904     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13905                (!getLangOpts().CPlusPlus || Record->isUnion())) {
13906       // It's an error in ARC if a field has lifetime.
13907       // We don't want to report this in a system header, though,
13908       // so we just make the field unavailable.
13909       // FIXME: that's really not sufficient; we need to make the type
13910       // itself invalid to, say, initialize or copy.
13911       QualType T = FD->getType();
13912       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
13913       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13914         SourceLocation loc = FD->getLocation();
13915         if (getSourceManager().isInSystemHeader(loc)) {
13916           if (!FD->hasAttr<UnavailableAttr>()) {
13917             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13918                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
13919           }
13920         } else {
13921           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
13922             << T->isBlockPointerType() << Record->getTagKind();
13923         }
13924         ARCErrReported = true;
13925       }
13926     } else if (getLangOpts().ObjC1 &&
13927                getLangOpts().getGC() != LangOptions::NonGC &&
13928                Record && !Record->hasObjectMember()) {
13929       if (FD->getType()->isObjCObjectPointerType() ||
13930           FD->getType().isObjCGCStrong())
13931         Record->setHasObjectMember(true);
13932       else if (Context.getAsArrayType(FD->getType())) {
13933         QualType BaseType = Context.getBaseElementType(FD->getType());
13934         if (BaseType->isRecordType() &&
13935             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
13936           Record->setHasObjectMember(true);
13937         else if (BaseType->isObjCObjectPointerType() ||
13938                  BaseType.isObjCGCStrong())
13939                Record->setHasObjectMember(true);
13940       }
13941     }
13942     if (Record && FD->getType().isVolatileQualified())
13943       Record->setHasVolatileMember(true);
13944     // Keep track of the number of named members.
13945     if (FD->getIdentifier())
13946       ++NumNamedMembers;
13947   }
13948
13949   // Okay, we successfully defined 'Record'.
13950   if (Record) {
13951     bool Completed = false;
13952     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
13953       if (!CXXRecord->isInvalidDecl()) {
13954         // Set access bits correctly on the directly-declared conversions.
13955         for (CXXRecordDecl::conversion_iterator
13956                I = CXXRecord->conversion_begin(),
13957                E = CXXRecord->conversion_end(); I != E; ++I)
13958           I.setAccess((*I)->getAccess());
13959       }
13960
13961       if (!CXXRecord->isDependentType()) {
13962         if (CXXRecord->hasUserDeclaredDestructor()) {
13963           // Adjust user-defined destructor exception spec.
13964           if (getLangOpts().CPlusPlus11)
13965             AdjustDestructorExceptionSpec(CXXRecord,
13966                                           CXXRecord->getDestructor());
13967         }
13968
13969         if (!CXXRecord->isInvalidDecl()) {
13970           // Add any implicitly-declared members to this class.
13971           AddImplicitlyDeclaredMembersToClass(CXXRecord);
13972
13973           // If we have virtual base classes, we may end up finding multiple
13974           // final overriders for a given virtual function. Check for this
13975           // problem now.
13976           if (CXXRecord->getNumVBases()) {
13977             CXXFinalOverriderMap FinalOverriders;
13978             CXXRecord->getFinalOverriders(FinalOverriders);
13979
13980             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
13981                                              MEnd = FinalOverriders.end();
13982                  M != MEnd; ++M) {
13983               for (OverridingMethods::iterator SO = M->second.begin(),
13984                                             SOEnd = M->second.end();
13985                    SO != SOEnd; ++SO) {
13986                 assert(SO->second.size() > 0 &&
13987                        "Virtual function without overridding functions?");
13988                 if (SO->second.size() == 1)
13989                   continue;
13990
13991                 // C++ [class.virtual]p2:
13992                 //   In a derived class, if a virtual member function of a base
13993                 //   class subobject has more than one final overrider the
13994                 //   program is ill-formed.
13995                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
13996                   << (const NamedDecl *)M->first << Record;
13997                 Diag(M->first->getLocation(),
13998                      diag::note_overridden_virtual_function);
13999                 for (OverridingMethods::overriding_iterator
14000                           OM = SO->second.begin(),
14001                        OMEnd = SO->second.end();
14002                      OM != OMEnd; ++OM)
14003                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14004                     << (const NamedDecl *)M->first << OM->Method->getParent();
14005
14006                 Record->setInvalidDecl();
14007               }
14008             }
14009             CXXRecord->completeDefinition(&FinalOverriders);
14010             Completed = true;
14011           }
14012         }
14013       }
14014     }
14015
14016     if (!Completed)
14017       Record->completeDefinition();
14018
14019     if (Record->hasAttrs()) {
14020       CheckAlignasUnderalignment(Record);
14021
14022       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14023         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14024                                            IA->getRange(), IA->getBestCase(),
14025                                            IA->getSemanticSpelling());
14026     }
14027
14028     // Check if the structure/union declaration is a type that can have zero
14029     // size in C. For C this is a language extension, for C++ it may cause
14030     // compatibility problems.
14031     bool CheckForZeroSize;
14032     if (!getLangOpts().CPlusPlus) {
14033       CheckForZeroSize = true;
14034     } else {
14035       // For C++ filter out types that cannot be referenced in C code.
14036       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14037       CheckForZeroSize =
14038           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14039           !CXXRecord->isDependentType() &&
14040           CXXRecord->isCLike();
14041     }
14042     if (CheckForZeroSize) {
14043       bool ZeroSize = true;
14044       bool IsEmpty = true;
14045       unsigned NonBitFields = 0;
14046       for (RecordDecl::field_iterator I = Record->field_begin(),
14047                                       E = Record->field_end();
14048            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14049         IsEmpty = false;
14050         if (I->isUnnamedBitfield()) {
14051           if (I->getBitWidthValue(Context) > 0)
14052             ZeroSize = false;
14053         } else {
14054           ++NonBitFields;
14055           QualType FieldType = I->getType();
14056           if (FieldType->isIncompleteType() ||
14057               !Context.getTypeSizeInChars(FieldType).isZero())
14058             ZeroSize = false;
14059         }
14060       }
14061
14062       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14063       // allowed in C++, but warn if its declaration is inside
14064       // extern "C" block.
14065       if (ZeroSize) {
14066         Diag(RecLoc, getLangOpts().CPlusPlus ?
14067                          diag::warn_zero_size_struct_union_in_extern_c :
14068                          diag::warn_zero_size_struct_union_compat)
14069           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14070       }
14071
14072       // Structs without named members are extension in C (C99 6.7.2.1p7),
14073       // but are accepted by GCC.
14074       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14075         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14076                                diag::ext_no_named_members_in_struct_union)
14077           << Record->isUnion();
14078       }
14079     }
14080   } else {
14081     ObjCIvarDecl **ClsFields =
14082       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14083     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14084       ID->setEndOfDefinitionLoc(RBrac);
14085       // Add ivar's to class's DeclContext.
14086       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14087         ClsFields[i]->setLexicalDeclContext(ID);
14088         ID->addDecl(ClsFields[i]);
14089       }
14090       // Must enforce the rule that ivars in the base classes may not be
14091       // duplicates.
14092       if (ID->getSuperClass())
14093         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14094     } else if (ObjCImplementationDecl *IMPDecl =
14095                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14096       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14097       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14098         // Ivar declared in @implementation never belongs to the implementation.
14099         // Only it is in implementation's lexical context.
14100         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14101       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14102       IMPDecl->setIvarLBraceLoc(LBrac);
14103       IMPDecl->setIvarRBraceLoc(RBrac);
14104     } else if (ObjCCategoryDecl *CDecl =
14105                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14106       // case of ivars in class extension; all other cases have been
14107       // reported as errors elsewhere.
14108       // FIXME. Class extension does not have a LocEnd field.
14109       // CDecl->setLocEnd(RBrac);
14110       // Add ivar's to class extension's DeclContext.
14111       // Diagnose redeclaration of private ivars.
14112       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14113       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14114         if (IDecl) {
14115           if (const ObjCIvarDecl *ClsIvar =
14116               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14117             Diag(ClsFields[i]->getLocation(),
14118                  diag::err_duplicate_ivar_declaration);
14119             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14120             continue;
14121           }
14122           for (const auto *Ext : IDecl->known_extensions()) {
14123             if (const ObjCIvarDecl *ClsExtIvar
14124                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14125               Diag(ClsFields[i]->getLocation(),
14126                    diag::err_duplicate_ivar_declaration);
14127               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14128               continue;
14129             }
14130           }
14131         }
14132         ClsFields[i]->setLexicalDeclContext(CDecl);
14133         CDecl->addDecl(ClsFields[i]);
14134       }
14135       CDecl->setIvarLBraceLoc(LBrac);
14136       CDecl->setIvarRBraceLoc(RBrac);
14137     }
14138   }
14139
14140   if (Attr)
14141     ProcessDeclAttributeList(S, Record, Attr);
14142 }
14143
14144 /// \brief Determine whether the given integral value is representable within
14145 /// the given type T.
14146 static bool isRepresentableIntegerValue(ASTContext &Context,
14147                                         llvm::APSInt &Value,
14148                                         QualType T) {
14149   assert(T->isIntegralType(Context) && "Integral type required!");
14150   unsigned BitWidth = Context.getIntWidth(T);
14151
14152   if (Value.isUnsigned() || Value.isNonNegative()) {
14153     if (T->isSignedIntegerOrEnumerationType())
14154       --BitWidth;
14155     return Value.getActiveBits() <= BitWidth;
14156   }
14157   return Value.getMinSignedBits() <= BitWidth;
14158 }
14159
14160 // \brief Given an integral type, return the next larger integral type
14161 // (or a NULL type of no such type exists).
14162 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14163   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14164   // enum checking below.
14165   assert(T->isIntegralType(Context) && "Integral type required!");
14166   const unsigned NumTypes = 4;
14167   QualType SignedIntegralTypes[NumTypes] = {
14168     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14169   };
14170   QualType UnsignedIntegralTypes[NumTypes] = {
14171     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14172     Context.UnsignedLongLongTy
14173   };
14174
14175   unsigned BitWidth = Context.getTypeSize(T);
14176   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14177                                                         : UnsignedIntegralTypes;
14178   for (unsigned I = 0; I != NumTypes; ++I)
14179     if (Context.getTypeSize(Types[I]) > BitWidth)
14180       return Types[I];
14181
14182   return QualType();
14183 }
14184
14185 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14186                                           EnumConstantDecl *LastEnumConst,
14187                                           SourceLocation IdLoc,
14188                                           IdentifierInfo *Id,
14189                                           Expr *Val) {
14190   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14191   llvm::APSInt EnumVal(IntWidth);
14192   QualType EltTy;
14193
14194   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14195     Val = nullptr;
14196
14197   if (Val)
14198     Val = DefaultLvalueConversion(Val).get();
14199
14200   if (Val) {
14201     if (Enum->isDependentType() || Val->isTypeDependent())
14202       EltTy = Context.DependentTy;
14203     else {
14204       SourceLocation ExpLoc;
14205       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14206           !getLangOpts().MSVCCompat) {
14207         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14208         // constant-expression in the enumerator-definition shall be a converted
14209         // constant expression of the underlying type.
14210         EltTy = Enum->getIntegerType();
14211         ExprResult Converted =
14212           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14213                                            CCEK_Enumerator);
14214         if (Converted.isInvalid())
14215           Val = nullptr;
14216         else
14217           Val = Converted.get();
14218       } else if (!Val->isValueDependent() &&
14219                  !(Val = VerifyIntegerConstantExpression(Val,
14220                                                          &EnumVal).get())) {
14221         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14222       } else {
14223         if (Enum->isFixed()) {
14224           EltTy = Enum->getIntegerType();
14225
14226           // In Obj-C and Microsoft mode, require the enumeration value to be
14227           // representable in the underlying type of the enumeration. In C++11,
14228           // we perform a non-narrowing conversion as part of converted constant
14229           // expression checking.
14230           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14231             if (getLangOpts().MSVCCompat) {
14232               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14233               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14234             } else
14235               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14236           } else
14237             Val = ImpCastExprToType(Val, EltTy,
14238                                     EltTy->isBooleanType() ?
14239                                     CK_IntegralToBoolean : CK_IntegralCast)
14240                     .get();
14241         } else if (getLangOpts().CPlusPlus) {
14242           // C++11 [dcl.enum]p5:
14243           //   If the underlying type is not fixed, the type of each enumerator
14244           //   is the type of its initializing value:
14245           //     - If an initializer is specified for an enumerator, the
14246           //       initializing value has the same type as the expression.
14247           EltTy = Val->getType();
14248         } else {
14249           // C99 6.7.2.2p2:
14250           //   The expression that defines the value of an enumeration constant
14251           //   shall be an integer constant expression that has a value
14252           //   representable as an int.
14253
14254           // Complain if the value is not representable in an int.
14255           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14256             Diag(IdLoc, diag::ext_enum_value_not_int)
14257               << EnumVal.toString(10) << Val->getSourceRange()
14258               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14259           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14260             // Force the type of the expression to 'int'.
14261             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14262           }
14263           EltTy = Val->getType();
14264         }
14265       }
14266     }
14267   }
14268
14269   if (!Val) {
14270     if (Enum->isDependentType())
14271       EltTy = Context.DependentTy;
14272     else if (!LastEnumConst) {
14273       // C++0x [dcl.enum]p5:
14274       //   If the underlying type is not fixed, the type of each enumerator
14275       //   is the type of its initializing value:
14276       //     - If no initializer is specified for the first enumerator, the
14277       //       initializing value has an unspecified integral type.
14278       //
14279       // GCC uses 'int' for its unspecified integral type, as does
14280       // C99 6.7.2.2p3.
14281       if (Enum->isFixed()) {
14282         EltTy = Enum->getIntegerType();
14283       }
14284       else {
14285         EltTy = Context.IntTy;
14286       }
14287     } else {
14288       // Assign the last value + 1.
14289       EnumVal = LastEnumConst->getInitVal();
14290       ++EnumVal;
14291       EltTy = LastEnumConst->getType();
14292
14293       // Check for overflow on increment.
14294       if (EnumVal < LastEnumConst->getInitVal()) {
14295         // C++0x [dcl.enum]p5:
14296         //   If the underlying type is not fixed, the type of each enumerator
14297         //   is the type of its initializing value:
14298         //
14299         //     - Otherwise the type of the initializing value is the same as
14300         //       the type of the initializing value of the preceding enumerator
14301         //       unless the incremented value is not representable in that type,
14302         //       in which case the type is an unspecified integral type
14303         //       sufficient to contain the incremented value. If no such type
14304         //       exists, the program is ill-formed.
14305         QualType T = getNextLargerIntegralType(Context, EltTy);
14306         if (T.isNull() || Enum->isFixed()) {
14307           // There is no integral type larger enough to represent this
14308           // value. Complain, then allow the value to wrap around.
14309           EnumVal = LastEnumConst->getInitVal();
14310           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14311           ++EnumVal;
14312           if (Enum->isFixed())
14313             // When the underlying type is fixed, this is ill-formed.
14314             Diag(IdLoc, diag::err_enumerator_wrapped)
14315               << EnumVal.toString(10)
14316               << EltTy;
14317           else
14318             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14319               << EnumVal.toString(10);
14320         } else {
14321           EltTy = T;
14322         }
14323
14324         // Retrieve the last enumerator's value, extent that type to the
14325         // type that is supposed to be large enough to represent the incremented
14326         // value, then increment.
14327         EnumVal = LastEnumConst->getInitVal();
14328         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14329         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14330         ++EnumVal;
14331
14332         // If we're not in C++, diagnose the overflow of enumerator values,
14333         // which in C99 means that the enumerator value is not representable in
14334         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14335         // permits enumerator values that are representable in some larger
14336         // integral type.
14337         if (!getLangOpts().CPlusPlus && !T.isNull())
14338           Diag(IdLoc, diag::warn_enum_value_overflow);
14339       } else if (!getLangOpts().CPlusPlus &&
14340                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14341         // Enforce C99 6.7.2.2p2 even when we compute the next value.
14342         Diag(IdLoc, diag::ext_enum_value_not_int)
14343           << EnumVal.toString(10) << 1;
14344       }
14345     }
14346   }
14347
14348   if (!EltTy->isDependentType()) {
14349     // Make the enumerator value match the signedness and size of the
14350     // enumerator's type.
14351     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14352     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14353   }
14354
14355   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14356                                   Val, EnumVal);
14357 }
14358
14359 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14360                                                 SourceLocation IILoc) {
14361   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14362       !getLangOpts().CPlusPlus)
14363     return SkipBodyInfo();
14364
14365   // We have an anonymous enum definition. Look up the first enumerator to
14366   // determine if we should merge the definition with an existing one and
14367   // skip the body.
14368   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14369                                          ForRedeclaration);
14370   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14371   if (!PrevECD)
14372     return SkipBodyInfo();
14373
14374   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14375   NamedDecl *Hidden;
14376   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14377     SkipBodyInfo Skip;
14378     Skip.Previous = Hidden;
14379     return Skip;
14380   }
14381
14382   return SkipBodyInfo();
14383 }
14384
14385 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14386                               SourceLocation IdLoc, IdentifierInfo *Id,
14387                               AttributeList *Attr,
14388                               SourceLocation EqualLoc, Expr *Val) {
14389   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14390   EnumConstantDecl *LastEnumConst =
14391     cast_or_null<EnumConstantDecl>(lastEnumConst);
14392
14393   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14394   // we find one that is.
14395   S = getNonFieldDeclScope(S);
14396
14397   // Verify that there isn't already something declared with this name in this
14398   // scope.
14399   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14400                                          ForRedeclaration);
14401   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14402     // Maybe we will complain about the shadowed template parameter.
14403     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14404     // Just pretend that we didn't see the previous declaration.
14405     PrevDecl = nullptr;
14406   }
14407
14408   // C++ [class.mem]p15:
14409   // If T is the name of a class, then each of the following shall have a name
14410   // different from T:
14411   // - every enumerator of every member of class T that is an unscoped
14412   // enumerated type
14413   if (!TheEnumDecl->isScoped())
14414     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14415                             DeclarationNameInfo(Id, IdLoc));
14416
14417   EnumConstantDecl *New =
14418     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14419   if (!New)
14420     return nullptr;
14421
14422   if (PrevDecl) {
14423     // When in C++, we may get a TagDecl with the same name; in this case the
14424     // enum constant will 'hide' the tag.
14425     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14426            "Received TagDecl when not in C++!");
14427     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14428         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14429       if (isa<EnumConstantDecl>(PrevDecl))
14430         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14431       else
14432         Diag(IdLoc, diag::err_redefinition) << Id;
14433       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14434       return nullptr;
14435     }
14436   }
14437
14438   // Process attributes.
14439   if (Attr) ProcessDeclAttributeList(S, New, Attr);
14440
14441   // Register this decl in the current scope stack.
14442   New->setAccess(TheEnumDecl->getAccess());
14443   PushOnScopeChains(New, S);
14444
14445   ActOnDocumentableDecl(New);
14446
14447   return New;
14448 }
14449
14450 // Returns true when the enum initial expression does not trigger the
14451 // duplicate enum warning.  A few common cases are exempted as follows:
14452 // Element2 = Element1
14453 // Element2 = Element1 + 1
14454 // Element2 = Element1 - 1
14455 // Where Element2 and Element1 are from the same enum.
14456 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14457   Expr *InitExpr = ECD->getInitExpr();
14458   if (!InitExpr)
14459     return true;
14460   InitExpr = InitExpr->IgnoreImpCasts();
14461
14462   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14463     if (!BO->isAdditiveOp())
14464       return true;
14465     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14466     if (!IL)
14467       return true;
14468     if (IL->getValue() != 1)
14469       return true;
14470
14471     InitExpr = BO->getLHS();
14472   }
14473
14474   // This checks if the elements are from the same enum.
14475   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14476   if (!DRE)
14477     return true;
14478
14479   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14480   if (!EnumConstant)
14481     return true;
14482
14483   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14484       Enum)
14485     return true;
14486
14487   return false;
14488 }
14489
14490 namespace {
14491 struct DupKey {
14492   int64_t val;
14493   bool isTombstoneOrEmptyKey;
14494   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14495     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14496 };
14497
14498 static DupKey GetDupKey(const llvm::APSInt& Val) {
14499   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14500                 false);
14501 }
14502
14503 struct DenseMapInfoDupKey {
14504   static DupKey getEmptyKey() { return DupKey(0, true); }
14505   static DupKey getTombstoneKey() { return DupKey(1, true); }
14506   static unsigned getHashValue(const DupKey Key) {
14507     return (unsigned)(Key.val * 37);
14508   }
14509   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14510     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14511            LHS.val == RHS.val;
14512   }
14513 };
14514 } // end anonymous namespace
14515
14516 // Emits a warning when an element is implicitly set a value that
14517 // a previous element has already been set to.
14518 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14519                                         EnumDecl *Enum,
14520                                         QualType EnumType) {
14521   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14522     return;
14523   // Avoid anonymous enums
14524   if (!Enum->getIdentifier())
14525     return;
14526
14527   // Only check for small enums.
14528   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14529     return;
14530
14531   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14532   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14533
14534   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14535   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14536           ValueToVectorMap;
14537
14538   DuplicatesVector DupVector;
14539   ValueToVectorMap EnumMap;
14540
14541   // Populate the EnumMap with all values represented by enum constants without
14542   // an initialier.
14543   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14544     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14545
14546     // Null EnumConstantDecl means a previous diagnostic has been emitted for
14547     // this constant.  Skip this enum since it may be ill-formed.
14548     if (!ECD) {
14549       return;
14550     }
14551
14552     if (ECD->getInitExpr())
14553       continue;
14554
14555     DupKey Key = GetDupKey(ECD->getInitVal());
14556     DeclOrVector &Entry = EnumMap[Key];
14557
14558     // First time encountering this value.
14559     if (Entry.isNull())
14560       Entry = ECD;
14561   }
14562
14563   // Create vectors for any values that has duplicates.
14564   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14565     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14566     if (!ValidDuplicateEnum(ECD, Enum))
14567       continue;
14568
14569     DupKey Key = GetDupKey(ECD->getInitVal());
14570
14571     DeclOrVector& Entry = EnumMap[Key];
14572     if (Entry.isNull())
14573       continue;
14574
14575     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14576       // Ensure constants are different.
14577       if (D == ECD)
14578         continue;
14579
14580       // Create new vector and push values onto it.
14581       ECDVector *Vec = new ECDVector();
14582       Vec->push_back(D);
14583       Vec->push_back(ECD);
14584
14585       // Update entry to point to the duplicates vector.
14586       Entry = Vec;
14587
14588       // Store the vector somewhere we can consult later for quick emission of
14589       // diagnostics.
14590       DupVector.push_back(Vec);
14591       continue;
14592     }
14593
14594     ECDVector *Vec = Entry.get<ECDVector*>();
14595     // Make sure constants are not added more than once.
14596     if (*Vec->begin() == ECD)
14597       continue;
14598
14599     Vec->push_back(ECD);
14600   }
14601
14602   // Emit diagnostics.
14603   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14604                                   DupVectorEnd = DupVector.end();
14605        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14606     ECDVector *Vec = *DupVectorIter;
14607     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14608
14609     // Emit warning for one enum constant.
14610     ECDVector::iterator I = Vec->begin();
14611     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14612       << (*I)->getName() << (*I)->getInitVal().toString(10)
14613       << (*I)->getSourceRange();
14614     ++I;
14615
14616     // Emit one note for each of the remaining enum constants with
14617     // the same value.
14618     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14619       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14620         << (*I)->getName() << (*I)->getInitVal().toString(10)
14621         << (*I)->getSourceRange();
14622     delete Vec;
14623   }
14624 }
14625
14626 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14627                              bool AllowMask) const {
14628   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14629   assert(ED->isCompleteDefinition() && "expected enum definition");
14630
14631   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14632   llvm::APInt &FlagBits = R.first->second;
14633
14634   if (R.second) {
14635     for (auto *E : ED->enumerators()) {
14636       const auto &EVal = E->getInitVal();
14637       // Only single-bit enumerators introduce new flag values.
14638       if (EVal.isPowerOf2())
14639         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14640     }
14641   }
14642
14643   // A value is in a flag enum if either its bits are a subset of the enum's
14644   // flag bits (the first condition) or we are allowing masks and the same is
14645   // true of its complement (the second condition). When masks are allowed, we
14646   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14647   //
14648   // While it's true that any value could be used as a mask, the assumption is
14649   // that a mask will have all of the insignificant bits set. Anything else is
14650   // likely a logic error.
14651   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14652   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14653 }
14654
14655 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14656                          SourceLocation RBraceLoc, Decl *EnumDeclX,
14657                          ArrayRef<Decl *> Elements,
14658                          Scope *S, AttributeList *Attr) {
14659   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14660   QualType EnumType = Context.getTypeDeclType(Enum);
14661
14662   if (Attr)
14663     ProcessDeclAttributeList(S, Enum, Attr);
14664
14665   if (Enum->isDependentType()) {
14666     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14667       EnumConstantDecl *ECD =
14668         cast_or_null<EnumConstantDecl>(Elements[i]);
14669       if (!ECD) continue;
14670
14671       ECD->setType(EnumType);
14672     }
14673
14674     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14675     return;
14676   }
14677
14678   // TODO: If the result value doesn't fit in an int, it must be a long or long
14679   // long value.  ISO C does not support this, but GCC does as an extension,
14680   // emit a warning.
14681   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14682   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14683   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14684
14685   // Verify that all the values are okay, compute the size of the values, and
14686   // reverse the list.
14687   unsigned NumNegativeBits = 0;
14688   unsigned NumPositiveBits = 0;
14689
14690   // Keep track of whether all elements have type int.
14691   bool AllElementsInt = true;
14692
14693   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14694     EnumConstantDecl *ECD =
14695       cast_or_null<EnumConstantDecl>(Elements[i]);
14696     if (!ECD) continue;  // Already issued a diagnostic.
14697
14698     const llvm::APSInt &InitVal = ECD->getInitVal();
14699
14700     // Keep track of the size of positive and negative values.
14701     if (InitVal.isUnsigned() || InitVal.isNonNegative())
14702       NumPositiveBits = std::max(NumPositiveBits,
14703                                  (unsigned)InitVal.getActiveBits());
14704     else
14705       NumNegativeBits = std::max(NumNegativeBits,
14706                                  (unsigned)InitVal.getMinSignedBits());
14707
14708     // Keep track of whether every enum element has type int (very commmon).
14709     if (AllElementsInt)
14710       AllElementsInt = ECD->getType() == Context.IntTy;
14711   }
14712
14713   // Figure out the type that should be used for this enum.
14714   QualType BestType;
14715   unsigned BestWidth;
14716
14717   // C++0x N3000 [conv.prom]p3:
14718   //   An rvalue of an unscoped enumeration type whose underlying
14719   //   type is not fixed can be converted to an rvalue of the first
14720   //   of the following types that can represent all the values of
14721   //   the enumeration: int, unsigned int, long int, unsigned long
14722   //   int, long long int, or unsigned long long int.
14723   // C99 6.4.4.3p2:
14724   //   An identifier declared as an enumeration constant has type int.
14725   // The C99 rule is modified by a gcc extension
14726   QualType BestPromotionType;
14727
14728   bool Packed = Enum->hasAttr<PackedAttr>();
14729   // -fshort-enums is the equivalent to specifying the packed attribute on all
14730   // enum definitions.
14731   if (LangOpts.ShortEnums)
14732     Packed = true;
14733
14734   if (Enum->isFixed()) {
14735     BestType = Enum->getIntegerType();
14736     if (BestType->isPromotableIntegerType())
14737       BestPromotionType = Context.getPromotedIntegerType(BestType);
14738     else
14739       BestPromotionType = BestType;
14740
14741     BestWidth = Context.getIntWidth(BestType);
14742   }
14743   else if (NumNegativeBits) {
14744     // If there is a negative value, figure out the smallest integer type (of
14745     // int/long/longlong) that fits.
14746     // If it's packed, check also if it fits a char or a short.
14747     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14748       BestType = Context.SignedCharTy;
14749       BestWidth = CharWidth;
14750     } else if (Packed && NumNegativeBits <= ShortWidth &&
14751                NumPositiveBits < ShortWidth) {
14752       BestType = Context.ShortTy;
14753       BestWidth = ShortWidth;
14754     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14755       BestType = Context.IntTy;
14756       BestWidth = IntWidth;
14757     } else {
14758       BestWidth = Context.getTargetInfo().getLongWidth();
14759
14760       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14761         BestType = Context.LongTy;
14762       } else {
14763         BestWidth = Context.getTargetInfo().getLongLongWidth();
14764
14765         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14766           Diag(Enum->getLocation(), diag::ext_enum_too_large);
14767         BestType = Context.LongLongTy;
14768       }
14769     }
14770     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14771   } else {
14772     // If there is no negative value, figure out the smallest type that fits
14773     // all of the enumerator values.
14774     // If it's packed, check also if it fits a char or a short.
14775     if (Packed && NumPositiveBits <= CharWidth) {
14776       BestType = Context.UnsignedCharTy;
14777       BestPromotionType = Context.IntTy;
14778       BestWidth = CharWidth;
14779     } else if (Packed && NumPositiveBits <= ShortWidth) {
14780       BestType = Context.UnsignedShortTy;
14781       BestPromotionType = Context.IntTy;
14782       BestWidth = ShortWidth;
14783     } else if (NumPositiveBits <= IntWidth) {
14784       BestType = Context.UnsignedIntTy;
14785       BestWidth = IntWidth;
14786       BestPromotionType
14787         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14788                            ? Context.UnsignedIntTy : Context.IntTy;
14789     } else if (NumPositiveBits <=
14790                (BestWidth = Context.getTargetInfo().getLongWidth())) {
14791       BestType = Context.UnsignedLongTy;
14792       BestPromotionType
14793         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14794                            ? Context.UnsignedLongTy : Context.LongTy;
14795     } else {
14796       BestWidth = Context.getTargetInfo().getLongLongWidth();
14797       assert(NumPositiveBits <= BestWidth &&
14798              "How could an initializer get larger than ULL?");
14799       BestType = Context.UnsignedLongLongTy;
14800       BestPromotionType
14801         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14802                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
14803     }
14804   }
14805
14806   // Loop over all of the enumerator constants, changing their types to match
14807   // the type of the enum if needed.
14808   for (auto *D : Elements) {
14809     auto *ECD = cast_or_null<EnumConstantDecl>(D);
14810     if (!ECD) continue;  // Already issued a diagnostic.
14811
14812     // Standard C says the enumerators have int type, but we allow, as an
14813     // extension, the enumerators to be larger than int size.  If each
14814     // enumerator value fits in an int, type it as an int, otherwise type it the
14815     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
14816     // that X has type 'int', not 'unsigned'.
14817
14818     // Determine whether the value fits into an int.
14819     llvm::APSInt InitVal = ECD->getInitVal();
14820
14821     // If it fits into an integer type, force it.  Otherwise force it to match
14822     // the enum decl type.
14823     QualType NewTy;
14824     unsigned NewWidth;
14825     bool NewSign;
14826     if (!getLangOpts().CPlusPlus &&
14827         !Enum->isFixed() &&
14828         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14829       NewTy = Context.IntTy;
14830       NewWidth = IntWidth;
14831       NewSign = true;
14832     } else if (ECD->getType() == BestType) {
14833       // Already the right type!
14834       if (getLangOpts().CPlusPlus)
14835         // C++ [dcl.enum]p4: Following the closing brace of an
14836         // enum-specifier, each enumerator has the type of its
14837         // enumeration.
14838         ECD->setType(EnumType);
14839       continue;
14840     } else {
14841       NewTy = BestType;
14842       NewWidth = BestWidth;
14843       NewSign = BestType->isSignedIntegerOrEnumerationType();
14844     }
14845
14846     // Adjust the APSInt value.
14847     InitVal = InitVal.extOrTrunc(NewWidth);
14848     InitVal.setIsSigned(NewSign);
14849     ECD->setInitVal(InitVal);
14850
14851     // Adjust the Expr initializer and type.
14852     if (ECD->getInitExpr() &&
14853         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14854       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14855                                                 CK_IntegralCast,
14856                                                 ECD->getInitExpr(),
14857                                                 /*base paths*/ nullptr,
14858                                                 VK_RValue));
14859     if (getLangOpts().CPlusPlus)
14860       // C++ [dcl.enum]p4: Following the closing brace of an
14861       // enum-specifier, each enumerator has the type of its
14862       // enumeration.
14863       ECD->setType(EnumType);
14864     else
14865       ECD->setType(NewTy);
14866   }
14867
14868   Enum->completeDefinition(BestType, BestPromotionType,
14869                            NumPositiveBits, NumNegativeBits);
14870
14871   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14872
14873   if (Enum->hasAttr<FlagEnumAttr>()) {
14874     for (Decl *D : Elements) {
14875       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14876       if (!ECD) continue;  // Already issued a diagnostic.
14877
14878       llvm::APSInt InitVal = ECD->getInitVal();
14879       if (InitVal != 0 && !InitVal.isPowerOf2() &&
14880           !IsValueInFlagEnum(Enum, InitVal, true))
14881         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14882           << ECD << Enum;
14883     }
14884   }
14885
14886   // Now that the enum type is defined, ensure it's not been underaligned.
14887   if (Enum->hasAttrs())
14888     CheckAlignasUnderalignment(Enum);
14889 }
14890
14891 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
14892                                   SourceLocation StartLoc,
14893                                   SourceLocation EndLoc) {
14894   StringLiteral *AsmString = cast<StringLiteral>(expr);
14895
14896   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
14897                                                    AsmString, StartLoc,
14898                                                    EndLoc);
14899   CurContext->addDecl(New);
14900   return New;
14901 }
14902
14903 static void checkModuleImportContext(Sema &S, Module *M,
14904                                      SourceLocation ImportLoc, DeclContext *DC,
14905                                      bool FromInclude = false) {
14906   SourceLocation ExternCLoc;
14907
14908   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14909     switch (LSD->getLanguage()) {
14910     case LinkageSpecDecl::lang_c:
14911       if (ExternCLoc.isInvalid())
14912         ExternCLoc = LSD->getLocStart();
14913       break;
14914     case LinkageSpecDecl::lang_cxx:
14915       break;
14916     }
14917     DC = LSD->getParent();
14918   }
14919
14920   while (isa<LinkageSpecDecl>(DC))
14921     DC = DC->getParent();
14922
14923   if (!isa<TranslationUnitDecl>(DC)) {
14924     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
14925                           ? diag::ext_module_import_not_at_top_level_noop
14926                           : diag::err_module_import_not_at_top_level_fatal)
14927         << M->getFullModuleName() << DC;
14928     S.Diag(cast<Decl>(DC)->getLocStart(),
14929            diag::note_module_import_not_at_top_level) << DC;
14930   } else if (!M->IsExternC && ExternCLoc.isValid()) {
14931     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
14932       << M->getFullModuleName();
14933     S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
14934   }
14935 }
14936
14937 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
14938   return checkModuleImportContext(*this, M, ImportLoc, CurContext);
14939 }
14940
14941 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
14942                                    SourceLocation ImportLoc,
14943                                    ModuleIdPath Path) {
14944   Module *Mod =
14945       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
14946                                    /*IsIncludeDirective=*/false);
14947   if (!Mod)
14948     return true;
14949
14950   VisibleModules.setVisible(Mod, ImportLoc);
14951
14952   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
14953
14954   // FIXME: we should support importing a submodule within a different submodule
14955   // of the same top-level module. Until we do, make it an error rather than
14956   // silently ignoring the import.
14957   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
14958     Diag(ImportLoc, getLangOpts().CompilingModule
14959                         ? diag::err_module_self_import
14960                         : diag::err_module_import_in_implementation)
14961         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
14962
14963   SmallVector<SourceLocation, 2> IdentifierLocs;
14964   Module *ModCheck = Mod;
14965   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
14966     // If we've run out of module parents, just drop the remaining identifiers.
14967     // We need the length to be consistent.
14968     if (!ModCheck)
14969       break;
14970     ModCheck = ModCheck->Parent;
14971
14972     IdentifierLocs.push_back(Path[I].second);
14973   }
14974
14975   ImportDecl *Import = ImportDecl::Create(Context,
14976                                           Context.getTranslationUnitDecl(),
14977                                           AtLoc.isValid()? AtLoc : ImportLoc,
14978                                           Mod, IdentifierLocs);
14979   Context.getTranslationUnitDecl()->addDecl(Import);
14980   return Import;
14981 }
14982
14983 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
14984   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
14985
14986   // Determine whether we're in the #include buffer for a module. The #includes
14987   // in that buffer do not qualify as module imports; they're just an
14988   // implementation detail of us building the module.
14989   //
14990   // FIXME: Should we even get ActOnModuleInclude calls for those?
14991   bool IsInModuleIncludes =
14992       TUKind == TU_Module &&
14993       getSourceManager().isWrittenInMainFile(DirectiveLoc);
14994
14995   // Similarly, if we're in the implementation of a module, don't
14996   // synthesize an illegal module import. FIXME: Why not?
14997   bool ShouldAddImport =
14998       !IsInModuleIncludes &&
14999       (getLangOpts().CompilingModule ||
15000        getLangOpts().CurrentModule.empty() ||
15001        getLangOpts().CurrentModule != Mod->getTopLevelModuleName());
15002
15003   // If this module import was due to an inclusion directive, create an
15004   // implicit import declaration to capture it in the AST.
15005   if (ShouldAddImport) {
15006     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15007     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15008                                                      DirectiveLoc, Mod,
15009                                                      DirectiveLoc);
15010     TU->addDecl(ImportD);
15011     Consumer.HandleImplicitImportDecl(ImportD);
15012   }
15013
15014   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15015   VisibleModules.setVisible(Mod, DirectiveLoc);
15016 }
15017
15018 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15019   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15020
15021   if (getLangOpts().ModulesLocalVisibility)
15022     VisibleModulesStack.push_back(std::move(VisibleModules));
15023   VisibleModules.setVisible(Mod, DirectiveLoc);
15024 }
15025
15026 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
15027   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15028
15029   if (getLangOpts().ModulesLocalVisibility) {
15030     VisibleModules = std::move(VisibleModulesStack.back());
15031     VisibleModulesStack.pop_back();
15032     VisibleModules.setVisible(Mod, DirectiveLoc);
15033     // Leaving a module hides namespace names, so our visible namespace cache
15034     // is now out of date.
15035     VisibleNamespaceCache.clear();
15036   }
15037 }
15038
15039 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15040                                                       Module *Mod) {
15041   // Bail if we're not allowed to implicitly import a module here.
15042   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15043     return;
15044
15045   // Create the implicit import declaration.
15046   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15047   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15048                                                    Loc, Mod, Loc);
15049   TU->addDecl(ImportD);
15050   Consumer.HandleImplicitImportDecl(ImportD);
15051
15052   // Make the module visible.
15053   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15054   VisibleModules.setVisible(Mod, Loc);
15055 }
15056
15057 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15058                                       IdentifierInfo* AliasName,
15059                                       SourceLocation PragmaLoc,
15060                                       SourceLocation NameLoc,
15061                                       SourceLocation AliasNameLoc) {
15062   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15063                                          LookupOrdinaryName);
15064   AsmLabelAttr *Attr =
15065       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15066
15067   // If a declaration that:
15068   // 1) declares a function or a variable
15069   // 2) has external linkage
15070   // already exists, add a label attribute to it.
15071   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15072     if (isDeclExternC(PrevDecl))
15073       PrevDecl->addAttr(Attr);
15074     else
15075       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15076           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15077   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15078   } else
15079     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15080 }
15081
15082 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15083                              SourceLocation PragmaLoc,
15084                              SourceLocation NameLoc) {
15085   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15086
15087   if (PrevDecl) {
15088     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15089   } else {
15090     (void)WeakUndeclaredIdentifiers.insert(
15091       std::pair<IdentifierInfo*,WeakInfo>
15092         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15093   }
15094 }
15095
15096 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15097                                 IdentifierInfo* AliasName,
15098                                 SourceLocation PragmaLoc,
15099                                 SourceLocation NameLoc,
15100                                 SourceLocation AliasNameLoc) {
15101   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15102                                     LookupOrdinaryName);
15103   WeakInfo W = WeakInfo(Name, NameLoc);
15104
15105   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15106     if (!PrevDecl->hasAttr<AliasAttr>())
15107       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15108         DeclApplyPragmaWeak(TUScope, ND, W);
15109   } else {
15110     (void)WeakUndeclaredIdentifiers.insert(
15111       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15112   }
15113 }
15114
15115 Decl *Sema::getObjCDeclContext() const {
15116   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15117 }
15118
15119 AvailabilityResult Sema::getCurContextAvailability() const {
15120   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
15121   if (!D)
15122     return AR_Available;
15123
15124   // If we are within an Objective-C method, we should consult
15125   // both the availability of the method as well as the
15126   // enclosing class.  If the class is (say) deprecated,
15127   // the entire method is considered deprecated from the
15128   // purpose of checking if the current context is deprecated.
15129   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
15130     AvailabilityResult R = MD->getAvailability();
15131     if (R != AR_Available)
15132       return R;
15133     D = MD->getClassInterface();
15134   }
15135   // If we are within an Objective-c @implementation, it
15136   // gets the same availability context as the @interface.
15137   else if (const ObjCImplementationDecl *ID =
15138             dyn_cast<ObjCImplementationDecl>(D)) {
15139     D = ID->getClassInterface();
15140   }
15141   // Recover from user error.
15142   return D ? D->getAvailability() : AR_Available;
15143 }