]> granicus.if.org Git - clang/blob - lib/Sema/SemaDecl.cpp
6a61ac0e44ce0de55052d5314f8975c89144d922
[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 using namespace clang;
51 using namespace sema;
52
53 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
54   if (OwnedType) {
55     Decl *Group[2] = { OwnedType, Ptr };
56     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
57   }
58
59   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
60 }
61
62 namespace {
63
64 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
65  public:
66   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
67                        bool AllowTemplates=false)
68       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
69         AllowClassTemplates(AllowTemplates) {
70     WantExpressionKeywords = false;
71     WantCXXNamedCasts = false;
72     WantRemainingKeywords = false;
73   }
74
75   bool ValidateCandidate(const TypoCorrection &candidate) override {
76     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
77       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
78       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
79       return (IsType || AllowedTemplate) &&
80              (AllowInvalidDecl || !ND->isInvalidDecl());
81     }
82     return !WantClassName && candidate.isKeyword();
83   }
84
85  private:
86   bool AllowInvalidDecl;
87   bool WantClassName;
88   bool AllowClassTemplates;
89 };
90
91 }
92
93 /// \brief Determine whether the token kind starts a simple-type-specifier.
94 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
95   switch (Kind) {
96   // FIXME: Take into account the current language when deciding whether a
97   // token kind is a valid type specifier
98   case tok::kw_short:
99   case tok::kw_long:
100   case tok::kw___int64:
101   case tok::kw___int128:
102   case tok::kw_signed:
103   case tok::kw_unsigned:
104   case tok::kw_void:
105   case tok::kw_char:
106   case tok::kw_int:
107   case tok::kw_half:
108   case tok::kw_float:
109   case tok::kw_double:
110   case tok::kw_wchar_t:
111   case tok::kw_bool:
112   case tok::kw___underlying_type:
113   case tok::kw___auto_type:
114     return true;
115
116   case tok::annot_typename:
117   case tok::kw_char16_t:
118   case tok::kw_char32_t:
119   case tok::kw_typeof:
120   case tok::annot_decltype:
121   case tok::kw_decltype:
122     return getLangOpts().CPlusPlus;
123
124   default:
125     break;
126   }
127
128   return false;
129 }
130
131 namespace {
132 enum class UnqualifiedTypeNameLookupResult {
133   NotFound,
134   FoundNonType,
135   FoundType
136 };
137 } // namespace
138
139 /// \brief Tries to perform unqualified lookup of the type decls in bases for
140 /// dependent class.
141 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
142 /// type decl, \a FoundType if only type decls are found.
143 static UnqualifiedTypeNameLookupResult
144 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
145                                 SourceLocation NameLoc,
146                                 const CXXRecordDecl *RD) {
147   if (!RD->hasDefinition())
148     return UnqualifiedTypeNameLookupResult::NotFound;
149   // Look for type decls in base classes.
150   UnqualifiedTypeNameLookupResult FoundTypeDecl =
151       UnqualifiedTypeNameLookupResult::NotFound;
152   for (const auto &Base : RD->bases()) {
153     const CXXRecordDecl *BaseRD = nullptr;
154     if (auto *BaseTT = Base.getType()->getAs<TagType>())
155       BaseRD = BaseTT->getAsCXXRecordDecl();
156     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
157       // Look for type decls in dependent base classes that have known primary
158       // templates.
159       if (!TST || !TST->isDependentType())
160         continue;
161       auto *TD = TST->getTemplateName().getAsTemplateDecl();
162       if (!TD)
163         continue;
164       auto *BasePrimaryTemplate =
165           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
166       if (!BasePrimaryTemplate)
167         continue;
168       BaseRD = BasePrimaryTemplate;
169     }
170     if (BaseRD) {
171       for (NamedDecl *ND : BaseRD->lookup(&II)) {
172         if (!isa<TypeDecl>(ND))
173           return UnqualifiedTypeNameLookupResult::FoundNonType;
174         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
175       }
176       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
177         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
178         case UnqualifiedTypeNameLookupResult::FoundNonType:
179           return UnqualifiedTypeNameLookupResult::FoundNonType;
180         case UnqualifiedTypeNameLookupResult::FoundType:
181           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
182           break;
183         case UnqualifiedTypeNameLookupResult::NotFound:
184           break;
185         }
186       }
187     }
188   }
189
190   return FoundTypeDecl;
191 }
192
193 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
194                                                       const IdentifierInfo &II,
195                                                       SourceLocation NameLoc) {
196   // Lookup in the parent class template context, if any.
197   const CXXRecordDecl *RD = nullptr;
198   UnqualifiedTypeNameLookupResult FoundTypeDecl =
199       UnqualifiedTypeNameLookupResult::NotFound;
200   for (DeclContext *DC = S.CurContext;
201        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
202        DC = DC->getParent()) {
203     // Look for type decls in dependent base classes that have known primary
204     // templates.
205     RD = dyn_cast<CXXRecordDecl>(DC);
206     if (RD && RD->getDescribedClassTemplate())
207       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
208   }
209   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
210     return ParsedType();
211
212   // We found some types in dependent base classes.  Recover as if the user
213   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
214   // lookup during template instantiation.
215   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
216
217   ASTContext &Context = S.Context;
218   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
219                                           cast<Type>(Context.getRecordType(RD)));
220   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
221
222   CXXScopeSpec SS;
223   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
224
225   TypeLocBuilder Builder;
226   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
227   DepTL.setNameLoc(NameLoc);
228   DepTL.setElaboratedKeywordLoc(SourceLocation());
229   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
230   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
231 }
232
233 /// \brief If the identifier refers to a type name within this scope,
234 /// return the declaration of that type.
235 ///
236 /// This routine performs ordinary name lookup of the identifier II
237 /// within the given scope, with optional C++ scope specifier SS, to
238 /// determine whether the name refers to a type. If so, returns an
239 /// opaque pointer (actually a QualType) corresponding to that
240 /// type. Otherwise, returns NULL.
241 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
242                              Scope *S, CXXScopeSpec *SS,
243                              bool isClassName, bool HasTrailingDot,
244                              ParsedType ObjectTypePtr,
245                              bool IsCtorOrDtorName,
246                              bool WantNontrivialTypeSourceInfo,
247                              IdentifierInfo **CorrectedII) {
248   // Determine where we will perform name lookup.
249   DeclContext *LookupCtx = nullptr;
250   if (ObjectTypePtr) {
251     QualType ObjectType = ObjectTypePtr.get();
252     if (ObjectType->isRecordType())
253       LookupCtx = computeDeclContext(ObjectType);
254   } else if (SS && SS->isNotEmpty()) {
255     LookupCtx = computeDeclContext(*SS, false);
256
257     if (!LookupCtx) {
258       if (isDependentScopeSpecifier(*SS)) {
259         // C++ [temp.res]p3:
260         //   A qualified-id that refers to a type and in which the
261         //   nested-name-specifier depends on a template-parameter (14.6.2)
262         //   shall be prefixed by the keyword typename to indicate that the
263         //   qualified-id denotes a type, forming an
264         //   elaborated-type-specifier (7.1.5.3).
265         //
266         // We therefore do not perform any name lookup if the result would
267         // refer to a member of an unknown specialization.
268         if (!isClassName && !IsCtorOrDtorName)
269           return ParsedType();
270         
271         // We know from the grammar that this name refers to a type,
272         // so build a dependent node to describe the type.
273         if (WantNontrivialTypeSourceInfo)
274           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
275         
276         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
277         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
278                                        II, NameLoc);
279         return ParsedType::make(T);
280       }
281       
282       return ParsedType();
283     }
284     
285     if (!LookupCtx->isDependentContext() &&
286         RequireCompleteDeclContext(*SS, LookupCtx))
287       return ParsedType();
288   }
289
290   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
291   // lookup for class-names.
292   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
293                                       LookupOrdinaryName;
294   LookupResult Result(*this, &II, NameLoc, Kind);
295   if (LookupCtx) {
296     // Perform "qualified" name lookup into the declaration context we
297     // computed, which is either the type of the base of a member access
298     // expression or the declaration context associated with a prior
299     // nested-name-specifier.
300     LookupQualifiedName(Result, LookupCtx);
301
302     if (ObjectTypePtr && Result.empty()) {
303       // C++ [basic.lookup.classref]p3:
304       //   If the unqualified-id is ~type-name, the type-name is looked up
305       //   in the context of the entire postfix-expression. If the type T of 
306       //   the object expression is of a class type C, the type-name is also
307       //   looked up in the scope of class C. At least one of the lookups shall
308       //   find a name that refers to (possibly cv-qualified) T.
309       LookupName(Result, S);
310     }
311   } else {
312     // Perform unqualified name lookup.
313     LookupName(Result, S);
314
315     // For unqualified lookup in a class template in MSVC mode, look into
316     // dependent base classes where the primary class template is known.
317     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
318       if (ParsedType TypeInBase =
319               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
320         return TypeInBase;
321     }
322   }
323
324   NamedDecl *IIDecl = nullptr;
325   switch (Result.getResultKind()) {
326   case LookupResult::NotFound:
327   case LookupResult::NotFoundInCurrentInstantiation:
328     if (CorrectedII) {
329       TypoCorrection Correction = CorrectTypo(
330           Result.getLookupNameInfo(), Kind, S, SS,
331           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
332           CTK_ErrorRecovery);
333       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
334       TemplateTy Template;
335       bool MemberOfUnknownSpecialization;
336       UnqualifiedId TemplateName;
337       TemplateName.setIdentifier(NewII, NameLoc);
338       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
339       CXXScopeSpec NewSS, *NewSSPtr = SS;
340       if (SS && NNS) {
341         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
342         NewSSPtr = &NewSS;
343       }
344       if (Correction && (NNS || NewII != &II) &&
345           // Ignore a correction to a template type as the to-be-corrected
346           // identifier is not a template (typo correction for template names
347           // is handled elsewhere).
348           !(getLangOpts().CPlusPlus && NewSSPtr &&
349             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
350                            false, Template, MemberOfUnknownSpecialization))) {
351         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
352                                     isClassName, HasTrailingDot, ObjectTypePtr,
353                                     IsCtorOrDtorName,
354                                     WantNontrivialTypeSourceInfo);
355         if (Ty) {
356           diagnoseTypo(Correction,
357                        PDiag(diag::err_unknown_type_or_class_name_suggest)
358                          << Result.getLookupName() << isClassName);
359           if (SS && NNS)
360             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
361           *CorrectedII = NewII;
362           return Ty;
363         }
364       }
365     }
366     // If typo correction failed or was not performed, fall through
367   case LookupResult::FoundOverloaded:
368   case LookupResult::FoundUnresolvedValue:
369     Result.suppressDiagnostics();
370     return ParsedType();
371
372   case LookupResult::Ambiguous:
373     // Recover from type-hiding ambiguities by hiding the type.  We'll
374     // do the lookup again when looking for an object, and we can
375     // diagnose the error then.  If we don't do this, then the error
376     // about hiding the type will be immediately followed by an error
377     // that only makes sense if the identifier was treated like a type.
378     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
379       Result.suppressDiagnostics();
380       return ParsedType();
381     }
382
383     // Look to see if we have a type anywhere in the list of results.
384     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
385          Res != ResEnd; ++Res) {
386       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
387         if (!IIDecl ||
388             (*Res)->getLocation().getRawEncoding() <
389               IIDecl->getLocation().getRawEncoding())
390           IIDecl = *Res;
391       }
392     }
393
394     if (!IIDecl) {
395       // None of the entities we found is a type, so there is no way
396       // to even assume that the result is a type. In this case, don't
397       // complain about the ambiguity. The parser will either try to
398       // perform this lookup again (e.g., as an object name), which
399       // will produce the ambiguity, or will complain that it expected
400       // a type name.
401       Result.suppressDiagnostics();
402       return ParsedType();
403     }
404
405     // We found a type within the ambiguous lookup; diagnose the
406     // ambiguity and then return that type. This might be the right
407     // answer, or it might not be, but it suppresses any attempt to
408     // perform the name lookup again.
409     break;
410
411   case LookupResult::Found:
412     IIDecl = Result.getFoundDecl();
413     break;
414   }
415
416   assert(IIDecl && "Didn't find decl");
417
418   QualType T;
419   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
420     DiagnoseUseOfDecl(IIDecl, NameLoc);
421
422     T = Context.getTypeDeclType(TD);
423     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
424
425     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
426     // constructor or destructor name (in such a case, the scope specifier
427     // will be attached to the enclosing Expr or Decl node).
428     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
429       if (WantNontrivialTypeSourceInfo) {
430         // Construct a type with type-source information.
431         TypeLocBuilder Builder;
432         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
433         
434         T = getElaboratedType(ETK_None, *SS, T);
435         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
436         ElabTL.setElaboratedKeywordLoc(SourceLocation());
437         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
438         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
439       } else {
440         T = getElaboratedType(ETK_None, *SS, T);
441       }
442     }
443   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
444     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
445     if (!HasTrailingDot)
446       T = Context.getObjCInterfaceType(IDecl);
447   }
448
449   if (T.isNull()) {
450     // If it's not plausibly a type, suppress diagnostics.
451     Result.suppressDiagnostics();
452     return ParsedType();
453   }
454   return ParsedType::make(T);
455 }
456
457 // Builds a fake NNS for the given decl context.
458 static NestedNameSpecifier *
459 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
460   for (;; DC = DC->getLookupParent()) {
461     DC = DC->getPrimaryContext();
462     auto *ND = dyn_cast<NamespaceDecl>(DC);
463     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
464       return NestedNameSpecifier::Create(Context, nullptr, ND);
465     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
466       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
467                                          RD->getTypeForDecl());
468     else if (isa<TranslationUnitDecl>(DC))
469       return NestedNameSpecifier::GlobalSpecifier(Context);
470   }
471   llvm_unreachable("something isn't in TU scope?");
472 }
473
474 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
475                                                 SourceLocation NameLoc) {
476   // Accepting an undeclared identifier as a default argument for a template
477   // type parameter is a Microsoft extension.
478   Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
479
480   // Build a fake DependentNameType that will perform lookup into CurContext at
481   // instantiation time.  The name specifier isn't dependent, so template
482   // instantiation won't transform it.  It will retry the lookup, however.
483   NestedNameSpecifier *NNS =
484       synthesizeCurrentNestedNameSpecifier(Context, CurContext);
485   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
486
487   // Build type location information.  We synthesized the qualifier, so we have
488   // to build a fake NestedNameSpecifierLoc.
489   NestedNameSpecifierLocBuilder NNSLocBuilder;
490   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
491   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
492
493   TypeLocBuilder Builder;
494   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
495   DepTL.setNameLoc(NameLoc);
496   DepTL.setElaboratedKeywordLoc(SourceLocation());
497   DepTL.setQualifierLoc(QualifierLoc);
498   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
499 }
500
501 /// isTagName() - This method is called *for error recovery purposes only*
502 /// to determine if the specified name is a valid tag name ("struct foo").  If
503 /// so, this returns the TST for the tag corresponding to it (TST_enum,
504 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
505 /// cases in C where the user forgot to specify the tag.
506 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
507   // Do a tag name lookup in this scope.
508   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
509   LookupName(R, S, false);
510   R.suppressDiagnostics();
511   if (R.getResultKind() == LookupResult::Found)
512     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
513       switch (TD->getTagKind()) {
514       case TTK_Struct: return DeclSpec::TST_struct;
515       case TTK_Interface: return DeclSpec::TST_interface;
516       case TTK_Union:  return DeclSpec::TST_union;
517       case TTK_Class:  return DeclSpec::TST_class;
518       case TTK_Enum:   return DeclSpec::TST_enum;
519       }
520     }
521
522   return DeclSpec::TST_unspecified;
523 }
524
525 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
526 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
527 /// then downgrade the missing typename error to a warning.
528 /// This is needed for MSVC compatibility; Example:
529 /// @code
530 /// template<class T> class A {
531 /// public:
532 ///   typedef int TYPE;
533 /// };
534 /// template<class T> class B : public A<T> {
535 /// public:
536 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
537 /// };
538 /// @endcode
539 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
540   if (CurContext->isRecord()) {
541     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
542       return true;
543
544     const Type *Ty = SS->getScopeRep()->getAsType();
545
546     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
547     for (const auto &Base : RD->bases())
548       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
549         return true;
550     return S->isFunctionPrototypeScope();
551   } 
552   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
553 }
554
555 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
556                                    SourceLocation IILoc,
557                                    Scope *S,
558                                    CXXScopeSpec *SS,
559                                    ParsedType &SuggestedType,
560                                    bool AllowClassTemplates) {
561   // We don't have anything to suggest (yet).
562   SuggestedType = ParsedType();
563   
564   // There may have been a typo in the name of the type. Look up typo
565   // results, in case we have something that we can suggest.
566   if (TypoCorrection Corrected =
567           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
568                       llvm::make_unique<TypeNameValidatorCCC>(
569                           false, false, AllowClassTemplates),
570                       CTK_ErrorRecovery)) {
571     if (Corrected.isKeyword()) {
572       // We corrected to a keyword.
573       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
574       II = Corrected.getCorrectionAsIdentifierInfo();
575     } else {
576       // We found a similarly-named type or interface; suggest that.
577       if (!SS || !SS->isSet()) {
578         diagnoseTypo(Corrected,
579                      PDiag(diag::err_unknown_typename_suggest) << II);
580       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
581         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
582         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
583                                 II->getName().equals(CorrectedStr);
584         diagnoseTypo(Corrected,
585                      PDiag(diag::err_unknown_nested_typename_suggest)
586                        << II << DC << DroppedSpecifier << SS->getRange());
587       } else {
588         llvm_unreachable("could not have corrected a typo here");
589       }
590
591       CXXScopeSpec tmpSS;
592       if (Corrected.getCorrectionSpecifier())
593         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
594                           SourceRange(IILoc));
595       SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
596                                   IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
597                                   false, ParsedType(),
598                                   /*IsCtorOrDtorName=*/false,
599                                   /*NonTrivialTypeSourceInfo=*/true);
600     }
601     return;
602   }
603
604   if (getLangOpts().CPlusPlus) {
605     // See if II is a class template that the user forgot to pass arguments to.
606     UnqualifiedId Name;
607     Name.setIdentifier(II, IILoc);
608     CXXScopeSpec EmptySS;
609     TemplateTy TemplateResult;
610     bool MemberOfUnknownSpecialization;
611     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
612                        Name, ParsedType(), true, TemplateResult,
613                        MemberOfUnknownSpecialization) == TNK_Type_template) {
614       TemplateName TplName = TemplateResult.get();
615       Diag(IILoc, diag::err_template_missing_args) << TplName;
616       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
617         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
618           << TplDecl->getTemplateParameters()->getSourceRange();
619       }
620       return;
621     }
622   }
623
624   // FIXME: Should we move the logic that tries to recover from a missing tag
625   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
626   
627   if (!SS || (!SS->isSet() && !SS->isInvalid()))
628     Diag(IILoc, diag::err_unknown_typename) << II;
629   else if (DeclContext *DC = computeDeclContext(*SS, false))
630     Diag(IILoc, diag::err_typename_nested_not_found) 
631       << II << DC << SS->getRange();
632   else if (isDependentScopeSpecifier(*SS)) {
633     unsigned DiagID = diag::err_typename_missing;
634     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
635       DiagID = diag::ext_typename_missing;
636
637     Diag(SS->getRange().getBegin(), DiagID)
638       << SS->getScopeRep() << II->getName()
639       << SourceRange(SS->getRange().getBegin(), IILoc)
640       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
641     SuggestedType = ActOnTypenameType(S, SourceLocation(),
642                                       *SS, *II, IILoc).get();
643   } else {
644     assert(SS && SS->isInvalid() && 
645            "Invalid scope specifier has already been diagnosed");
646   }
647 }
648
649 /// \brief Determine whether the given result set contains either a type name
650 /// or 
651 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
652   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
653                        NextToken.is(tok::less);
654   
655   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
656     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
657       return true;
658     
659     if (CheckTemplate && isa<TemplateDecl>(*I))
660       return true;
661   }
662   
663   return false;
664 }
665
666 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
667                                     Scope *S, CXXScopeSpec &SS,
668                                     IdentifierInfo *&Name,
669                                     SourceLocation NameLoc) {
670   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
671   SemaRef.LookupParsedName(R, S, &SS);
672   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
673     StringRef FixItTagName;
674     switch (Tag->getTagKind()) {
675       case TTK_Class:
676         FixItTagName = "class ";
677         break;
678
679       case TTK_Enum:
680         FixItTagName = "enum ";
681         break;
682
683       case TTK_Struct:
684         FixItTagName = "struct ";
685         break;
686
687       case TTK_Interface:
688         FixItTagName = "__interface ";
689         break;
690
691       case TTK_Union:
692         FixItTagName = "union ";
693         break;
694     }
695
696     StringRef TagName = FixItTagName.drop_back();
697     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
698       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
699       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
700
701     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
702          I != IEnd; ++I)
703       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
704         << Name << TagName;
705
706     // Replace lookup results with just the tag decl.
707     Result.clear(Sema::LookupTagName);
708     SemaRef.LookupParsedName(Result, S, &SS);
709     return true;
710   }
711
712   return false;
713 }
714
715 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
716 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
717                                   QualType T, SourceLocation NameLoc) {
718   ASTContext &Context = S.Context;
719
720   TypeLocBuilder Builder;
721   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
722
723   T = S.getElaboratedType(ETK_None, SS, T);
724   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
725   ElabTL.setElaboratedKeywordLoc(SourceLocation());
726   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
727   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
728 }
729
730 Sema::NameClassification
731 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
732                    SourceLocation NameLoc, const Token &NextToken,
733                    bool IsAddressOfOperand,
734                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
735   DeclarationNameInfo NameInfo(Name, NameLoc);
736   ObjCMethodDecl *CurMethod = getCurMethodDecl();
737
738   if (NextToken.is(tok::coloncolon)) {
739     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
740                                 QualType(), false, SS, nullptr, false);
741   }
742
743   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
744   LookupParsedName(Result, S, &SS, !CurMethod);
745
746   // For unqualified lookup in a class template in MSVC mode, look into
747   // dependent base classes where the primary class template is known.
748   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
749     if (ParsedType TypeInBase =
750             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
751       return TypeInBase;
752   }
753
754   // Perform lookup for Objective-C instance variables (including automatically 
755   // synthesized instance variables), if we're in an Objective-C method.
756   // FIXME: This lookup really, really needs to be folded in to the normal
757   // unqualified lookup mechanism.
758   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
759     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
760     if (E.get() || E.isInvalid())
761       return E;
762   }
763   
764   bool SecondTry = false;
765   bool IsFilteredTemplateName = false;
766   
767 Corrected:
768   switch (Result.getResultKind()) {
769   case LookupResult::NotFound:
770     // If an unqualified-id is followed by a '(', then we have a function
771     // call.
772     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
773       // In C++, this is an ADL-only call.
774       // FIXME: Reference?
775       if (getLangOpts().CPlusPlus)
776         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
777       
778       // C90 6.3.2.2:
779       //   If the expression that precedes the parenthesized argument list in a 
780       //   function call consists solely of an identifier, and if no 
781       //   declaration is visible for this identifier, the identifier is 
782       //   implicitly declared exactly as if, in the innermost block containing
783       //   the function call, the declaration
784       //
785       //     extern int identifier (); 
786       //
787       //   appeared. 
788       // 
789       // We also allow this in C99 as an extension.
790       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
791         Result.addDecl(D);
792         Result.resolveKind();
793         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
794       }
795     }
796     
797     // In C, we first see whether there is a tag type by the same name, in 
798     // which case it's likely that the user just forget to write "enum", 
799     // "struct", or "union".
800     if (!getLangOpts().CPlusPlus && !SecondTry &&
801         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
802       break;
803     }
804
805     // Perform typo correction to determine if there is another name that is
806     // close to this name.
807     if (!SecondTry && CCC) {
808       SecondTry = true;
809       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
810                                                  Result.getLookupKind(), S, 
811                                                  &SS, std::move(CCC),
812                                                  CTK_ErrorRecovery)) {
813         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
814         unsigned QualifiedDiag = diag::err_no_member_suggest;
815
816         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
817         NamedDecl *UnderlyingFirstDecl
818           = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
819         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
820             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
821           UnqualifiedDiag = diag::err_no_template_suggest;
822           QualifiedDiag = diag::err_no_member_template_suggest;
823         } else if (UnderlyingFirstDecl && 
824                    (isa<TypeDecl>(UnderlyingFirstDecl) || 
825                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
826                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
827           UnqualifiedDiag = diag::err_unknown_typename_suggest;
828           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
829         }
830
831         if (SS.isEmpty()) {
832           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
833         } else {// FIXME: is this even reachable? Test it.
834           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
835           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
836                                   Name->getName().equals(CorrectedStr);
837           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
838                                     << Name << computeDeclContext(SS, false)
839                                     << DroppedSpecifier << SS.getRange());
840         }
841
842         // Update the name, so that the caller has the new name.
843         Name = Corrected.getCorrectionAsIdentifierInfo();
844
845         // Typo correction corrected to a keyword.
846         if (Corrected.isKeyword())
847           return Name;
848
849         // Also update the LookupResult...
850         // FIXME: This should probably go away at some point
851         Result.clear();
852         Result.setLookupName(Corrected.getCorrection());
853         if (FirstDecl)
854           Result.addDecl(FirstDecl);
855
856         // If we found an Objective-C instance variable, let
857         // LookupInObjCMethod build the appropriate expression to
858         // reference the ivar.
859         // FIXME: This is a gross hack.
860         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
861           Result.clear();
862           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
863           return E;
864         }
865         
866         goto Corrected;
867       }
868     }
869       
870     // We failed to correct; just fall through and let the parser deal with it.
871     Result.suppressDiagnostics();
872     return NameClassification::Unknown();
873       
874   case LookupResult::NotFoundInCurrentInstantiation: {
875     // We performed name lookup into the current instantiation, and there were 
876     // dependent bases, so we treat this result the same way as any other
877     // dependent nested-name-specifier.
878       
879     // C++ [temp.res]p2:
880     //   A name used in a template declaration or definition and that is 
881     //   dependent on a template-parameter is assumed not to name a type 
882     //   unless the applicable name lookup finds a type name or the name is 
883     //   qualified by the keyword typename.
884     //
885     // FIXME: If the next token is '<', we might want to ask the parser to
886     // perform some heroics to see if we actually have a 
887     // template-argument-list, which would indicate a missing 'template'
888     // keyword here.
889     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
890                                       NameInfo, IsAddressOfOperand,
891                                       /*TemplateArgs=*/nullptr);
892   }
893
894   case LookupResult::Found:
895   case LookupResult::FoundOverloaded:
896   case LookupResult::FoundUnresolvedValue:
897     break;
898       
899   case LookupResult::Ambiguous:
900     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
901         hasAnyAcceptableTemplateNames(Result)) {
902       // C++ [temp.local]p3:
903       //   A lookup that finds an injected-class-name (10.2) can result in an
904       //   ambiguity in certain cases (for example, if it is found in more than
905       //   one base class). If all of the injected-class-names that are found
906       //   refer to specializations of the same class template, and if the name
907       //   is followed by a template-argument-list, the reference refers to the
908       //   class template itself and not a specialization thereof, and is not
909       //   ambiguous.
910       //
911       // This filtering can make an ambiguous result into an unambiguous one,
912       // so try again after filtering out template names.
913       FilterAcceptableTemplateNames(Result);
914       if (!Result.isAmbiguous()) {
915         IsFilteredTemplateName = true;
916         break;
917       }
918     }
919       
920     // Diagnose the ambiguity and return an error.
921     return NameClassification::Error();
922   }
923   
924   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
925       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
926     // C++ [temp.names]p3:
927     //   After name lookup (3.4) finds that a name is a template-name or that
928     //   an operator-function-id or a literal- operator-id refers to a set of
929     //   overloaded functions any member of which is a function template if 
930     //   this is followed by a <, the < is always taken as the delimiter of a
931     //   template-argument-list and never as the less-than operator.
932     if (!IsFilteredTemplateName)
933       FilterAcceptableTemplateNames(Result);
934     
935     if (!Result.empty()) {
936       bool IsFunctionTemplate;
937       bool IsVarTemplate;
938       TemplateName Template;
939       if (Result.end() - Result.begin() > 1) {
940         IsFunctionTemplate = true;
941         Template = Context.getOverloadedTemplateName(Result.begin(), 
942                                                      Result.end());
943       } else {
944         TemplateDecl *TD
945           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
946         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
947         IsVarTemplate = isa<VarTemplateDecl>(TD);
948
949         if (SS.isSet() && !SS.isInvalid())
950           Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 
951                                                     /*TemplateKeyword=*/false,
952                                                       TD);
953         else
954           Template = TemplateName(TD);
955       }
956       
957       if (IsFunctionTemplate) {
958         // Function templates always go through overload resolution, at which
959         // point we'll perform the various checks (e.g., accessibility) we need
960         // to based on which function we selected.
961         Result.suppressDiagnostics();
962         
963         return NameClassification::FunctionTemplate(Template);
964       }
965
966       return IsVarTemplate ? NameClassification::VarTemplate(Template)
967                            : NameClassification::TypeTemplate(Template);
968     }
969   }
970
971   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
972   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
973     DiagnoseUseOfDecl(Type, NameLoc);
974     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
975     QualType T = Context.getTypeDeclType(Type);
976     if (SS.isNotEmpty())
977       return buildNestedType(*this, SS, T, NameLoc);
978     return ParsedType::make(T);
979   }
980
981   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
982   if (!Class) {
983     // FIXME: It's unfortunate that we don't have a Type node for handling this.
984     if (ObjCCompatibleAliasDecl *Alias =
985             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
986       Class = Alias->getClassInterface();
987   }
988   
989   if (Class) {
990     DiagnoseUseOfDecl(Class, NameLoc);
991     
992     if (NextToken.is(tok::period)) {
993       // Interface. <something> is parsed as a property reference expression.
994       // Just return "unknown" as a fall-through for now.
995       Result.suppressDiagnostics();
996       return NameClassification::Unknown();
997     }
998     
999     QualType T = Context.getObjCInterfaceType(Class);
1000     return ParsedType::make(T);
1001   }
1002
1003   // We can have a type template here if we're classifying a template argument.
1004   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1005     return NameClassification::TypeTemplate(
1006         TemplateName(cast<TemplateDecl>(FirstDecl)));
1007
1008   // Check for a tag type hidden by a non-type decl in a few cases where it
1009   // seems likely a type is wanted instead of the non-type that was found.
1010   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1011   if ((NextToken.is(tok::identifier) ||
1012        (NextIsOp &&
1013         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1014       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1015     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1016     DiagnoseUseOfDecl(Type, NameLoc);
1017     QualType T = Context.getTypeDeclType(Type);
1018     if (SS.isNotEmpty())
1019       return buildNestedType(*this, SS, T, NameLoc);
1020     return ParsedType::make(T);
1021   }
1022   
1023   if (FirstDecl->isCXXClassMember())
1024     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1025                                            nullptr, S);
1026
1027   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1028   return BuildDeclarationNameExpr(SS, Result, ADL);
1029 }
1030
1031 // Determines the context to return to after temporarily entering a
1032 // context.  This depends in an unnecessarily complicated way on the
1033 // exact ordering of callbacks from the parser.
1034 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1035
1036   // Functions defined inline within classes aren't parsed until we've
1037   // finished parsing the top-level class, so the top-level class is
1038   // the context we'll need to return to.
1039   // A Lambda call operator whose parent is a class must not be treated 
1040   // as an inline member function.  A Lambda can be used legally
1041   // either as an in-class member initializer or a default argument.  These
1042   // are parsed once the class has been marked complete and so the containing
1043   // context would be the nested class (when the lambda is defined in one);
1044   // If the class is not complete, then the lambda is being used in an 
1045   // ill-formed fashion (such as to specify the width of a bit-field, or
1046   // in an array-bound) - in which case we still want to return the 
1047   // lexically containing DC (which could be a nested class). 
1048   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1049     DC = DC->getLexicalParent();
1050
1051     // A function not defined within a class will always return to its
1052     // lexical context.
1053     if (!isa<CXXRecordDecl>(DC))
1054       return DC;
1055
1056     // A C++ inline method/friend is parsed *after* the topmost class
1057     // it was declared in is fully parsed ("complete");  the topmost
1058     // class is the context we need to return to.
1059     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1060       DC = RD;
1061
1062     // Return the declaration context of the topmost class the inline method is
1063     // declared in.
1064     return DC;
1065   }
1066
1067   return DC->getLexicalParent();
1068 }
1069
1070 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1071   assert(getContainingDC(DC) == CurContext &&
1072       "The next DeclContext should be lexically contained in the current one.");
1073   CurContext = DC;
1074   S->setEntity(DC);
1075 }
1076
1077 void Sema::PopDeclContext() {
1078   assert(CurContext && "DeclContext imbalance!");
1079
1080   CurContext = getContainingDC(CurContext);
1081   assert(CurContext && "Popped translation unit!");
1082 }
1083
1084 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1085                                                                     Decl *D) {
1086   // Unlike PushDeclContext, the context to which we return is not necessarily
1087   // the containing DC of TD, because the new context will be some pre-existing
1088   // TagDecl definition instead of a fresh one.
1089   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1090   CurContext = cast<TagDecl>(D)->getDefinition();
1091   assert(CurContext && "skipping definition of undefined tag");
1092   // Start lookups from the parent of the current context; we don't want to look
1093   // into the pre-existing complete definition.
1094   S->setEntity(CurContext->getLookupParent());
1095   return Result;
1096 }
1097
1098 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1099   CurContext = static_cast<decltype(CurContext)>(Context);
1100 }
1101
1102 /// EnterDeclaratorContext - Used when we must lookup names in the context
1103 /// of a declarator's nested name specifier.
1104 ///
1105 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1106   // C++0x [basic.lookup.unqual]p13:
1107   //   A name used in the definition of a static data member of class
1108   //   X (after the qualified-id of the static member) is looked up as
1109   //   if the name was used in a member function of X.
1110   // C++0x [basic.lookup.unqual]p14:
1111   //   If a variable member of a namespace is defined outside of the
1112   //   scope of its namespace then any name used in the definition of
1113   //   the variable member (after the declarator-id) is looked up as
1114   //   if the definition of the variable member occurred in its
1115   //   namespace.
1116   // Both of these imply that we should push a scope whose context
1117   // is the semantic context of the declaration.  We can't use
1118   // PushDeclContext here because that context is not necessarily
1119   // lexically contained in the current context.  Fortunately,
1120   // the containing scope should have the appropriate information.
1121
1122   assert(!S->getEntity() && "scope already has entity");
1123
1124 #ifndef NDEBUG
1125   Scope *Ancestor = S->getParent();
1126   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1127   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1128 #endif
1129
1130   CurContext = DC;
1131   S->setEntity(DC);
1132 }
1133
1134 void Sema::ExitDeclaratorContext(Scope *S) {
1135   assert(S->getEntity() == CurContext && "Context imbalance!");
1136
1137   // Switch back to the lexical context.  The safety of this is
1138   // enforced by an assert in EnterDeclaratorContext.
1139   Scope *Ancestor = S->getParent();
1140   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1141   CurContext = Ancestor->getEntity();
1142
1143   // We don't need to do anything with the scope, which is going to
1144   // disappear.
1145 }
1146
1147
1148 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1149   // We assume that the caller has already called
1150   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1151   FunctionDecl *FD = D->getAsFunction();
1152   if (!FD)
1153     return;
1154
1155   // Same implementation as PushDeclContext, but enters the context
1156   // from the lexical parent, rather than the top-level class.
1157   assert(CurContext == FD->getLexicalParent() &&
1158     "The next DeclContext should be lexically contained in the current one.");
1159   CurContext = FD;
1160   S->setEntity(CurContext);
1161
1162   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1163     ParmVarDecl *Param = FD->getParamDecl(P);
1164     // If the parameter has an identifier, then add it to the scope
1165     if (Param->getIdentifier()) {
1166       S->AddDecl(Param);
1167       IdResolver.AddDecl(Param);
1168     }
1169   }
1170 }
1171
1172
1173 void Sema::ActOnExitFunctionContext() {
1174   // Same implementation as PopDeclContext, but returns to the lexical parent,
1175   // rather than the top-level class.
1176   assert(CurContext && "DeclContext imbalance!");
1177   CurContext = CurContext->getLexicalParent();
1178   assert(CurContext && "Popped translation unit!");
1179 }
1180
1181
1182 /// \brief Determine whether we allow overloading of the function
1183 /// PrevDecl with another declaration.
1184 ///
1185 /// This routine determines whether overloading is possible, not
1186 /// whether some new function is actually an overload. It will return
1187 /// true in C++ (where we can always provide overloads) or, as an
1188 /// extension, in C when the previous function is already an
1189 /// overloaded function declaration or has the "overloadable"
1190 /// attribute.
1191 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1192                                        ASTContext &Context) {
1193   if (Context.getLangOpts().CPlusPlus)
1194     return true;
1195
1196   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1197     return true;
1198
1199   return (Previous.getResultKind() == LookupResult::Found
1200           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1201 }
1202
1203 /// Add this decl to the scope shadowed decl chains.
1204 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1205   // Move up the scope chain until we find the nearest enclosing
1206   // non-transparent context. The declaration will be introduced into this
1207   // scope.
1208   while (S->getEntity() && S->getEntity()->isTransparentContext())
1209     S = S->getParent();
1210
1211   // Add scoped declarations into their context, so that they can be
1212   // found later. Declarations without a context won't be inserted
1213   // into any context.
1214   if (AddToContext)
1215     CurContext->addDecl(D);
1216
1217   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1218   // are function-local declarations.
1219   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1220       !D->getDeclContext()->getRedeclContext()->Equals(
1221         D->getLexicalDeclContext()->getRedeclContext()) &&
1222       !D->getLexicalDeclContext()->isFunctionOrMethod())
1223     return;
1224
1225   // Template instantiations should also not be pushed into scope.
1226   if (isa<FunctionDecl>(D) &&
1227       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1228     return;
1229
1230   // If this replaces anything in the current scope, 
1231   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1232                                IEnd = IdResolver.end();
1233   for (; I != IEnd; ++I) {
1234     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1235       S->RemoveDecl(*I);
1236       IdResolver.RemoveDecl(*I);
1237
1238       // Should only need to replace one decl.
1239       break;
1240     }
1241   }
1242
1243   S->AddDecl(D);
1244   
1245   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1246     // Implicitly-generated labels may end up getting generated in an order that
1247     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1248     // the label at the appropriate place in the identifier chain.
1249     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1250       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1251       if (IDC == CurContext) {
1252         if (!S->isDeclScope(*I))
1253           continue;
1254       } else if (IDC->Encloses(CurContext))
1255         break;
1256     }
1257     
1258     IdResolver.InsertDeclAfter(I, D);
1259   } else {
1260     IdResolver.AddDecl(D);
1261   }
1262 }
1263
1264 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1265   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1266     TUScope->AddDecl(D);
1267 }
1268
1269 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1270                          bool AllowInlineNamespace) {
1271   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1272 }
1273
1274 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1275   DeclContext *TargetDC = DC->getPrimaryContext();
1276   do {
1277     if (DeclContext *ScopeDC = S->getEntity())
1278       if (ScopeDC->getPrimaryContext() == TargetDC)
1279         return S;
1280   } while ((S = S->getParent()));
1281
1282   return nullptr;
1283 }
1284
1285 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1286                                             DeclContext*,
1287                                             ASTContext&);
1288
1289 /// Filters out lookup results that don't fall within the given scope
1290 /// as determined by isDeclInScope.
1291 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1292                                 bool ConsiderLinkage,
1293                                 bool AllowInlineNamespace) {
1294   LookupResult::Filter F = R.makeFilter();
1295   while (F.hasNext()) {
1296     NamedDecl *D = F.next();
1297
1298     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1299       continue;
1300
1301     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1302       continue;
1303
1304     F.erase();
1305   }
1306
1307   F.done();
1308 }
1309
1310 static bool isUsingDecl(NamedDecl *D) {
1311   return isa<UsingShadowDecl>(D) ||
1312          isa<UnresolvedUsingTypenameDecl>(D) ||
1313          isa<UnresolvedUsingValueDecl>(D);
1314 }
1315
1316 /// Removes using shadow declarations from the lookup results.
1317 static void RemoveUsingDecls(LookupResult &R) {
1318   LookupResult::Filter F = R.makeFilter();
1319   while (F.hasNext())
1320     if (isUsingDecl(F.next()))
1321       F.erase();
1322
1323   F.done();
1324 }
1325
1326 /// \brief Check for this common pattern:
1327 /// @code
1328 /// class S {
1329 ///   S(const S&); // DO NOT IMPLEMENT
1330 ///   void operator=(const S&); // DO NOT IMPLEMENT
1331 /// };
1332 /// @endcode
1333 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1334   // FIXME: Should check for private access too but access is set after we get
1335   // the decl here.
1336   if (D->doesThisDeclarationHaveABody())
1337     return false;
1338
1339   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1340     return CD->isCopyConstructor();
1341   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1342     return Method->isCopyAssignmentOperator();
1343   return false;
1344 }
1345
1346 // We need this to handle
1347 //
1348 // typedef struct {
1349 //   void *foo() { return 0; }
1350 // } A;
1351 //
1352 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1353 // for example. If 'A', foo will have external linkage. If we have '*A',
1354 // foo will have no linkage. Since we can't know until we get to the end
1355 // of the typedef, this function finds out if D might have non-external linkage.
1356 // Callers should verify at the end of the TU if it D has external linkage or
1357 // not.
1358 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1359   const DeclContext *DC = D->getDeclContext();
1360   while (!DC->isTranslationUnit()) {
1361     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1362       if (!RD->hasNameForLinkage())
1363         return true;
1364     }
1365     DC = DC->getParent();
1366   }
1367
1368   return !D->isExternallyVisible();
1369 }
1370
1371 // FIXME: This needs to be refactored; some other isInMainFile users want
1372 // these semantics.
1373 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1374   if (S.TUKind != TU_Complete)
1375     return false;
1376   return S.SourceMgr.isInMainFile(Loc);
1377 }
1378
1379 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1380   assert(D);
1381
1382   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1383     return false;
1384
1385   // Ignore all entities declared within templates, and out-of-line definitions
1386   // of members of class templates.
1387   if (D->getDeclContext()->isDependentContext() ||
1388       D->getLexicalDeclContext()->isDependentContext())
1389     return false;
1390
1391   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1392     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1393       return false;
1394
1395     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1396       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1397         return false;
1398     } else {
1399       // 'static inline' functions are defined in headers; don't warn.
1400       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1401         return false;
1402     }
1403
1404     if (FD->doesThisDeclarationHaveABody() &&
1405         Context.DeclMustBeEmitted(FD))
1406       return false;
1407   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1408     // Constants and utility variables are defined in headers with internal
1409     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1410     // like "inline".)
1411     if (!isMainFileLoc(*this, VD->getLocation()))
1412       return false;
1413
1414     if (Context.DeclMustBeEmitted(VD))
1415       return false;
1416
1417     if (VD->isStaticDataMember() &&
1418         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1419       return false;
1420   } else {
1421     return false;
1422   }
1423
1424   // Only warn for unused decls internal to the translation unit.
1425   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1426   // for inline functions defined in the main source file, for instance.
1427   return mightHaveNonExternalLinkage(D);
1428 }
1429
1430 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1431   if (!D)
1432     return;
1433
1434   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1435     const FunctionDecl *First = FD->getFirstDecl();
1436     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1437       return; // First should already be in the vector.
1438   }
1439
1440   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1441     const VarDecl *First = VD->getFirstDecl();
1442     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1443       return; // First should already be in the vector.
1444   }
1445
1446   if (ShouldWarnIfUnusedFileScopedDecl(D))
1447     UnusedFileScopedDecls.push_back(D);
1448 }
1449
1450 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1451   if (D->isInvalidDecl())
1452     return false;
1453
1454   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1455       D->hasAttr<ObjCPreciseLifetimeAttr>())
1456     return false;
1457
1458   if (isa<LabelDecl>(D))
1459     return true;
1460
1461   // Except for labels, we only care about unused decls that are local to
1462   // functions.
1463   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1464   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1465     // For dependent types, the diagnostic is deferred.
1466     WithinFunction =
1467         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1468   if (!WithinFunction)
1469     return false;
1470
1471   if (isa<TypedefNameDecl>(D))
1472     return true;
1473   
1474   // White-list anything that isn't a local variable.
1475   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1476     return false;
1477
1478   // Types of valid local variables should be complete, so this should succeed.
1479   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1480
1481     // White-list anything with an __attribute__((unused)) type.
1482     QualType Ty = VD->getType();
1483
1484     // Only look at the outermost level of typedef.
1485     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1486       if (TT->getDecl()->hasAttr<UnusedAttr>())
1487         return false;
1488     }
1489
1490     // If we failed to complete the type for some reason, or if the type is
1491     // dependent, don't diagnose the variable. 
1492     if (Ty->isIncompleteType() || Ty->isDependentType())
1493       return false;
1494
1495     if (const TagType *TT = Ty->getAs<TagType>()) {
1496       const TagDecl *Tag = TT->getDecl();
1497       if (Tag->hasAttr<UnusedAttr>())
1498         return false;
1499
1500       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1501         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1502           return false;
1503
1504         if (const Expr *Init = VD->getInit()) {
1505           if (const ExprWithCleanups *Cleanups =
1506                   dyn_cast<ExprWithCleanups>(Init))
1507             Init = Cleanups->getSubExpr();
1508           const CXXConstructExpr *Construct =
1509             dyn_cast<CXXConstructExpr>(Init);
1510           if (Construct && !Construct->isElidable()) {
1511             CXXConstructorDecl *CD = Construct->getConstructor();
1512             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1513               return false;
1514           }
1515         }
1516       }
1517     }
1518
1519     // TODO: __attribute__((unused)) templates?
1520   }
1521   
1522   return true;
1523 }
1524
1525 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1526                                      FixItHint &Hint) {
1527   if (isa<LabelDecl>(D)) {
1528     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1529                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1530     if (AfterColon.isInvalid())
1531       return;
1532     Hint = FixItHint::CreateRemoval(CharSourceRange::
1533                                     getCharRange(D->getLocStart(), AfterColon));
1534   }
1535   return;
1536 }
1537
1538 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1539   if (D->getTypeForDecl()->isDependentType())
1540     return;
1541
1542   for (auto *TmpD : D->decls()) {
1543     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1544       DiagnoseUnusedDecl(T);
1545     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1546       DiagnoseUnusedNestedTypedefs(R);
1547   }
1548 }
1549
1550 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1551 /// unless they are marked attr(unused).
1552 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1553   if (!ShouldDiagnoseUnusedDecl(D))
1554     return;
1555
1556   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1557     // typedefs can be referenced later on, so the diagnostics are emitted
1558     // at end-of-translation-unit.
1559     UnusedLocalTypedefNameCandidates.insert(TD);
1560     return;
1561   }
1562   
1563   FixItHint Hint;
1564   GenerateFixForUnusedDecl(D, Context, Hint);
1565
1566   unsigned DiagID;
1567   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1568     DiagID = diag::warn_unused_exception_param;
1569   else if (isa<LabelDecl>(D))
1570     DiagID = diag::warn_unused_label;
1571   else
1572     DiagID = diag::warn_unused_variable;
1573
1574   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1575 }
1576
1577 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1578   // Verify that we have no forward references left.  If so, there was a goto
1579   // or address of a label taken, but no definition of it.  Label fwd
1580   // definitions are indicated with a null substmt which is also not a resolved
1581   // MS inline assembly label name.
1582   bool Diagnose = false;
1583   if (L->isMSAsmLabel())
1584     Diagnose = !L->isResolvedMSAsmLabel();
1585   else
1586     Diagnose = L->getStmt() == nullptr;
1587   if (Diagnose)
1588     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1589 }
1590
1591 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1592   S->mergeNRVOIntoParent();
1593
1594   if (S->decl_empty()) return;
1595   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1596          "Scope shouldn't contain decls!");
1597
1598   for (auto *TmpD : S->decls()) {
1599     assert(TmpD && "This decl didn't get pushed??");
1600
1601     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1602     NamedDecl *D = cast<NamedDecl>(TmpD);
1603
1604     if (!D->getDeclName()) continue;
1605
1606     // Diagnose unused variables in this scope.
1607     if (!S->hasUnrecoverableErrorOccurred()) {
1608       DiagnoseUnusedDecl(D);
1609       if (const auto *RD = dyn_cast<RecordDecl>(D))
1610         DiagnoseUnusedNestedTypedefs(RD);
1611     }
1612     
1613     // If this was a forward reference to a label, verify it was defined.
1614     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1615       CheckPoppedLabel(LD, *this);
1616     
1617     // Remove this name from our lexical scope.
1618     IdResolver.RemoveDecl(D);
1619   }
1620 }
1621
1622 /// \brief Look for an Objective-C class in the translation unit.
1623 ///
1624 /// \param Id The name of the Objective-C class we're looking for. If
1625 /// typo-correction fixes this name, the Id will be updated
1626 /// to the fixed name.
1627 ///
1628 /// \param IdLoc The location of the name in the translation unit.
1629 ///
1630 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1631 /// if there is no class with the given name.
1632 ///
1633 /// \returns The declaration of the named Objective-C class, or NULL if the
1634 /// class could not be found.
1635 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1636                                               SourceLocation IdLoc,
1637                                               bool DoTypoCorrection) {
1638   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1639   // creation from this context.
1640   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1641
1642   if (!IDecl && DoTypoCorrection) {
1643     // Perform typo correction at the given location, but only if we
1644     // find an Objective-C class name.
1645     if (TypoCorrection C = CorrectTypo(
1646             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1647             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1648             CTK_ErrorRecovery)) {
1649       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1650       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1651       Id = IDecl->getIdentifier();
1652     }
1653   }
1654   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1655   // This routine must always return a class definition, if any.
1656   if (Def && Def->getDefinition())
1657       Def = Def->getDefinition();
1658   return Def;
1659 }
1660
1661 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1662 /// from S, where a non-field would be declared. This routine copes
1663 /// with the difference between C and C++ scoping rules in structs and
1664 /// unions. For example, the following code is well-formed in C but
1665 /// ill-formed in C++:
1666 /// @code
1667 /// struct S6 {
1668 ///   enum { BAR } e;
1669 /// };
1670 ///
1671 /// void test_S6() {
1672 ///   struct S6 a;
1673 ///   a.e = BAR;
1674 /// }
1675 /// @endcode
1676 /// For the declaration of BAR, this routine will return a different
1677 /// scope. The scope S will be the scope of the unnamed enumeration
1678 /// within S6. In C++, this routine will return the scope associated
1679 /// with S6, because the enumeration's scope is a transparent
1680 /// context but structures can contain non-field names. In C, this
1681 /// routine will return the translation unit scope, since the
1682 /// enumeration's scope is a transparent context and structures cannot
1683 /// contain non-field names.
1684 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1685   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1686          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1687          (S->isClassScope() && !getLangOpts().CPlusPlus))
1688     S = S->getParent();
1689   return S;
1690 }
1691
1692 /// \brief Looks up the declaration of "struct objc_super" and
1693 /// saves it for later use in building builtin declaration of
1694 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1695 /// pre-existing declaration exists no action takes place.
1696 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1697                                         IdentifierInfo *II) {
1698   if (!II->isStr("objc_msgSendSuper"))
1699     return;
1700   ASTContext &Context = ThisSema.Context;
1701     
1702   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1703                       SourceLocation(), Sema::LookupTagName);
1704   ThisSema.LookupName(Result, S);
1705   if (Result.getResultKind() == LookupResult::Found)
1706     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1707       Context.setObjCSuperType(Context.getTagDeclType(TD));
1708 }
1709
1710 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1711   switch (Error) {
1712   case ASTContext::GE_None:
1713     return "";
1714   case ASTContext::GE_Missing_stdio:
1715     return "stdio.h";
1716   case ASTContext::GE_Missing_setjmp:
1717     return "setjmp.h";
1718   case ASTContext::GE_Missing_ucontext:
1719     return "ucontext.h";
1720   }
1721   llvm_unreachable("unhandled error kind");
1722 }
1723
1724 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1725 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1726 /// if we're creating this built-in in anticipation of redeclaring the
1727 /// built-in.
1728 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1729                                      Scope *S, bool ForRedeclaration,
1730                                      SourceLocation Loc) {
1731   LookupPredefedObjCSuperType(*this, S, II);
1732
1733   ASTContext::GetBuiltinTypeError Error;
1734   QualType R = Context.GetBuiltinType(ID, Error);
1735   if (Error) {
1736     if (ForRedeclaration)
1737       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1738           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1739     return nullptr;
1740   }
1741
1742   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1743     Diag(Loc, diag::ext_implicit_lib_function_decl)
1744         << Context.BuiltinInfo.getName(ID) << R;
1745     if (Context.BuiltinInfo.getHeaderName(ID) &&
1746         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1747       Diag(Loc, diag::note_include_header_or_declare)
1748           << Context.BuiltinInfo.getHeaderName(ID)
1749           << Context.BuiltinInfo.getName(ID);
1750   }
1751
1752   DeclContext *Parent = Context.getTranslationUnitDecl();
1753   if (getLangOpts().CPlusPlus) {
1754     LinkageSpecDecl *CLinkageDecl =
1755         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1756                                 LinkageSpecDecl::lang_c, false);
1757     CLinkageDecl->setImplicit();
1758     Parent->addDecl(CLinkageDecl);
1759     Parent = CLinkageDecl;
1760   }
1761
1762   FunctionDecl *New = FunctionDecl::Create(Context,
1763                                            Parent,
1764                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1765                                            SC_Extern,
1766                                            false,
1767                                            R->isFunctionProtoType());
1768   New->setImplicit();
1769
1770   // Create Decl objects for each parameter, adding them to the
1771   // FunctionDecl.
1772   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1773     SmallVector<ParmVarDecl*, 16> Params;
1774     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1775       ParmVarDecl *parm =
1776           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1777                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1778                               SC_None, nullptr);
1779       parm->setScopeInfo(0, i);
1780       Params.push_back(parm);
1781     }
1782     New->setParams(Params);
1783   }
1784
1785   AddKnownFunctionAttributes(New);
1786   RegisterLocallyScopedExternCDecl(New, S);
1787
1788   // TUScope is the translation-unit scope to insert this function into.
1789   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1790   // relate Scopes to DeclContexts, and probably eliminate CurContext
1791   // entirely, but we're not there yet.
1792   DeclContext *SavedContext = CurContext;
1793   CurContext = Parent;
1794   PushOnScopeChains(New, TUScope);
1795   CurContext = SavedContext;
1796   return New;
1797 }
1798
1799 /// Typedef declarations don't have linkage, but they still denote the same
1800 /// entity if their types are the same.
1801 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1802 /// isSameEntity.
1803 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1804                                                      TypedefNameDecl *Decl,
1805                                                      LookupResult &Previous) {
1806   // This is only interesting when modules are enabled.
1807   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1808     return;
1809
1810   // Empty sets are uninteresting.
1811   if (Previous.empty())
1812     return;
1813
1814   LookupResult::Filter Filter = Previous.makeFilter();
1815   while (Filter.hasNext()) {
1816     NamedDecl *Old = Filter.next();
1817
1818     // Non-hidden declarations are never ignored.
1819     if (S.isVisible(Old))
1820       continue;
1821
1822     // Declarations of the same entity are not ignored, even if they have
1823     // different linkages.
1824     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1825       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1826                                 Decl->getUnderlyingType()))
1827         continue;
1828
1829       // If both declarations give a tag declaration a typedef name for linkage
1830       // purposes, then they declare the same entity.
1831       if (S.getLangOpts().CPlusPlus &&
1832           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1833           Decl->getAnonDeclWithTypedefName())
1834         continue;
1835     }
1836
1837     Filter.erase();
1838   }
1839
1840   Filter.done();
1841 }
1842
1843 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1844   QualType OldType;
1845   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1846     OldType = OldTypedef->getUnderlyingType();
1847   else
1848     OldType = Context.getTypeDeclType(Old);
1849   QualType NewType = New->getUnderlyingType();
1850
1851   if (NewType->isVariablyModifiedType()) {
1852     // Must not redefine a typedef with a variably-modified type.
1853     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1854     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1855       << Kind << NewType;
1856     if (Old->getLocation().isValid())
1857       Diag(Old->getLocation(), diag::note_previous_definition);
1858     New->setInvalidDecl();
1859     return true;    
1860   }
1861   
1862   if (OldType != NewType &&
1863       !OldType->isDependentType() &&
1864       !NewType->isDependentType() &&
1865       !Context.hasSameType(OldType, NewType)) { 
1866     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1867     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1868       << Kind << NewType << OldType;
1869     if (Old->getLocation().isValid())
1870       Diag(Old->getLocation(), diag::note_previous_definition);
1871     New->setInvalidDecl();
1872     return true;
1873   }
1874   return false;
1875 }
1876
1877 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1878 /// same name and scope as a previous declaration 'Old'.  Figure out
1879 /// how to resolve this situation, merging decls or emitting
1880 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1881 ///
1882 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1883                                 LookupResult &OldDecls) {
1884   // If the new decl is known invalid already, don't bother doing any
1885   // merging checks.
1886   if (New->isInvalidDecl()) return;
1887
1888   // Allow multiple definitions for ObjC built-in typedefs.
1889   // FIXME: Verify the underlying types are equivalent!
1890   if (getLangOpts().ObjC1) {
1891     const IdentifierInfo *TypeID = New->getIdentifier();
1892     switch (TypeID->getLength()) {
1893     default: break;
1894     case 2:
1895       {
1896         if (!TypeID->isStr("id"))
1897           break;
1898         QualType T = New->getUnderlyingType();
1899         if (!T->isPointerType())
1900           break;
1901         if (!T->isVoidPointerType()) {
1902           QualType PT = T->getAs<PointerType>()->getPointeeType();
1903           if (!PT->isStructureType())
1904             break;
1905         }
1906         Context.setObjCIdRedefinitionType(T);
1907         // Install the built-in type for 'id', ignoring the current definition.
1908         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1909         return;
1910       }
1911     case 5:
1912       if (!TypeID->isStr("Class"))
1913         break;
1914       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1915       // Install the built-in type for 'Class', ignoring the current definition.
1916       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1917       return;
1918     case 3:
1919       if (!TypeID->isStr("SEL"))
1920         break;
1921       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1922       // Install the built-in type for 'SEL', ignoring the current definition.
1923       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1924       return;
1925     }
1926     // Fall through - the typedef name was not a builtin type.
1927   }
1928
1929   // Verify the old decl was also a type.
1930   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1931   if (!Old) {
1932     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1933       << New->getDeclName();
1934
1935     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1936     if (OldD->getLocation().isValid())
1937       Diag(OldD->getLocation(), diag::note_previous_definition);
1938
1939     return New->setInvalidDecl();
1940   }
1941
1942   // If the old declaration is invalid, just give up here.
1943   if (Old->isInvalidDecl())
1944     return New->setInvalidDecl();
1945
1946   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1947     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
1948     auto *NewTag = New->getAnonDeclWithTypedefName();
1949     NamedDecl *Hidden = nullptr;
1950     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
1951         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
1952         !hasVisibleDefinition(OldTag, &Hidden)) {
1953       // There is a definition of this tag, but it is not visible. Use it
1954       // instead of our tag.
1955       New->setTypeForDecl(OldTD->getTypeForDecl());
1956       if (OldTD->isModed())
1957         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
1958                                     OldTD->getUnderlyingType());
1959       else
1960         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
1961
1962       // Make the old tag definition visible.
1963       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
1964
1965       // If this was an unscoped enumeration, yank all of its enumerators
1966       // out of the scope.
1967       if (isa<EnumDecl>(NewTag)) {
1968         Scope *EnumScope = getNonFieldDeclScope(S);
1969         for (auto *D : NewTag->decls()) {
1970           auto *ED = cast<EnumConstantDecl>(D);
1971           assert(EnumScope->isDeclScope(ED));
1972           EnumScope->RemoveDecl(ED);
1973           IdResolver.RemoveDecl(ED);
1974           ED->getLexicalDeclContext()->removeDecl(ED);
1975         }
1976       }
1977     }
1978   }
1979
1980   // If the typedef types are not identical, reject them in all languages and
1981   // with any extensions enabled.
1982   if (isIncompatibleTypedef(Old, New))
1983     return;
1984
1985   // The types match.  Link up the redeclaration chain and merge attributes if
1986   // the old declaration was a typedef.
1987   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1988     New->setPreviousDecl(Typedef);
1989     mergeDeclAttributes(New, Old);
1990   }
1991
1992   if (getLangOpts().MicrosoftExt)
1993     return;
1994
1995   if (getLangOpts().CPlusPlus) {
1996     // C++ [dcl.typedef]p2:
1997     //   In a given non-class scope, a typedef specifier can be used to
1998     //   redefine the name of any type declared in that scope to refer
1999     //   to the type to which it already refers.
2000     if (!isa<CXXRecordDecl>(CurContext))
2001       return;
2002
2003     // C++0x [dcl.typedef]p4:
2004     //   In a given class scope, a typedef specifier can be used to redefine 
2005     //   any class-name declared in that scope that is not also a typedef-name
2006     //   to refer to the type to which it already refers.
2007     //
2008     // This wording came in via DR424, which was a correction to the
2009     // wording in DR56, which accidentally banned code like:
2010     //
2011     //   struct S {
2012     //     typedef struct A { } A;
2013     //   };
2014     //
2015     // in the C++03 standard. We implement the C++0x semantics, which
2016     // allow the above but disallow
2017     //
2018     //   struct S {
2019     //     typedef int I;
2020     //     typedef int I;
2021     //   };
2022     //
2023     // since that was the intent of DR56.
2024     if (!isa<TypedefNameDecl>(Old))
2025       return;
2026
2027     Diag(New->getLocation(), diag::err_redefinition)
2028       << New->getDeclName();
2029     Diag(Old->getLocation(), diag::note_previous_definition);
2030     return New->setInvalidDecl();
2031   }
2032
2033   // Modules always permit redefinition of typedefs, as does C11.
2034   if (getLangOpts().Modules || getLangOpts().C11)
2035     return;
2036   
2037   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2038   // is normally mapped to an error, but can be controlled with
2039   // -Wtypedef-redefinition.  If either the original or the redefinition is
2040   // in a system header, don't emit this for compatibility with GCC.
2041   if (getDiagnostics().getSuppressSystemWarnings() &&
2042       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2043        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2044     return;
2045
2046   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2047     << New->getDeclName();
2048   Diag(Old->getLocation(), diag::note_previous_definition);
2049 }
2050
2051 /// DeclhasAttr - returns true if decl Declaration already has the target
2052 /// attribute.
2053 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2054   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2055   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2056   for (const auto *i : D->attrs())
2057     if (i->getKind() == A->getKind()) {
2058       if (Ann) {
2059         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2060           return true;
2061         continue;
2062       }
2063       // FIXME: Don't hardcode this check
2064       if (OA && isa<OwnershipAttr>(i))
2065         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2066       return true;
2067     }
2068
2069   return false;
2070 }
2071
2072 static bool isAttributeTargetADefinition(Decl *D) {
2073   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2074     return VD->isThisDeclarationADefinition();
2075   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2076     return TD->isCompleteDefinition() || TD->isBeingDefined();
2077   return true;
2078 }
2079
2080 /// Merge alignment attributes from \p Old to \p New, taking into account the
2081 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2082 ///
2083 /// \return \c true if any attributes were added to \p New.
2084 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2085   // Look for alignas attributes on Old, and pick out whichever attribute
2086   // specifies the strictest alignment requirement.
2087   AlignedAttr *OldAlignasAttr = nullptr;
2088   AlignedAttr *OldStrictestAlignAttr = nullptr;
2089   unsigned OldAlign = 0;
2090   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2091     // FIXME: We have no way of representing inherited dependent alignments
2092     // in a case like:
2093     //   template<int A, int B> struct alignas(A) X;
2094     //   template<int A, int B> struct alignas(B) X {};
2095     // For now, we just ignore any alignas attributes which are not on the
2096     // definition in such a case.
2097     if (I->isAlignmentDependent())
2098       return false;
2099
2100     if (I->isAlignas())
2101       OldAlignasAttr = I;
2102
2103     unsigned Align = I->getAlignment(S.Context);
2104     if (Align > OldAlign) {
2105       OldAlign = Align;
2106       OldStrictestAlignAttr = I;
2107     }
2108   }
2109
2110   // Look for alignas attributes on New.
2111   AlignedAttr *NewAlignasAttr = nullptr;
2112   unsigned NewAlign = 0;
2113   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2114     if (I->isAlignmentDependent())
2115       return false;
2116
2117     if (I->isAlignas())
2118       NewAlignasAttr = I;
2119
2120     unsigned Align = I->getAlignment(S.Context);
2121     if (Align > NewAlign)
2122       NewAlign = Align;
2123   }
2124
2125   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2126     // Both declarations have 'alignas' attributes. We require them to match.
2127     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2128     // fall short. (If two declarations both have alignas, they must both match
2129     // every definition, and so must match each other if there is a definition.)
2130
2131     // If either declaration only contains 'alignas(0)' specifiers, then it
2132     // specifies the natural alignment for the type.
2133     if (OldAlign == 0 || NewAlign == 0) {
2134       QualType Ty;
2135       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2136         Ty = VD->getType();
2137       else
2138         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2139
2140       if (OldAlign == 0)
2141         OldAlign = S.Context.getTypeAlign(Ty);
2142       if (NewAlign == 0)
2143         NewAlign = S.Context.getTypeAlign(Ty);
2144     }
2145
2146     if (OldAlign != NewAlign) {
2147       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2148         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2149         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2150       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2151     }
2152   }
2153
2154   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2155     // C++11 [dcl.align]p6:
2156     //   if any declaration of an entity has an alignment-specifier,
2157     //   every defining declaration of that entity shall specify an
2158     //   equivalent alignment.
2159     // C11 6.7.5/7:
2160     //   If the definition of an object does not have an alignment
2161     //   specifier, any other declaration of that object shall also
2162     //   have no alignment specifier.
2163     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2164       << OldAlignasAttr;
2165     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2166       << OldAlignasAttr;
2167   }
2168
2169   bool AnyAdded = false;
2170
2171   // Ensure we have an attribute representing the strictest alignment.
2172   if (OldAlign > NewAlign) {
2173     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2174     Clone->setInherited(true);
2175     New->addAttr(Clone);
2176     AnyAdded = true;
2177   }
2178
2179   // Ensure we have an alignas attribute if the old declaration had one.
2180   if (OldAlignasAttr && !NewAlignasAttr &&
2181       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2182     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2183     Clone->setInherited(true);
2184     New->addAttr(Clone);
2185     AnyAdded = true;
2186   }
2187
2188   return AnyAdded;
2189 }
2190
2191 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2192                                const InheritableAttr *Attr,
2193                                Sema::AvailabilityMergeKind AMK) {
2194   InheritableAttr *NewAttr = nullptr;
2195   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2196   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2197     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2198                                       AA->getIntroduced(), AA->getDeprecated(),
2199                                       AA->getObsoleted(), AA->getUnavailable(),
2200                                       AA->getMessage(), AMK,
2201                                       AttrSpellingListIndex);
2202   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2203     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2204                                     AttrSpellingListIndex);
2205   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2206     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2207                                         AttrSpellingListIndex);
2208   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2209     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2210                                    AttrSpellingListIndex);
2211   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2212     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2213                                    AttrSpellingListIndex);
2214   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2215     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2216                                 FA->getFormatIdx(), FA->getFirstArg(),
2217                                 AttrSpellingListIndex);
2218   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2219     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2220                                  AttrSpellingListIndex);
2221   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2222     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2223                                        AttrSpellingListIndex,
2224                                        IA->getSemanticSpelling());
2225   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2226     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2227                                       &S.Context.Idents.get(AA->getSpelling()),
2228                                       AttrSpellingListIndex);
2229   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2230     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2231   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2232     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2233   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2234     NewAttr = S.mergeInternalLinkageAttr(
2235         D, InternalLinkageA->getRange(),
2236         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2237         AttrSpellingListIndex);
2238   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2239     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2240                                 &S.Context.Idents.get(CommonA->getSpelling()),
2241                                 AttrSpellingListIndex);
2242   else if (isa<AlignedAttr>(Attr))
2243     // AlignedAttrs are handled separately, because we need to handle all
2244     // such attributes on a declaration at the same time.
2245     NewAttr = nullptr;
2246   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2247            (AMK == Sema::AMK_Override ||
2248             AMK == Sema::AMK_ProtocolImplementation))
2249     NewAttr = nullptr;
2250   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2251     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2252
2253   if (NewAttr) {
2254     NewAttr->setInherited(true);
2255     D->addAttr(NewAttr);
2256     return true;
2257   }
2258
2259   return false;
2260 }
2261
2262 static const Decl *getDefinition(const Decl *D) {
2263   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2264     return TD->getDefinition();
2265   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2266     const VarDecl *Def = VD->getDefinition();
2267     if (Def)
2268       return Def;
2269     return VD->getActingDefinition();
2270   }
2271   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2272     const FunctionDecl* Def;
2273     if (FD->isDefined(Def))
2274       return Def;
2275   }
2276   return nullptr;
2277 }
2278
2279 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2280   for (const auto *Attribute : D->attrs())
2281     if (Attribute->getKind() == Kind)
2282       return true;
2283   return false;
2284 }
2285
2286 /// checkNewAttributesAfterDef - If we already have a definition, check that
2287 /// there are no new attributes in this declaration.
2288 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2289   if (!New->hasAttrs())
2290     return;
2291
2292   const Decl *Def = getDefinition(Old);
2293   if (!Def || Def == New)
2294     return;
2295
2296   AttrVec &NewAttributes = New->getAttrs();
2297   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2298     const Attr *NewAttribute = NewAttributes[I];
2299
2300     if (isa<AliasAttr>(NewAttribute)) {
2301       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2302         Sema::SkipBodyInfo SkipBody;
2303         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2304
2305         // If we're skipping this definition, drop the "alias" attribute.
2306         if (SkipBody.ShouldSkip) {
2307           NewAttributes.erase(NewAttributes.begin() + I);
2308           --E;
2309           continue;
2310         }
2311       } else {
2312         VarDecl *VD = cast<VarDecl>(New);
2313         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2314                                 VarDecl::TentativeDefinition
2315                             ? diag::err_alias_after_tentative
2316                             : diag::err_redefinition;
2317         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2318         S.Diag(Def->getLocation(), diag::note_previous_definition);
2319         VD->setInvalidDecl();
2320       }
2321       ++I;
2322       continue;
2323     }
2324
2325     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2326       // Tentative definitions are only interesting for the alias check above.
2327       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2328         ++I;
2329         continue;
2330       }
2331     }
2332
2333     if (hasAttribute(Def, NewAttribute->getKind())) {
2334       ++I;
2335       continue; // regular attr merging will take care of validating this.
2336     }
2337
2338     if (isa<C11NoReturnAttr>(NewAttribute)) {
2339       // C's _Noreturn is allowed to be added to a function after it is defined.
2340       ++I;
2341       continue;
2342     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2343       if (AA->isAlignas()) { 
2344         // C++11 [dcl.align]p6:
2345         //   if any declaration of an entity has an alignment-specifier,
2346         //   every defining declaration of that entity shall specify an
2347         //   equivalent alignment.
2348         // C11 6.7.5/7:
2349         //   If the definition of an object does not have an alignment
2350         //   specifier, any other declaration of that object shall also
2351         //   have no alignment specifier.
2352         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2353           << AA;
2354         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2355           << AA;
2356         NewAttributes.erase(NewAttributes.begin() + I);
2357         --E;
2358         continue;
2359       }
2360     }
2361
2362     S.Diag(NewAttribute->getLocation(),
2363            diag::warn_attribute_precede_definition);
2364     S.Diag(Def->getLocation(), diag::note_previous_definition);
2365     NewAttributes.erase(NewAttributes.begin() + I);
2366     --E;
2367   }
2368 }
2369
2370 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2371 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2372                                AvailabilityMergeKind AMK) {
2373   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2374     UsedAttr *NewAttr = OldAttr->clone(Context);
2375     NewAttr->setInherited(true);
2376     New->addAttr(NewAttr);
2377   }
2378
2379   if (!Old->hasAttrs() && !New->hasAttrs())
2380     return;
2381
2382   // Attributes declared post-definition are currently ignored.
2383   checkNewAttributesAfterDef(*this, New, Old);
2384
2385   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2386     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2387       if (OldA->getLabel() != NewA->getLabel()) {
2388         // This redeclaration changes __asm__ label.
2389         Diag(New->getLocation(), diag::err_different_asm_label);
2390         Diag(OldA->getLocation(), diag::note_previous_declaration);
2391       }
2392     } else if (Old->isUsed()) {
2393       // This redeclaration adds an __asm__ label to a declaration that has
2394       // already been ODR-used.
2395       Diag(New->getLocation(), diag::err_late_asm_label_name)
2396         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2397     }
2398   }
2399
2400   if (!Old->hasAttrs())
2401     return;
2402
2403   bool foundAny = New->hasAttrs();
2404
2405   // Ensure that any moving of objects within the allocated map is done before
2406   // we process them.
2407   if (!foundAny) New->setAttrs(AttrVec());
2408
2409   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2410     // Ignore deprecated/unavailable/availability attributes if requested.
2411     AvailabilityMergeKind LocalAMK = AMK_None;
2412     if (isa<DeprecatedAttr>(I) ||
2413         isa<UnavailableAttr>(I) ||
2414         isa<AvailabilityAttr>(I)) {
2415       switch (AMK) {
2416       case AMK_None:
2417         continue;
2418
2419       case AMK_Redeclaration:
2420       case AMK_Override:
2421       case AMK_ProtocolImplementation:
2422         LocalAMK = AMK;
2423         break;
2424       }
2425     }
2426
2427     // Already handled.
2428     if (isa<UsedAttr>(I))
2429       continue;
2430
2431     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2432       foundAny = true;
2433   }
2434
2435   if (mergeAlignedAttrs(*this, New, Old))
2436     foundAny = true;
2437
2438   if (!foundAny) New->dropAttrs();
2439 }
2440
2441 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2442 /// to the new one.
2443 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2444                                      const ParmVarDecl *oldDecl,
2445                                      Sema &S) {
2446   // C++11 [dcl.attr.depend]p2:
2447   //   The first declaration of a function shall specify the
2448   //   carries_dependency attribute for its declarator-id if any declaration
2449   //   of the function specifies the carries_dependency attribute.
2450   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2451   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2452     S.Diag(CDA->getLocation(),
2453            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2454     // Find the first declaration of the parameter.
2455     // FIXME: Should we build redeclaration chains for function parameters?
2456     const FunctionDecl *FirstFD =
2457       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2458     const ParmVarDecl *FirstVD =
2459       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2460     S.Diag(FirstVD->getLocation(),
2461            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2462   }
2463
2464   if (!oldDecl->hasAttrs())
2465     return;
2466
2467   bool foundAny = newDecl->hasAttrs();
2468
2469   // Ensure that any moving of objects within the allocated map is
2470   // done before we process them.
2471   if (!foundAny) newDecl->setAttrs(AttrVec());
2472
2473   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2474     if (!DeclHasAttr(newDecl, I)) {
2475       InheritableAttr *newAttr =
2476         cast<InheritableParamAttr>(I->clone(S.Context));
2477       newAttr->setInherited(true);
2478       newDecl->addAttr(newAttr);
2479       foundAny = true;
2480     }
2481   }
2482
2483   if (!foundAny) newDecl->dropAttrs();
2484 }
2485
2486 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2487                                 const ParmVarDecl *OldParam,
2488                                 Sema &S) {
2489   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2490     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2491       if (*Oldnullability != *Newnullability) {
2492         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2493           << DiagNullabilityKind(
2494                *Newnullability,
2495                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2496                 != 0))
2497           << DiagNullabilityKind(
2498                *Oldnullability,
2499                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2500                 != 0));
2501         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2502       }
2503     } else {
2504       QualType NewT = NewParam->getType();
2505       NewT = S.Context.getAttributedType(
2506                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2507                          NewT, NewT);
2508       NewParam->setType(NewT);
2509     }
2510   }
2511 }
2512
2513 namespace {
2514
2515 /// Used in MergeFunctionDecl to keep track of function parameters in
2516 /// C.
2517 struct GNUCompatibleParamWarning {
2518   ParmVarDecl *OldParm;
2519   ParmVarDecl *NewParm;
2520   QualType PromotedType;
2521 };
2522
2523 }
2524
2525 /// getSpecialMember - get the special member enum for a method.
2526 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2527   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2528     if (Ctor->isDefaultConstructor())
2529       return Sema::CXXDefaultConstructor;
2530
2531     if (Ctor->isCopyConstructor())
2532       return Sema::CXXCopyConstructor;
2533
2534     if (Ctor->isMoveConstructor())
2535       return Sema::CXXMoveConstructor;
2536   } else if (isa<CXXDestructorDecl>(MD)) {
2537     return Sema::CXXDestructor;
2538   } else if (MD->isCopyAssignmentOperator()) {
2539     return Sema::CXXCopyAssignment;
2540   } else if (MD->isMoveAssignmentOperator()) {
2541     return Sema::CXXMoveAssignment;
2542   }
2543
2544   return Sema::CXXInvalid;
2545 }
2546
2547 // Determine whether the previous declaration was a definition, implicit
2548 // declaration, or a declaration.
2549 template <typename T>
2550 static std::pair<diag::kind, SourceLocation>
2551 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2552   diag::kind PrevDiag;
2553   SourceLocation OldLocation = Old->getLocation();
2554   if (Old->isThisDeclarationADefinition())
2555     PrevDiag = diag::note_previous_definition;
2556   else if (Old->isImplicit()) {
2557     PrevDiag = diag::note_previous_implicit_declaration;
2558     if (OldLocation.isInvalid())
2559       OldLocation = New->getLocation();
2560   } else
2561     PrevDiag = diag::note_previous_declaration;
2562   return std::make_pair(PrevDiag, OldLocation);
2563 }
2564
2565 /// canRedefineFunction - checks if a function can be redefined. Currently,
2566 /// only extern inline functions can be redefined, and even then only in
2567 /// GNU89 mode.
2568 static bool canRedefineFunction(const FunctionDecl *FD,
2569                                 const LangOptions& LangOpts) {
2570   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2571           !LangOpts.CPlusPlus &&
2572           FD->isInlineSpecified() &&
2573           FD->getStorageClass() == SC_Extern);
2574 }
2575
2576 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2577   const AttributedType *AT = T->getAs<AttributedType>();
2578   while (AT && !AT->isCallingConv())
2579     AT = AT->getModifiedType()->getAs<AttributedType>();
2580   return AT;
2581 }
2582
2583 template <typename T>
2584 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2585   const DeclContext *DC = Old->getDeclContext();
2586   if (DC->isRecord())
2587     return false;
2588
2589   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2590   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2591     return true;
2592   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2593     return true;
2594   return false;
2595 }
2596
2597 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2598 static bool isExternC(VarTemplateDecl *) { return false; }
2599
2600 /// \brief Check whether a redeclaration of an entity introduced by a
2601 /// using-declaration is valid, given that we know it's not an overload
2602 /// (nor a hidden tag declaration).
2603 template<typename ExpectedDecl>
2604 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2605                                    ExpectedDecl *New) {
2606   // C++11 [basic.scope.declarative]p4:
2607   //   Given a set of declarations in a single declarative region, each of
2608   //   which specifies the same unqualified name,
2609   //   -- they shall all refer to the same entity, or all refer to functions
2610   //      and function templates; or
2611   //   -- exactly one declaration shall declare a class name or enumeration
2612   //      name that is not a typedef name and the other declarations shall all
2613   //      refer to the same variable or enumerator, or all refer to functions
2614   //      and function templates; in this case the class name or enumeration
2615   //      name is hidden (3.3.10).
2616
2617   // C++11 [namespace.udecl]p14:
2618   //   If a function declaration in namespace scope or block scope has the
2619   //   same name and the same parameter-type-list as a function introduced
2620   //   by a using-declaration, and the declarations do not declare the same
2621   //   function, the program is ill-formed.
2622
2623   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2624   if (Old &&
2625       !Old->getDeclContext()->getRedeclContext()->Equals(
2626           New->getDeclContext()->getRedeclContext()) &&
2627       !(isExternC(Old) && isExternC(New)))
2628     Old = nullptr;
2629
2630   if (!Old) {
2631     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2632     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2633     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2634     return true;
2635   }
2636   return false;
2637 }
2638
2639 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2640                                             const FunctionDecl *B) {
2641   assert(A->getNumParams() == B->getNumParams());
2642
2643   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2644     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2645     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2646     if (AttrA == AttrB)
2647       return true;
2648     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2649   };
2650
2651   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2652 }
2653
2654 /// MergeFunctionDecl - We just parsed a function 'New' from
2655 /// declarator D which has the same name and scope as a previous
2656 /// declaration 'Old'.  Figure out how to resolve this situation,
2657 /// merging decls or emitting diagnostics as appropriate.
2658 ///
2659 /// In C++, New and Old must be declarations that are not
2660 /// overloaded. Use IsOverload to determine whether New and Old are
2661 /// overloaded, and to select the Old declaration that New should be
2662 /// merged with.
2663 ///
2664 /// Returns true if there was an error, false otherwise.
2665 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2666                              Scope *S, bool MergeTypeWithOld) {
2667   // Verify the old decl was also a function.
2668   FunctionDecl *Old = OldD->getAsFunction();
2669   if (!Old) {
2670     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2671       if (New->getFriendObjectKind()) {
2672         Diag(New->getLocation(), diag::err_using_decl_friend);
2673         Diag(Shadow->getTargetDecl()->getLocation(),
2674              diag::note_using_decl_target);
2675         Diag(Shadow->getUsingDecl()->getLocation(),
2676              diag::note_using_decl) << 0;
2677         return true;
2678       }
2679
2680       // Check whether the two declarations might declare the same function.
2681       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2682         return true;
2683       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2684     } else {
2685       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2686         << New->getDeclName();
2687       Diag(OldD->getLocation(), diag::note_previous_definition);
2688       return true;
2689     }
2690   }
2691
2692   // If the old declaration is invalid, just give up here.
2693   if (Old->isInvalidDecl())
2694     return true;
2695
2696   diag::kind PrevDiag;
2697   SourceLocation OldLocation;
2698   std::tie(PrevDiag, OldLocation) =
2699       getNoteDiagForInvalidRedeclaration(Old, New);
2700
2701   // Don't complain about this if we're in GNU89 mode and the old function
2702   // is an extern inline function.
2703   // Don't complain about specializations. They are not supposed to have
2704   // storage classes.
2705   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2706       New->getStorageClass() == SC_Static &&
2707       Old->hasExternalFormalLinkage() &&
2708       !New->getTemplateSpecializationInfo() &&
2709       !canRedefineFunction(Old, getLangOpts())) {
2710     if (getLangOpts().MicrosoftExt) {
2711       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2712       Diag(OldLocation, PrevDiag);
2713     } else {
2714       Diag(New->getLocation(), diag::err_static_non_static) << New;
2715       Diag(OldLocation, PrevDiag);
2716       return true;
2717     }
2718   }
2719
2720   if (New->hasAttr<InternalLinkageAttr>() &&
2721       !Old->hasAttr<InternalLinkageAttr>()) {
2722     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2723         << New->getDeclName();
2724     Diag(Old->getLocation(), diag::note_previous_definition);
2725     New->dropAttr<InternalLinkageAttr>();
2726   }
2727
2728   // If a function is first declared with a calling convention, but is later
2729   // declared or defined without one, all following decls assume the calling
2730   // convention of the first.
2731   //
2732   // It's OK if a function is first declared without a calling convention,
2733   // but is later declared or defined with the default calling convention.
2734   //
2735   // To test if either decl has an explicit calling convention, we look for
2736   // AttributedType sugar nodes on the type as written.  If they are missing or
2737   // were canonicalized away, we assume the calling convention was implicit.
2738   //
2739   // Note also that we DO NOT return at this point, because we still have
2740   // other tests to run.
2741   QualType OldQType = Context.getCanonicalType(Old->getType());
2742   QualType NewQType = Context.getCanonicalType(New->getType());
2743   const FunctionType *OldType = cast<FunctionType>(OldQType);
2744   const FunctionType *NewType = cast<FunctionType>(NewQType);
2745   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2746   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2747   bool RequiresAdjustment = false;
2748
2749   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2750     FunctionDecl *First = Old->getFirstDecl();
2751     const FunctionType *FT =
2752         First->getType().getCanonicalType()->castAs<FunctionType>();
2753     FunctionType::ExtInfo FI = FT->getExtInfo();
2754     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2755     if (!NewCCExplicit) {
2756       // Inherit the CC from the previous declaration if it was specified
2757       // there but not here.
2758       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2759       RequiresAdjustment = true;
2760     } else {
2761       // Calling conventions aren't compatible, so complain.
2762       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2763       Diag(New->getLocation(), diag::err_cconv_change)
2764         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2765         << !FirstCCExplicit
2766         << (!FirstCCExplicit ? "" :
2767             FunctionType::getNameForCallConv(FI.getCC()));
2768
2769       // Put the note on the first decl, since it is the one that matters.
2770       Diag(First->getLocation(), diag::note_previous_declaration);
2771       return true;
2772     }
2773   }
2774
2775   // FIXME: diagnose the other way around?
2776   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2777     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2778     RequiresAdjustment = true;
2779   }
2780
2781   // Merge regparm attribute.
2782   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2783       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2784     if (NewTypeInfo.getHasRegParm()) {
2785       Diag(New->getLocation(), diag::err_regparm_mismatch)
2786         << NewType->getRegParmType()
2787         << OldType->getRegParmType();
2788       Diag(OldLocation, diag::note_previous_declaration);
2789       return true;
2790     }
2791
2792     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2793     RequiresAdjustment = true;
2794   }
2795
2796   // Merge ns_returns_retained attribute.
2797   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2798     if (NewTypeInfo.getProducesResult()) {
2799       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2800       Diag(OldLocation, diag::note_previous_declaration);
2801       return true;
2802     }
2803     
2804     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2805     RequiresAdjustment = true;
2806   }
2807   
2808   if (RequiresAdjustment) {
2809     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2810     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2811     New->setType(QualType(AdjustedType, 0));
2812     NewQType = Context.getCanonicalType(New->getType());
2813     NewType = cast<FunctionType>(NewQType);
2814   }
2815
2816   // If this redeclaration makes the function inline, we may need to add it to
2817   // UndefinedButUsed.
2818   if (!Old->isInlined() && New->isInlined() &&
2819       !New->hasAttr<GNUInlineAttr>() &&
2820       !getLangOpts().GNUInline &&
2821       Old->isUsed(false) &&
2822       !Old->isDefined() && !New->isThisDeclarationADefinition())
2823     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2824                                            SourceLocation()));
2825
2826   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2827   // about it.
2828   if (New->hasAttr<GNUInlineAttr>() &&
2829       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2830     UndefinedButUsed.erase(Old->getCanonicalDecl());
2831   }
2832
2833   // If pass_object_size params don't match up perfectly, this isn't a valid
2834   // redeclaration.
2835   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2836       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2837     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2838         << New->getDeclName();
2839     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2840     return true;
2841   }
2842
2843   if (getLangOpts().CPlusPlus) {
2844     // (C++98 13.1p2):
2845     //   Certain function declarations cannot be overloaded:
2846     //     -- Function declarations that differ only in the return type
2847     //        cannot be overloaded.
2848
2849     // Go back to the type source info to compare the declared return types,
2850     // per C++1y [dcl.type.auto]p13:
2851     //   Redeclarations or specializations of a function or function template
2852     //   with a declared return type that uses a placeholder type shall also
2853     //   use that placeholder, not a deduced type.
2854     QualType OldDeclaredReturnType =
2855         (Old->getTypeSourceInfo()
2856              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2857              : OldType)->getReturnType();
2858     QualType NewDeclaredReturnType =
2859         (New->getTypeSourceInfo()
2860              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2861              : NewType)->getReturnType();
2862     QualType ResQT;
2863     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2864         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2865           New->isLocalExternDecl())) {
2866       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2867           OldDeclaredReturnType->isObjCObjectPointerType())
2868         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2869       if (ResQT.isNull()) {
2870         if (New->isCXXClassMember() && New->isOutOfLine())
2871           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2872               << New << New->getReturnTypeSourceRange();
2873         else
2874           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2875               << New->getReturnTypeSourceRange();
2876         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2877                                     << Old->getReturnTypeSourceRange();
2878         return true;
2879       }
2880       else
2881         NewQType = ResQT;
2882     }
2883
2884     QualType OldReturnType = OldType->getReturnType();
2885     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2886     if (OldReturnType != NewReturnType) {
2887       // If this function has a deduced return type and has already been
2888       // defined, copy the deduced value from the old declaration.
2889       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2890       if (OldAT && OldAT->isDeduced()) {
2891         New->setType(
2892             SubstAutoType(New->getType(),
2893                           OldAT->isDependentType() ? Context.DependentTy
2894                                                    : OldAT->getDeducedType()));
2895         NewQType = Context.getCanonicalType(
2896             SubstAutoType(NewQType,
2897                           OldAT->isDependentType() ? Context.DependentTy
2898                                                    : OldAT->getDeducedType()));
2899       }
2900     }
2901
2902     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2903     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2904     if (OldMethod && NewMethod) {
2905       // Preserve triviality.
2906       NewMethod->setTrivial(OldMethod->isTrivial());
2907
2908       // MSVC allows explicit template specialization at class scope:
2909       // 2 CXXMethodDecls referring to the same function will be injected.
2910       // We don't want a redeclaration error.
2911       bool IsClassScopeExplicitSpecialization =
2912                               OldMethod->isFunctionTemplateSpecialization() &&
2913                               NewMethod->isFunctionTemplateSpecialization();
2914       bool isFriend = NewMethod->getFriendObjectKind();
2915
2916       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2917           !IsClassScopeExplicitSpecialization) {
2918         //    -- Member function declarations with the same name and the
2919         //       same parameter types cannot be overloaded if any of them
2920         //       is a static member function declaration.
2921         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2922           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2923           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2924           return true;
2925         }
2926
2927         // C++ [class.mem]p1:
2928         //   [...] A member shall not be declared twice in the
2929         //   member-specification, except that a nested class or member
2930         //   class template can be declared and then later defined.
2931         if (ActiveTemplateInstantiations.empty()) {
2932           unsigned NewDiag;
2933           if (isa<CXXConstructorDecl>(OldMethod))
2934             NewDiag = diag::err_constructor_redeclared;
2935           else if (isa<CXXDestructorDecl>(NewMethod))
2936             NewDiag = diag::err_destructor_redeclared;
2937           else if (isa<CXXConversionDecl>(NewMethod))
2938             NewDiag = diag::err_conv_function_redeclared;
2939           else
2940             NewDiag = diag::err_member_redeclared;
2941
2942           Diag(New->getLocation(), NewDiag);
2943         } else {
2944           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2945             << New << New->getType();
2946         }
2947         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2948         return true;
2949
2950       // Complain if this is an explicit declaration of a special
2951       // member that was initially declared implicitly.
2952       //
2953       // As an exception, it's okay to befriend such methods in order
2954       // to permit the implicit constructor/destructor/operator calls.
2955       } else if (OldMethod->isImplicit()) {
2956         if (isFriend) {
2957           NewMethod->setImplicit();
2958         } else {
2959           Diag(NewMethod->getLocation(),
2960                diag::err_definition_of_implicitly_declared_member) 
2961             << New << getSpecialMember(OldMethod);
2962           return true;
2963         }
2964       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2965         Diag(NewMethod->getLocation(),
2966              diag::err_definition_of_explicitly_defaulted_member)
2967           << getSpecialMember(OldMethod);
2968         return true;
2969       }
2970     }
2971
2972     // C++11 [dcl.attr.noreturn]p1:
2973     //   The first declaration of a function shall specify the noreturn
2974     //   attribute if any declaration of that function specifies the noreturn
2975     //   attribute.
2976     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2977     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2978       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2979       Diag(Old->getFirstDecl()->getLocation(),
2980            diag::note_noreturn_missing_first_decl);
2981     }
2982
2983     // C++11 [dcl.attr.depend]p2:
2984     //   The first declaration of a function shall specify the
2985     //   carries_dependency attribute for its declarator-id if any declaration
2986     //   of the function specifies the carries_dependency attribute.
2987     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2988     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2989       Diag(CDA->getLocation(),
2990            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2991       Diag(Old->getFirstDecl()->getLocation(),
2992            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2993     }
2994
2995     // (C++98 8.3.5p3):
2996     //   All declarations for a function shall agree exactly in both the
2997     //   return type and the parameter-type-list.
2998     // We also want to respect all the extended bits except noreturn.
2999
3000     // noreturn should now match unless the old type info didn't have it.
3001     QualType OldQTypeForComparison = OldQType;
3002     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3003       assert(OldQType == QualType(OldType, 0));
3004       const FunctionType *OldTypeForComparison
3005         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3006       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3007       assert(OldQTypeForComparison.isCanonical());
3008     }
3009
3010     if (haveIncompatibleLanguageLinkages(Old, New)) {
3011       // As a special case, retain the language linkage from previous
3012       // declarations of a friend function as an extension.
3013       //
3014       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3015       // and is useful because there's otherwise no way to specify language
3016       // linkage within class scope.
3017       //
3018       // Check cautiously as the friend object kind isn't yet complete.
3019       if (New->getFriendObjectKind() != Decl::FOK_None) {
3020         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3021         Diag(OldLocation, PrevDiag);
3022       } else {
3023         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3024         Diag(OldLocation, PrevDiag);
3025         return true;
3026       }
3027     }
3028
3029     if (OldQTypeForComparison == NewQType)
3030       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3031
3032     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3033         New->isLocalExternDecl()) {
3034       // It's OK if we couldn't merge types for a local function declaraton
3035       // if either the old or new type is dependent. We'll merge the types
3036       // when we instantiate the function.
3037       return false;
3038     }
3039
3040     // Fall through for conflicting redeclarations and redefinitions.
3041   }
3042
3043   // C: Function types need to be compatible, not identical. This handles
3044   // duplicate function decls like "void f(int); void f(enum X);" properly.
3045   if (!getLangOpts().CPlusPlus &&
3046       Context.typesAreCompatible(OldQType, NewQType)) {
3047     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3048     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3049     const FunctionProtoType *OldProto = nullptr;
3050     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3051         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3052       // The old declaration provided a function prototype, but the
3053       // new declaration does not. Merge in the prototype.
3054       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3055       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3056       NewQType =
3057           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3058                                   OldProto->getExtProtoInfo());
3059       New->setType(NewQType);
3060       New->setHasInheritedPrototype();
3061
3062       // Synthesize parameters with the same types.
3063       SmallVector<ParmVarDecl*, 16> Params;
3064       for (const auto &ParamType : OldProto->param_types()) {
3065         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3066                                                  SourceLocation(), nullptr,
3067                                                  ParamType, /*TInfo=*/nullptr,
3068                                                  SC_None, nullptr);
3069         Param->setScopeInfo(0, Params.size());
3070         Param->setImplicit();
3071         Params.push_back(Param);
3072       }
3073
3074       New->setParams(Params);
3075     }
3076
3077     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3078   }
3079
3080   // GNU C permits a K&R definition to follow a prototype declaration
3081   // if the declared types of the parameters in the K&R definition
3082   // match the types in the prototype declaration, even when the
3083   // promoted types of the parameters from the K&R definition differ
3084   // from the types in the prototype. GCC then keeps the types from
3085   // the prototype.
3086   //
3087   // If a variadic prototype is followed by a non-variadic K&R definition,
3088   // the K&R definition becomes variadic.  This is sort of an edge case, but
3089   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3090   // C99 6.9.1p8.
3091   if (!getLangOpts().CPlusPlus &&
3092       Old->hasPrototype() && !New->hasPrototype() &&
3093       New->getType()->getAs<FunctionProtoType>() &&
3094       Old->getNumParams() == New->getNumParams()) {
3095     SmallVector<QualType, 16> ArgTypes;
3096     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3097     const FunctionProtoType *OldProto
3098       = Old->getType()->getAs<FunctionProtoType>();
3099     const FunctionProtoType *NewProto
3100       = New->getType()->getAs<FunctionProtoType>();
3101
3102     // Determine whether this is the GNU C extension.
3103     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3104                                                NewProto->getReturnType());
3105     bool LooseCompatible = !MergedReturn.isNull();
3106     for (unsigned Idx = 0, End = Old->getNumParams();
3107          LooseCompatible && Idx != End; ++Idx) {
3108       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3109       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3110       if (Context.typesAreCompatible(OldParm->getType(),
3111                                      NewProto->getParamType(Idx))) {
3112         ArgTypes.push_back(NewParm->getType());
3113       } else if (Context.typesAreCompatible(OldParm->getType(),
3114                                             NewParm->getType(),
3115                                             /*CompareUnqualified=*/true)) {
3116         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3117                                            NewProto->getParamType(Idx) };
3118         Warnings.push_back(Warn);
3119         ArgTypes.push_back(NewParm->getType());
3120       } else
3121         LooseCompatible = false;
3122     }
3123
3124     if (LooseCompatible) {
3125       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3126         Diag(Warnings[Warn].NewParm->getLocation(),
3127              diag::ext_param_promoted_not_compatible_with_prototype)
3128           << Warnings[Warn].PromotedType
3129           << Warnings[Warn].OldParm->getType();
3130         if (Warnings[Warn].OldParm->getLocation().isValid())
3131           Diag(Warnings[Warn].OldParm->getLocation(),
3132                diag::note_previous_declaration);
3133       }
3134
3135       if (MergeTypeWithOld)
3136         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3137                                              OldProto->getExtProtoInfo()));
3138       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3139     }
3140
3141     // Fall through to diagnose conflicting types.
3142   }
3143
3144   // A function that has already been declared has been redeclared or
3145   // defined with a different type; show an appropriate diagnostic.
3146
3147   // If the previous declaration was an implicitly-generated builtin
3148   // declaration, then at the very least we should use a specialized note.
3149   unsigned BuiltinID;
3150   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3151     // If it's actually a library-defined builtin function like 'malloc'
3152     // or 'printf', just warn about the incompatible redeclaration.
3153     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3154       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3155       Diag(OldLocation, diag::note_previous_builtin_declaration)
3156         << Old << Old->getType();
3157
3158       // If this is a global redeclaration, just forget hereafter
3159       // about the "builtin-ness" of the function.
3160       //
3161       // Doing this for local extern declarations is problematic.  If
3162       // the builtin declaration remains visible, a second invalid
3163       // local declaration will produce a hard error; if it doesn't
3164       // remain visible, a single bogus local redeclaration (which is
3165       // actually only a warning) could break all the downstream code.
3166       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3167         New->getIdentifier()->revertBuiltin();
3168
3169       return false;
3170     }
3171
3172     PrevDiag = diag::note_previous_builtin_declaration;
3173   }
3174
3175   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3176   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3177   return true;
3178 }
3179
3180 /// \brief Completes the merge of two function declarations that are
3181 /// known to be compatible.
3182 ///
3183 /// This routine handles the merging of attributes and other
3184 /// properties of function declarations from the old declaration to
3185 /// the new declaration, once we know that New is in fact a
3186 /// redeclaration of Old.
3187 ///
3188 /// \returns false
3189 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3190                                         Scope *S, bool MergeTypeWithOld) {
3191   // Merge the attributes
3192   mergeDeclAttributes(New, Old);
3193
3194   // Merge "pure" flag.
3195   if (Old->isPure())
3196     New->setPure();
3197
3198   // Merge "used" flag.
3199   if (Old->getMostRecentDecl()->isUsed(false))
3200     New->setIsUsed();
3201
3202   // Merge attributes from the parameters.  These can mismatch with K&R
3203   // declarations.
3204   if (New->getNumParams() == Old->getNumParams())
3205       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3206         ParmVarDecl *NewParam = New->getParamDecl(i);
3207         ParmVarDecl *OldParam = Old->getParamDecl(i);
3208         mergeParamDeclAttributes(NewParam, OldParam, *this);
3209         mergeParamDeclTypes(NewParam, OldParam, *this);
3210       }
3211
3212   if (getLangOpts().CPlusPlus)
3213     return MergeCXXFunctionDecl(New, Old, S);
3214
3215   // Merge the function types so the we get the composite types for the return
3216   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3217   // was visible.
3218   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3219   if (!Merged.isNull() && MergeTypeWithOld)
3220     New->setType(Merged);
3221
3222   return false;
3223 }
3224
3225
3226 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3227                                 ObjCMethodDecl *oldMethod) {
3228
3229   // Merge the attributes, including deprecated/unavailable
3230   AvailabilityMergeKind MergeKind =
3231     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3232       ? AMK_ProtocolImplementation
3233       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3234                                                        : AMK_Override;
3235
3236   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3237
3238   // Merge attributes from the parameters.
3239   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3240                                        oe = oldMethod->param_end();
3241   for (ObjCMethodDecl::param_iterator
3242          ni = newMethod->param_begin(), ne = newMethod->param_end();
3243        ni != ne && oi != oe; ++ni, ++oi)
3244     mergeParamDeclAttributes(*ni, *oi, *this);
3245
3246   CheckObjCMethodOverride(newMethod, oldMethod);
3247 }
3248
3249 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3250 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3251 /// emitting diagnostics as appropriate.
3252 ///
3253 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3254 /// to here in AddInitializerToDecl. We can't check them before the initializer
3255 /// is attached.
3256 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3257                              bool MergeTypeWithOld) {
3258   if (New->isInvalidDecl() || Old->isInvalidDecl())
3259     return;
3260
3261   QualType MergedT;
3262   if (getLangOpts().CPlusPlus) {
3263     if (New->getType()->isUndeducedType()) {
3264       // We don't know what the new type is until the initializer is attached.
3265       return;
3266     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3267       // These could still be something that needs exception specs checked.
3268       return MergeVarDeclExceptionSpecs(New, Old);
3269     }
3270     // C++ [basic.link]p10:
3271     //   [...] the types specified by all declarations referring to a given
3272     //   object or function shall be identical, except that declarations for an
3273     //   array object can specify array types that differ by the presence or
3274     //   absence of a major array bound (8.3.4).
3275     else if (Old->getType()->isIncompleteArrayType() &&
3276              New->getType()->isArrayType()) {
3277       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3278       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3279       if (Context.hasSameType(OldArray->getElementType(),
3280                               NewArray->getElementType()))
3281         MergedT = New->getType();
3282     } else if (Old->getType()->isArrayType() &&
3283                New->getType()->isIncompleteArrayType()) {
3284       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3285       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3286       if (Context.hasSameType(OldArray->getElementType(),
3287                               NewArray->getElementType()))
3288         MergedT = Old->getType();
3289     } else if (New->getType()->isObjCObjectPointerType() &&
3290                Old->getType()->isObjCObjectPointerType()) {
3291       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3292                                               Old->getType());
3293     }
3294   } else {
3295     // C 6.2.7p2:
3296     //   All declarations that refer to the same object or function shall have
3297     //   compatible type.
3298     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3299   }
3300   if (MergedT.isNull()) {
3301     // It's OK if we couldn't merge types if either type is dependent, for a
3302     // block-scope variable. In other cases (static data members of class
3303     // templates, variable templates, ...), we require the types to be
3304     // equivalent.
3305     // FIXME: The C++ standard doesn't say anything about this.
3306     if ((New->getType()->isDependentType() ||
3307          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3308       // If the old type was dependent, we can't merge with it, so the new type
3309       // becomes dependent for now. We'll reproduce the original type when we
3310       // instantiate the TypeSourceInfo for the variable.
3311       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3312         New->setType(Context.DependentTy);
3313       return;
3314     }
3315
3316     // FIXME: Even if this merging succeeds, some other non-visible declaration
3317     // of this variable might have an incompatible type. For instance:
3318     //
3319     //   extern int arr[];
3320     //   void f() { extern int arr[2]; }
3321     //   void g() { extern int arr[3]; }
3322     //
3323     // Neither C nor C++ requires a diagnostic for this, but we should still try
3324     // to diagnose it.
3325     Diag(New->getLocation(), New->isThisDeclarationADefinition()
3326                                  ? diag::err_redefinition_different_type
3327                                  : diag::err_redeclaration_different_type)
3328         << New->getDeclName() << New->getType() << Old->getType();
3329
3330     diag::kind PrevDiag;
3331     SourceLocation OldLocation;
3332     std::tie(PrevDiag, OldLocation) =
3333         getNoteDiagForInvalidRedeclaration(Old, New);
3334     Diag(OldLocation, PrevDiag);
3335     return New->setInvalidDecl();
3336   }
3337
3338   // Don't actually update the type on the new declaration if the old
3339   // declaration was an extern declaration in a different scope.
3340   if (MergeTypeWithOld)
3341     New->setType(MergedT);
3342 }
3343
3344 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3345                                   LookupResult &Previous) {
3346   // C11 6.2.7p4:
3347   //   For an identifier with internal or external linkage declared
3348   //   in a scope in which a prior declaration of that identifier is
3349   //   visible, if the prior declaration specifies internal or
3350   //   external linkage, the type of the identifier at the later
3351   //   declaration becomes the composite type.
3352   //
3353   // If the variable isn't visible, we do not merge with its type.
3354   if (Previous.isShadowed())
3355     return false;
3356
3357   if (S.getLangOpts().CPlusPlus) {
3358     // C++11 [dcl.array]p3:
3359     //   If there is a preceding declaration of the entity in the same
3360     //   scope in which the bound was specified, an omitted array bound
3361     //   is taken to be the same as in that earlier declaration.
3362     return NewVD->isPreviousDeclInSameBlockScope() ||
3363            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3364             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3365   } else {
3366     // If the old declaration was function-local, don't merge with its
3367     // type unless we're in the same function.
3368     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3369            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3370   }
3371 }
3372
3373 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3374 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3375 /// situation, merging decls or emitting diagnostics as appropriate.
3376 ///
3377 /// Tentative definition rules (C99 6.9.2p2) are checked by
3378 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3379 /// definitions here, since the initializer hasn't been attached.
3380 ///
3381 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3382   // If the new decl is already invalid, don't do any other checking.
3383   if (New->isInvalidDecl())
3384     return;
3385
3386   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3387     return;
3388
3389   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3390
3391   // Verify the old decl was also a variable or variable template.
3392   VarDecl *Old = nullptr;
3393   VarTemplateDecl *OldTemplate = nullptr;
3394   if (Previous.isSingleResult()) {
3395     if (NewTemplate) {
3396       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3397       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3398
3399       if (auto *Shadow =
3400               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3401         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3402           return New->setInvalidDecl();
3403     } else {
3404       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3405
3406       if (auto *Shadow =
3407               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3408         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3409           return New->setInvalidDecl();
3410     }
3411   }
3412   if (!Old) {
3413     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3414       << New->getDeclName();
3415     Diag(Previous.getRepresentativeDecl()->getLocation(),
3416          diag::note_previous_definition);
3417     return New->setInvalidDecl();
3418   }
3419
3420   // Ensure the template parameters are compatible.
3421   if (NewTemplate &&
3422       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3423                                       OldTemplate->getTemplateParameters(),
3424                                       /*Complain=*/true, TPL_TemplateMatch))
3425     return New->setInvalidDecl();
3426
3427   // C++ [class.mem]p1:
3428   //   A member shall not be declared twice in the member-specification [...]
3429   // 
3430   // Here, we need only consider static data members.
3431   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3432     Diag(New->getLocation(), diag::err_duplicate_member) 
3433       << New->getIdentifier();
3434     Diag(Old->getLocation(), diag::note_previous_declaration);
3435     New->setInvalidDecl();
3436   }
3437   
3438   mergeDeclAttributes(New, Old);
3439   // Warn if an already-declared variable is made a weak_import in a subsequent 
3440   // declaration
3441   if (New->hasAttr<WeakImportAttr>() &&
3442       Old->getStorageClass() == SC_None &&
3443       !Old->hasAttr<WeakImportAttr>()) {
3444     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3445     Diag(Old->getLocation(), diag::note_previous_definition);
3446     // Remove weak_import attribute on new declaration.
3447     New->dropAttr<WeakImportAttr>();
3448   }
3449
3450   if (New->hasAttr<InternalLinkageAttr>() &&
3451       !Old->hasAttr<InternalLinkageAttr>()) {
3452     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3453         << New->getDeclName();
3454     Diag(Old->getLocation(), diag::note_previous_definition);
3455     New->dropAttr<InternalLinkageAttr>();
3456   }
3457
3458   // Merge the types.
3459   VarDecl *MostRecent = Old->getMostRecentDecl();
3460   if (MostRecent != Old) {
3461     MergeVarDeclTypes(New, MostRecent,
3462                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3463     if (New->isInvalidDecl())
3464       return;
3465   }
3466
3467   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3468   if (New->isInvalidDecl())
3469     return;
3470
3471   diag::kind PrevDiag;
3472   SourceLocation OldLocation;
3473   std::tie(PrevDiag, OldLocation) =
3474       getNoteDiagForInvalidRedeclaration(Old, New);
3475
3476   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3477   if (New->getStorageClass() == SC_Static &&
3478       !New->isStaticDataMember() &&
3479       Old->hasExternalFormalLinkage()) {
3480     if (getLangOpts().MicrosoftExt) {
3481       Diag(New->getLocation(), diag::ext_static_non_static)
3482           << New->getDeclName();
3483       Diag(OldLocation, PrevDiag);
3484     } else {
3485       Diag(New->getLocation(), diag::err_static_non_static)
3486           << New->getDeclName();
3487       Diag(OldLocation, PrevDiag);
3488       return New->setInvalidDecl();
3489     }
3490   }
3491   // C99 6.2.2p4:
3492   //   For an identifier declared with the storage-class specifier
3493   //   extern in a scope in which a prior declaration of that
3494   //   identifier is visible,23) if the prior declaration specifies
3495   //   internal or external linkage, the linkage of the identifier at
3496   //   the later declaration is the same as the linkage specified at
3497   //   the prior declaration. If no prior declaration is visible, or
3498   //   if the prior declaration specifies no linkage, then the
3499   //   identifier has external linkage.
3500   if (New->hasExternalStorage() && Old->hasLinkage())
3501     /* Okay */;
3502   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3503            !New->isStaticDataMember() &&
3504            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3505     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3506     Diag(OldLocation, PrevDiag);
3507     return New->setInvalidDecl();
3508   }
3509
3510   // Check if extern is followed by non-extern and vice-versa.
3511   if (New->hasExternalStorage() &&
3512       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3513     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3514     Diag(OldLocation, PrevDiag);
3515     return New->setInvalidDecl();
3516   }
3517   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3518       !New->hasExternalStorage()) {
3519     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3520     Diag(OldLocation, PrevDiag);
3521     return New->setInvalidDecl();
3522   }
3523
3524   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3525
3526   // FIXME: The test for external storage here seems wrong? We still
3527   // need to check for mismatches.
3528   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3529       // Don't complain about out-of-line definitions of static members.
3530       !(Old->getLexicalDeclContext()->isRecord() &&
3531         !New->getLexicalDeclContext()->isRecord())) {
3532     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3533     Diag(OldLocation, PrevDiag);
3534     return New->setInvalidDecl();
3535   }
3536
3537   if (New->getTLSKind() != Old->getTLSKind()) {
3538     if (!Old->getTLSKind()) {
3539       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3540       Diag(OldLocation, PrevDiag);
3541     } else if (!New->getTLSKind()) {
3542       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3543       Diag(OldLocation, PrevDiag);
3544     } else {
3545       // Do not allow redeclaration to change the variable between requiring
3546       // static and dynamic initialization.
3547       // FIXME: GCC allows this, but uses the TLS keyword on the first
3548       // declaration to determine the kind. Do we need to be compatible here?
3549       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3550         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3551       Diag(OldLocation, PrevDiag);
3552     }
3553   }
3554
3555   // C++ doesn't have tentative definitions, so go right ahead and check here.
3556   VarDecl *Def;
3557   if (getLangOpts().CPlusPlus &&
3558       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3559       (Def = Old->getDefinition())) {
3560     NamedDecl *Hidden = nullptr;
3561     if (!hasVisibleDefinition(Def, &Hidden) &&
3562         (New->getFormalLinkage() == InternalLinkage ||
3563          New->getDescribedVarTemplate() ||
3564          New->getNumTemplateParameterLists() ||
3565          New->getDeclContext()->isDependentContext())) {
3566       // The previous definition is hidden, and multiple definitions are
3567       // permitted (in separate TUs). Form another definition of it.
3568     } else {
3569       Diag(New->getLocation(), diag::err_redefinition) << New;
3570       Diag(Def->getLocation(), diag::note_previous_definition);
3571       New->setInvalidDecl();
3572       return;
3573     }
3574   }
3575
3576   if (haveIncompatibleLanguageLinkages(Old, New)) {
3577     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3578     Diag(OldLocation, PrevDiag);
3579     New->setInvalidDecl();
3580     return;
3581   }
3582
3583   // Merge "used" flag.
3584   if (Old->getMostRecentDecl()->isUsed(false))
3585     New->setIsUsed();
3586
3587   // Keep a chain of previous declarations.
3588   New->setPreviousDecl(Old);
3589   if (NewTemplate)
3590     NewTemplate->setPreviousDecl(OldTemplate);
3591
3592   // Inherit access appropriately.
3593   New->setAccess(Old->getAccess());
3594   if (NewTemplate)
3595     NewTemplate->setAccess(New->getAccess());
3596 }
3597
3598 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3599 /// no declarator (e.g. "struct foo;") is parsed.
3600 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3601                                        DeclSpec &DS) {
3602   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3603 }
3604
3605 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3606 // disambiguate entities defined in different scopes.
3607 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3608 // compatibility.
3609 // We will pick our mangling number depending on which version of MSVC is being
3610 // targeted.
3611 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3612   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3613              ? S->getMSCurManglingNumber()
3614              : S->getMSLastManglingNumber();
3615 }
3616
3617 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3618   if (!Context.getLangOpts().CPlusPlus)
3619     return;
3620
3621   if (isa<CXXRecordDecl>(Tag->getParent())) {
3622     // If this tag is the direct child of a class, number it if
3623     // it is anonymous.
3624     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3625       return;
3626     MangleNumberingContext &MCtx =
3627         Context.getManglingNumberContext(Tag->getParent());
3628     Context.setManglingNumber(
3629         Tag, MCtx.getManglingNumber(
3630                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3631     return;
3632   }
3633
3634   // If this tag isn't a direct child of a class, number it if it is local.
3635   Decl *ManglingContextDecl;
3636   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3637           Tag->getDeclContext(), ManglingContextDecl)) {
3638     Context.setManglingNumber(
3639         Tag, MCtx->getManglingNumber(
3640                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3641   }
3642 }
3643
3644 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3645                                         TypedefNameDecl *NewTD) {
3646   if (TagFromDeclSpec->isInvalidDecl())
3647     return;
3648
3649   // Do nothing if the tag already has a name for linkage purposes.
3650   if (TagFromDeclSpec->hasNameForLinkage())
3651     return;
3652
3653   // A well-formed anonymous tag must always be a TUK_Definition.
3654   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3655
3656   // The type must match the tag exactly;  no qualifiers allowed.
3657   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3658                            Context.getTagDeclType(TagFromDeclSpec))) {
3659     if (getLangOpts().CPlusPlus)
3660       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3661     return;
3662   }
3663
3664   // If we've already computed linkage for the anonymous tag, then
3665   // adding a typedef name for the anonymous decl can change that
3666   // linkage, which might be a serious problem.  Diagnose this as
3667   // unsupported and ignore the typedef name.  TODO: we should
3668   // pursue this as a language defect and establish a formal rule
3669   // for how to handle it.
3670   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3671     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3672
3673     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3674     tagLoc = getLocForEndOfToken(tagLoc);
3675
3676     llvm::SmallString<40> textToInsert;
3677     textToInsert += ' ';
3678     textToInsert += NewTD->getIdentifier()->getName();
3679     Diag(tagLoc, diag::note_typedef_changes_linkage)
3680         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3681     return;
3682   }
3683
3684   // Otherwise, set this is the anon-decl typedef for the tag.
3685   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3686 }
3687
3688 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3689   switch (T) {
3690   case DeclSpec::TST_class:
3691     return 0;
3692   case DeclSpec::TST_struct:
3693     return 1;
3694   case DeclSpec::TST_interface:
3695     return 2;
3696   case DeclSpec::TST_union:
3697     return 3;
3698   case DeclSpec::TST_enum:
3699     return 4;
3700   default:
3701     llvm_unreachable("unexpected type specifier");
3702   }
3703 }
3704
3705 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3706 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3707 /// parameters to cope with template friend declarations.
3708 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3709                                        DeclSpec &DS,
3710                                        MultiTemplateParamsArg TemplateParams,
3711                                        bool IsExplicitInstantiation) {
3712   Decl *TagD = nullptr;
3713   TagDecl *Tag = nullptr;
3714   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3715       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3716       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3717       DS.getTypeSpecType() == DeclSpec::TST_union ||
3718       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3719     TagD = DS.getRepAsDecl();
3720
3721     if (!TagD) // We probably had an error
3722       return nullptr;
3723
3724     // Note that the above type specs guarantee that the
3725     // type rep is a Decl, whereas in many of the others
3726     // it's a Type.
3727     if (isa<TagDecl>(TagD))
3728       Tag = cast<TagDecl>(TagD);
3729     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3730       Tag = CTD->getTemplatedDecl();
3731   }
3732
3733   if (Tag) {
3734     handleTagNumbering(Tag, S);
3735     Tag->setFreeStanding();
3736     if (Tag->isInvalidDecl())
3737       return Tag;
3738   }
3739
3740   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3741     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3742     // or incomplete types shall not be restrict-qualified."
3743     if (TypeQuals & DeclSpec::TQ_restrict)
3744       Diag(DS.getRestrictSpecLoc(),
3745            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3746            << DS.getSourceRange();
3747   }
3748
3749   if (DS.isConstexprSpecified()) {
3750     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3751     // and definitions of functions and variables.
3752     if (Tag)
3753       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3754           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3755     else
3756       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3757     // Don't emit warnings after this error.
3758     return TagD;
3759   }
3760
3761   if (DS.isConceptSpecified()) {
3762     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3763     // either a function concept and its definition or a variable concept and
3764     // its initializer.
3765     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3766     return TagD;
3767   }
3768
3769   DiagnoseFunctionSpecifiers(DS);
3770
3771   if (DS.isFriendSpecified()) {
3772     // If we're dealing with a decl but not a TagDecl, assume that
3773     // whatever routines created it handled the friendship aspect.
3774     if (TagD && !Tag)
3775       return nullptr;
3776     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3777   }
3778
3779   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3780   bool IsExplicitSpecialization =
3781     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3782   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3783       !IsExplicitInstantiation && !IsExplicitSpecialization) {
3784     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3785     // nested-name-specifier unless it is an explicit instantiation
3786     // or an explicit specialization.
3787     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3788     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3789         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3790     return nullptr;
3791   }
3792
3793   // Track whether this decl-specifier declares anything.
3794   bool DeclaresAnything = true;
3795
3796   // Handle anonymous struct definitions.
3797   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3798     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3799         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3800       if (getLangOpts().CPlusPlus ||
3801           Record->getDeclContext()->isRecord())
3802         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3803                                            Context.getPrintingPolicy());
3804
3805       DeclaresAnything = false;
3806     }
3807   }
3808
3809   // C11 6.7.2.1p2:
3810   //   A struct-declaration that does not declare an anonymous structure or
3811   //   anonymous union shall contain a struct-declarator-list.
3812   //
3813   // This rule also existed in C89 and C99; the grammar for struct-declaration
3814   // did not permit a struct-declaration without a struct-declarator-list.
3815   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3816       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3817     // Check for Microsoft C extension: anonymous struct/union member.
3818     // Handle 2 kinds of anonymous struct/union:
3819     //   struct STRUCT;
3820     //   union UNION;
3821     // and
3822     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3823     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3824     if ((Tag && Tag->getDeclName()) ||
3825         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3826       RecordDecl *Record = nullptr;
3827       if (Tag)
3828         Record = dyn_cast<RecordDecl>(Tag);
3829       else if (const RecordType *RT =
3830                    DS.getRepAsType().get()->getAsStructureType())
3831         Record = RT->getDecl();
3832       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3833         Record = UT->getDecl();
3834
3835       if (Record && getLangOpts().MicrosoftExt) {
3836         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3837           << Record->isUnion() << DS.getSourceRange();
3838         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3839       }
3840
3841       DeclaresAnything = false;
3842     }
3843   }
3844
3845   // Skip all the checks below if we have a type error.
3846   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3847       (TagD && TagD->isInvalidDecl()))
3848     return TagD;
3849
3850   if (getLangOpts().CPlusPlus &&
3851       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3852     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3853       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3854           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3855         DeclaresAnything = false;
3856
3857   if (!DS.isMissingDeclaratorOk()) {
3858     // Customize diagnostic for a typedef missing a name.
3859     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3860       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3861         << DS.getSourceRange();
3862     else
3863       DeclaresAnything = false;
3864   }
3865
3866   if (DS.isModulePrivateSpecified() &&
3867       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3868     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3869       << Tag->getTagKind()
3870       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3871
3872   ActOnDocumentableDecl(TagD);
3873
3874   // C 6.7/2:
3875   //   A declaration [...] shall declare at least a declarator [...], a tag,
3876   //   or the members of an enumeration.
3877   // C++ [dcl.dcl]p3:
3878   //   [If there are no declarators], and except for the declaration of an
3879   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3880   //   names into the program, or shall redeclare a name introduced by a
3881   //   previous declaration.
3882   if (!DeclaresAnything) {
3883     // In C, we allow this as a (popular) extension / bug. Don't bother
3884     // producing further diagnostics for redundant qualifiers after this.
3885     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3886     return TagD;
3887   }
3888
3889   // C++ [dcl.stc]p1:
3890   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3891   //   init-declarator-list of the declaration shall not be empty.
3892   // C++ [dcl.fct.spec]p1:
3893   //   If a cv-qualifier appears in a decl-specifier-seq, the
3894   //   init-declarator-list of the declaration shall not be empty.
3895   //
3896   // Spurious qualifiers here appear to be valid in C.
3897   unsigned DiagID = diag::warn_standalone_specifier;
3898   if (getLangOpts().CPlusPlus)
3899     DiagID = diag::ext_standalone_specifier;
3900
3901   // Note that a linkage-specification sets a storage class, but
3902   // 'extern "C" struct foo;' is actually valid and not theoretically
3903   // useless.
3904   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3905     if (SCS == DeclSpec::SCS_mutable)
3906       // Since mutable is not a viable storage class specifier in C, there is
3907       // no reason to treat it as an extension. Instead, diagnose as an error.
3908       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3909     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3910       Diag(DS.getStorageClassSpecLoc(), DiagID)
3911         << DeclSpec::getSpecifierName(SCS);
3912   }
3913
3914   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3915     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3916       << DeclSpec::getSpecifierName(TSCS);
3917   if (DS.getTypeQualifiers()) {
3918     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3919       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3920     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3921       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3922     // Restrict is covered above.
3923     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3924       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3925   }
3926
3927   // Warn about ignored type attributes, for example:
3928   // __attribute__((aligned)) struct A;
3929   // Attributes should be placed after tag to apply to type declaration.
3930   if (!DS.getAttributes().empty()) {
3931     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3932     if (TypeSpecType == DeclSpec::TST_class ||
3933         TypeSpecType == DeclSpec::TST_struct ||
3934         TypeSpecType == DeclSpec::TST_interface ||
3935         TypeSpecType == DeclSpec::TST_union ||
3936         TypeSpecType == DeclSpec::TST_enum) {
3937       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
3938            attrs = attrs->getNext())
3939         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3940             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
3941     }
3942   }
3943
3944   return TagD;
3945 }
3946
3947 /// We are trying to inject an anonymous member into the given scope;
3948 /// check if there's an existing declaration that can't be overloaded.
3949 ///
3950 /// \return true if this is a forbidden redeclaration
3951 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3952                                          Scope *S,
3953                                          DeclContext *Owner,
3954                                          DeclarationName Name,
3955                                          SourceLocation NameLoc,
3956                                          bool IsUnion) {
3957   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3958                  Sema::ForRedeclaration);
3959   if (!SemaRef.LookupName(R, S)) return false;
3960
3961   if (R.getAsSingle<TagDecl>())
3962     return false;
3963
3964   // Pick a representative declaration.
3965   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3966   assert(PrevDecl && "Expected a non-null Decl");
3967
3968   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3969     return false;
3970
3971   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
3972     << IsUnion << Name;
3973   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3974
3975   return true;
3976 }
3977
3978 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3979 /// anonymous struct or union AnonRecord into the owning context Owner
3980 /// and scope S. This routine will be invoked just after we realize
3981 /// that an unnamed union or struct is actually an anonymous union or
3982 /// struct, e.g.,
3983 ///
3984 /// @code
3985 /// union {
3986 ///   int i;
3987 ///   float f;
3988 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3989 ///    // f into the surrounding scope.x
3990 /// @endcode
3991 ///
3992 /// This routine is recursive, injecting the names of nested anonymous
3993 /// structs/unions into the owning context and scope as well.
3994 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3995                                          DeclContext *Owner,
3996                                          RecordDecl *AnonRecord,
3997                                          AccessSpecifier AS,
3998                                          SmallVectorImpl<NamedDecl *> &Chaining,
3999                                          bool MSAnonStruct) {
4000   bool Invalid = false;
4001
4002   // Look every FieldDecl and IndirectFieldDecl with a name.
4003   for (auto *D : AnonRecord->decls()) {
4004     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4005         cast<NamedDecl>(D)->getDeclName()) {
4006       ValueDecl *VD = cast<ValueDecl>(D);
4007       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4008                                        VD->getLocation(),
4009                                        AnonRecord->isUnion())) {
4010         // C++ [class.union]p2:
4011         //   The names of the members of an anonymous union shall be
4012         //   distinct from the names of any other entity in the
4013         //   scope in which the anonymous union is declared.
4014         Invalid = true;
4015       } else {
4016         // C++ [class.union]p2:
4017         //   For the purpose of name lookup, after the anonymous union
4018         //   definition, the members of the anonymous union are
4019         //   considered to have been defined in the scope in which the
4020         //   anonymous union is declared.
4021         unsigned OldChainingSize = Chaining.size();
4022         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4023           Chaining.append(IF->chain_begin(), IF->chain_end());
4024         else
4025           Chaining.push_back(VD);
4026
4027         assert(Chaining.size() >= 2);
4028         NamedDecl **NamedChain =
4029           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4030         for (unsigned i = 0; i < Chaining.size(); i++)
4031           NamedChain[i] = Chaining[i];
4032
4033         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4034             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4035             VD->getType(), NamedChain, Chaining.size());
4036
4037         for (const auto *Attr : VD->attrs())
4038           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4039
4040         IndirectField->setAccess(AS);
4041         IndirectField->setImplicit();
4042         SemaRef.PushOnScopeChains(IndirectField, S);
4043
4044         // That includes picking up the appropriate access specifier.
4045         if (AS != AS_none) IndirectField->setAccess(AS);
4046
4047         Chaining.resize(OldChainingSize);
4048       }
4049     }
4050   }
4051
4052   return Invalid;
4053 }
4054
4055 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4056 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4057 /// illegal input values are mapped to SC_None.
4058 static StorageClass
4059 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4060   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4061   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4062          "Parser allowed 'typedef' as storage class VarDecl.");
4063   switch (StorageClassSpec) {
4064   case DeclSpec::SCS_unspecified:    return SC_None;
4065   case DeclSpec::SCS_extern:
4066     if (DS.isExternInLinkageSpec())
4067       return SC_None;
4068     return SC_Extern;
4069   case DeclSpec::SCS_static:         return SC_Static;
4070   case DeclSpec::SCS_auto:           return SC_Auto;
4071   case DeclSpec::SCS_register:       return SC_Register;
4072   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4073     // Illegal SCSs map to None: error reporting is up to the caller.
4074   case DeclSpec::SCS_mutable:        // Fall through.
4075   case DeclSpec::SCS_typedef:        return SC_None;
4076   }
4077   llvm_unreachable("unknown storage class specifier");
4078 }
4079
4080 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4081   assert(Record->hasInClassInitializer());
4082
4083   for (const auto *I : Record->decls()) {
4084     const auto *FD = dyn_cast<FieldDecl>(I);
4085     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4086       FD = IFD->getAnonField();
4087     if (FD && FD->hasInClassInitializer())
4088       return FD->getLocation();
4089   }
4090
4091   llvm_unreachable("couldn't find in-class initializer");
4092 }
4093
4094 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4095                                       SourceLocation DefaultInitLoc) {
4096   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4097     return;
4098
4099   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4100   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4101 }
4102
4103 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4104                                       CXXRecordDecl *AnonUnion) {
4105   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4106     return;
4107
4108   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4109 }
4110
4111 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4112 /// anonymous structure or union. Anonymous unions are a C++ feature
4113 /// (C++ [class.union]) and a C11 feature; anonymous structures
4114 /// are a C11 feature and GNU C++ extension.
4115 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4116                                         AccessSpecifier AS,
4117                                         RecordDecl *Record,
4118                                         const PrintingPolicy &Policy) {
4119   DeclContext *Owner = Record->getDeclContext();
4120
4121   // Diagnose whether this anonymous struct/union is an extension.
4122   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4123     Diag(Record->getLocation(), diag::ext_anonymous_union);
4124   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4125     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4126   else if (!Record->isUnion() && !getLangOpts().C11)
4127     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4128
4129   // C and C++ require different kinds of checks for anonymous
4130   // structs/unions.
4131   bool Invalid = false;
4132   if (getLangOpts().CPlusPlus) {
4133     const char *PrevSpec = nullptr;
4134     unsigned DiagID;
4135     if (Record->isUnion()) {
4136       // C++ [class.union]p6:
4137       //   Anonymous unions declared in a named namespace or in the
4138       //   global namespace shall be declared static.
4139       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4140           (isa<TranslationUnitDecl>(Owner) ||
4141            (isa<NamespaceDecl>(Owner) &&
4142             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4143         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4144           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4145   
4146         // Recover by adding 'static'.
4147         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4148                                PrevSpec, DiagID, Policy);
4149       }
4150       // C++ [class.union]p6:
4151       //   A storage class is not allowed in a declaration of an
4152       //   anonymous union in a class scope.
4153       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4154                isa<RecordDecl>(Owner)) {
4155         Diag(DS.getStorageClassSpecLoc(),
4156              diag::err_anonymous_union_with_storage_spec)
4157           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4158   
4159         // Recover by removing the storage specifier.
4160         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 
4161                                SourceLocation(),
4162                                PrevSpec, DiagID, Context.getPrintingPolicy());
4163       }
4164     }
4165
4166     // Ignore const/volatile/restrict qualifiers.
4167     if (DS.getTypeQualifiers()) {
4168       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4169         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4170           << Record->isUnion() << "const"
4171           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4172       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4173         Diag(DS.getVolatileSpecLoc(),
4174              diag::ext_anonymous_struct_union_qualified)
4175           << Record->isUnion() << "volatile"
4176           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4177       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4178         Diag(DS.getRestrictSpecLoc(),
4179              diag::ext_anonymous_struct_union_qualified)
4180           << Record->isUnion() << "restrict"
4181           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4182       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4183         Diag(DS.getAtomicSpecLoc(),
4184              diag::ext_anonymous_struct_union_qualified)
4185           << Record->isUnion() << "_Atomic"
4186           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4187
4188       DS.ClearTypeQualifiers();
4189     }
4190
4191     // C++ [class.union]p2:
4192     //   The member-specification of an anonymous union shall only
4193     //   define non-static data members. [Note: nested types and
4194     //   functions cannot be declared within an anonymous union. ]
4195     for (auto *Mem : Record->decls()) {
4196       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4197         // C++ [class.union]p3:
4198         //   An anonymous union shall not have private or protected
4199         //   members (clause 11).
4200         assert(FD->getAccess() != AS_none);
4201         if (FD->getAccess() != AS_public) {
4202           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4203             << Record->isUnion() << (FD->getAccess() == AS_protected);
4204           Invalid = true;
4205         }
4206
4207         // C++ [class.union]p1
4208         //   An object of a class with a non-trivial constructor, a non-trivial
4209         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4210         //   assignment operator cannot be a member of a union, nor can an
4211         //   array of such objects.
4212         if (CheckNontrivialField(FD))
4213           Invalid = true;
4214       } else if (Mem->isImplicit()) {
4215         // Any implicit members are fine.
4216       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4217         // This is a type that showed up in an
4218         // elaborated-type-specifier inside the anonymous struct or
4219         // union, but which actually declares a type outside of the
4220         // anonymous struct or union. It's okay.
4221       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4222         if (!MemRecord->isAnonymousStructOrUnion() &&
4223             MemRecord->getDeclName()) {
4224           // Visual C++ allows type definition in anonymous struct or union.
4225           if (getLangOpts().MicrosoftExt)
4226             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4227               << Record->isUnion();
4228           else {
4229             // This is a nested type declaration.
4230             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4231               << Record->isUnion();
4232             Invalid = true;
4233           }
4234         } else {
4235           // This is an anonymous type definition within another anonymous type.
4236           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4237           // not part of standard C++.
4238           Diag(MemRecord->getLocation(),
4239                diag::ext_anonymous_record_with_anonymous_type)
4240             << Record->isUnion();
4241         }
4242       } else if (isa<AccessSpecDecl>(Mem)) {
4243         // Any access specifier is fine.
4244       } else if (isa<StaticAssertDecl>(Mem)) {
4245         // In C++1z, static_assert declarations are also fine.
4246       } else {
4247         // We have something that isn't a non-static data
4248         // member. Complain about it.
4249         unsigned DK = diag::err_anonymous_record_bad_member;
4250         if (isa<TypeDecl>(Mem))
4251           DK = diag::err_anonymous_record_with_type;
4252         else if (isa<FunctionDecl>(Mem))
4253           DK = diag::err_anonymous_record_with_function;
4254         else if (isa<VarDecl>(Mem))
4255           DK = diag::err_anonymous_record_with_static;
4256         
4257         // Visual C++ allows type definition in anonymous struct or union.
4258         if (getLangOpts().MicrosoftExt &&
4259             DK == diag::err_anonymous_record_with_type)
4260           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4261             << Record->isUnion();
4262         else {
4263           Diag(Mem->getLocation(), DK) << Record->isUnion();
4264           Invalid = true;
4265         }
4266       }
4267     }
4268
4269     // C++11 [class.union]p8 (DR1460):
4270     //   At most one variant member of a union may have a
4271     //   brace-or-equal-initializer.
4272     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4273         Owner->isRecord())
4274       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4275                                 cast<CXXRecordDecl>(Record));
4276   }
4277
4278   if (!Record->isUnion() && !Owner->isRecord()) {
4279     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4280       << getLangOpts().CPlusPlus;
4281     Invalid = true;
4282   }
4283
4284   // Mock up a declarator.
4285   Declarator Dc(DS, Declarator::MemberContext);
4286   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4287   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4288
4289   // Create a declaration for this anonymous struct/union.
4290   NamedDecl *Anon = nullptr;
4291   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4292     Anon = FieldDecl::Create(Context, OwningClass,
4293                              DS.getLocStart(),
4294                              Record->getLocation(),
4295                              /*IdentifierInfo=*/nullptr,
4296                              Context.getTypeDeclType(Record),
4297                              TInfo,
4298                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4299                              /*InitStyle=*/ICIS_NoInit);
4300     Anon->setAccess(AS);
4301     if (getLangOpts().CPlusPlus)
4302       FieldCollector->Add(cast<FieldDecl>(Anon));
4303   } else {
4304     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4305     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4306     if (SCSpec == DeclSpec::SCS_mutable) {
4307       // mutable can only appear on non-static class members, so it's always
4308       // an error here
4309       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4310       Invalid = true;
4311       SC = SC_None;
4312     }
4313
4314     Anon = VarDecl::Create(Context, Owner,
4315                            DS.getLocStart(),
4316                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4317                            Context.getTypeDeclType(Record),
4318                            TInfo, SC);
4319
4320     // Default-initialize the implicit variable. This initialization will be
4321     // trivial in almost all cases, except if a union member has an in-class
4322     // initializer:
4323     //   union { int n = 0; };
4324     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4325   }
4326   Anon->setImplicit();
4327
4328   // Mark this as an anonymous struct/union type.
4329   Record->setAnonymousStructOrUnion(true);
4330
4331   // Add the anonymous struct/union object to the current
4332   // context. We'll be referencing this object when we refer to one of
4333   // its members.
4334   Owner->addDecl(Anon);
4335
4336   // Inject the members of the anonymous struct/union into the owning
4337   // context and into the identifier resolver chain for name lookup
4338   // purposes.
4339   SmallVector<NamedDecl*, 2> Chain;
4340   Chain.push_back(Anon);
4341
4342   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
4343                                           Chain, false))
4344     Invalid = true;
4345
4346   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4347     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4348       Decl *ManglingContextDecl;
4349       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4350               NewVD->getDeclContext(), ManglingContextDecl)) {
4351         Context.setManglingNumber(
4352             NewVD, MCtx->getManglingNumber(
4353                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4354         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4355       }
4356     }
4357   }
4358
4359   if (Invalid)
4360     Anon->setInvalidDecl();
4361
4362   return Anon;
4363 }
4364
4365 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4366 /// Microsoft C anonymous structure.
4367 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4368 /// Example:
4369 ///
4370 /// struct A { int a; };
4371 /// struct B { struct A; int b; };
4372 ///
4373 /// void foo() {
4374 ///   B var;
4375 ///   var.a = 3;
4376 /// }
4377 ///
4378 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4379                                            RecordDecl *Record) {
4380   assert(Record && "expected a record!");
4381
4382   // Mock up a declarator.
4383   Declarator Dc(DS, Declarator::TypeNameContext);
4384   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4385   assert(TInfo && "couldn't build declarator info for anonymous struct");
4386
4387   auto *ParentDecl = cast<RecordDecl>(CurContext);
4388   QualType RecTy = Context.getTypeDeclType(Record);
4389
4390   // Create a declaration for this anonymous struct.
4391   NamedDecl *Anon = FieldDecl::Create(Context,
4392                              ParentDecl,
4393                              DS.getLocStart(),
4394                              DS.getLocStart(),
4395                              /*IdentifierInfo=*/nullptr,
4396                              RecTy,
4397                              TInfo,
4398                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4399                              /*InitStyle=*/ICIS_NoInit);
4400   Anon->setImplicit();
4401
4402   // Add the anonymous struct object to the current context.
4403   CurContext->addDecl(Anon);
4404
4405   // Inject the members of the anonymous struct into the current
4406   // context and into the identifier resolver chain for name lookup
4407   // purposes.
4408   SmallVector<NamedDecl*, 2> Chain;
4409   Chain.push_back(Anon);
4410
4411   RecordDecl *RecordDef = Record->getDefinition();
4412   if (RequireCompleteType(Anon->getLocation(), RecTy,
4413                           diag::err_field_incomplete) ||
4414       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4415                                           AS_none, Chain, true)) {
4416     Anon->setInvalidDecl();
4417     ParentDecl->setInvalidDecl();
4418   }
4419
4420   return Anon;
4421 }
4422
4423 /// GetNameForDeclarator - Determine the full declaration name for the
4424 /// given Declarator.
4425 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4426   return GetNameFromUnqualifiedId(D.getName());
4427 }
4428
4429 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4430 DeclarationNameInfo
4431 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4432   DeclarationNameInfo NameInfo;
4433   NameInfo.setLoc(Name.StartLocation);
4434
4435   switch (Name.getKind()) {
4436
4437   case UnqualifiedId::IK_ImplicitSelfParam:
4438   case UnqualifiedId::IK_Identifier:
4439     NameInfo.setName(Name.Identifier);
4440     NameInfo.setLoc(Name.StartLocation);
4441     return NameInfo;
4442
4443   case UnqualifiedId::IK_OperatorFunctionId:
4444     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4445                                            Name.OperatorFunctionId.Operator));
4446     NameInfo.setLoc(Name.StartLocation);
4447     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4448       = Name.OperatorFunctionId.SymbolLocations[0];
4449     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4450       = Name.EndLocation.getRawEncoding();
4451     return NameInfo;
4452
4453   case UnqualifiedId::IK_LiteralOperatorId:
4454     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4455                                                            Name.Identifier));
4456     NameInfo.setLoc(Name.StartLocation);
4457     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4458     return NameInfo;
4459
4460   case UnqualifiedId::IK_ConversionFunctionId: {
4461     TypeSourceInfo *TInfo;
4462     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4463     if (Ty.isNull())
4464       return DeclarationNameInfo();
4465     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4466                                                Context.getCanonicalType(Ty)));
4467     NameInfo.setLoc(Name.StartLocation);
4468     NameInfo.setNamedTypeInfo(TInfo);
4469     return NameInfo;
4470   }
4471
4472   case UnqualifiedId::IK_ConstructorName: {
4473     TypeSourceInfo *TInfo;
4474     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4475     if (Ty.isNull())
4476       return DeclarationNameInfo();
4477     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4478                                               Context.getCanonicalType(Ty)));
4479     NameInfo.setLoc(Name.StartLocation);
4480     NameInfo.setNamedTypeInfo(TInfo);
4481     return NameInfo;
4482   }
4483
4484   case UnqualifiedId::IK_ConstructorTemplateId: {
4485     // In well-formed code, we can only have a constructor
4486     // template-id that refers to the current context, so go there
4487     // to find the actual type being constructed.
4488     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4489     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4490       return DeclarationNameInfo();
4491
4492     // Determine the type of the class being constructed.
4493     QualType CurClassType = Context.getTypeDeclType(CurClass);
4494
4495     // FIXME: Check two things: that the template-id names the same type as
4496     // CurClassType, and that the template-id does not occur when the name
4497     // was qualified.
4498
4499     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4500                                     Context.getCanonicalType(CurClassType)));
4501     NameInfo.setLoc(Name.StartLocation);
4502     // FIXME: should we retrieve TypeSourceInfo?
4503     NameInfo.setNamedTypeInfo(nullptr);
4504     return NameInfo;
4505   }
4506
4507   case UnqualifiedId::IK_DestructorName: {
4508     TypeSourceInfo *TInfo;
4509     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4510     if (Ty.isNull())
4511       return DeclarationNameInfo();
4512     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4513                                               Context.getCanonicalType(Ty)));
4514     NameInfo.setLoc(Name.StartLocation);
4515     NameInfo.setNamedTypeInfo(TInfo);
4516     return NameInfo;
4517   }
4518
4519   case UnqualifiedId::IK_TemplateId: {
4520     TemplateName TName = Name.TemplateId->Template.get();
4521     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4522     return Context.getNameForTemplate(TName, TNameLoc);
4523   }
4524
4525   } // switch (Name.getKind())
4526
4527   llvm_unreachable("Unknown name kind");
4528 }
4529
4530 static QualType getCoreType(QualType Ty) {
4531   do {
4532     if (Ty->isPointerType() || Ty->isReferenceType())
4533       Ty = Ty->getPointeeType();
4534     else if (Ty->isArrayType())
4535       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4536     else
4537       return Ty.withoutLocalFastQualifiers();
4538   } while (true);
4539 }
4540
4541 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4542 /// and Definition have "nearly" matching parameters. This heuristic is
4543 /// used to improve diagnostics in the case where an out-of-line function
4544 /// definition doesn't match any declaration within the class or namespace.
4545 /// Also sets Params to the list of indices to the parameters that differ
4546 /// between the declaration and the definition. If hasSimilarParameters
4547 /// returns true and Params is empty, then all of the parameters match.
4548 static bool hasSimilarParameters(ASTContext &Context,
4549                                      FunctionDecl *Declaration,
4550                                      FunctionDecl *Definition,
4551                                      SmallVectorImpl<unsigned> &Params) {
4552   Params.clear();
4553   if (Declaration->param_size() != Definition->param_size())
4554     return false;
4555   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4556     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4557     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4558
4559     // The parameter types are identical
4560     if (Context.hasSameType(DefParamTy, DeclParamTy))
4561       continue;
4562
4563     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4564     QualType DefParamBaseTy = getCoreType(DefParamTy);
4565     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4566     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4567
4568     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4569         (DeclTyName && DeclTyName == DefTyName))
4570       Params.push_back(Idx);
4571     else  // The two parameters aren't even close
4572       return false;
4573   }
4574
4575   return true;
4576 }
4577
4578 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4579 /// declarator needs to be rebuilt in the current instantiation.
4580 /// Any bits of declarator which appear before the name are valid for
4581 /// consideration here.  That's specifically the type in the decl spec
4582 /// and the base type in any member-pointer chunks.
4583 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4584                                                     DeclarationName Name) {
4585   // The types we specifically need to rebuild are:
4586   //   - typenames, typeofs, and decltypes
4587   //   - types which will become injected class names
4588   // Of course, we also need to rebuild any type referencing such a
4589   // type.  It's safest to just say "dependent", but we call out a
4590   // few cases here.
4591
4592   DeclSpec &DS = D.getMutableDeclSpec();
4593   switch (DS.getTypeSpecType()) {
4594   case DeclSpec::TST_typename:
4595   case DeclSpec::TST_typeofType:
4596   case DeclSpec::TST_underlyingType:
4597   case DeclSpec::TST_atomic: {
4598     // Grab the type from the parser.
4599     TypeSourceInfo *TSI = nullptr;
4600     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4601     if (T.isNull() || !T->isDependentType()) break;
4602
4603     // Make sure there's a type source info.  This isn't really much
4604     // of a waste; most dependent types should have type source info
4605     // attached already.
4606     if (!TSI)
4607       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4608
4609     // Rebuild the type in the current instantiation.
4610     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4611     if (!TSI) return true;
4612
4613     // Store the new type back in the decl spec.
4614     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4615     DS.UpdateTypeRep(LocType);
4616     break;
4617   }
4618
4619   case DeclSpec::TST_decltype:
4620   case DeclSpec::TST_typeofExpr: {
4621     Expr *E = DS.getRepAsExpr();
4622     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4623     if (Result.isInvalid()) return true;
4624     DS.UpdateExprRep(Result.get());
4625     break;
4626   }
4627
4628   default:
4629     // Nothing to do for these decl specs.
4630     break;
4631   }
4632
4633   // It doesn't matter what order we do this in.
4634   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4635     DeclaratorChunk &Chunk = D.getTypeObject(I);
4636
4637     // The only type information in the declarator which can come
4638     // before the declaration name is the base type of a member
4639     // pointer.
4640     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4641       continue;
4642
4643     // Rebuild the scope specifier in-place.
4644     CXXScopeSpec &SS = Chunk.Mem.Scope();
4645     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4646       return true;
4647   }
4648
4649   return false;
4650 }
4651
4652 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4653   D.setFunctionDefinitionKind(FDK_Declaration);
4654   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4655
4656   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4657       Dcl && Dcl->getDeclContext()->isFileContext())
4658     Dcl->setTopLevelDeclInObjCContainer();
4659
4660   return Dcl;
4661 }
4662
4663 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4664 ///   If T is the name of a class, then each of the following shall have a 
4665 ///   name different from T:
4666 ///     - every static data member of class T;
4667 ///     - every member function of class T
4668 ///     - every member of class T that is itself a type;
4669 /// \returns true if the declaration name violates these rules.
4670 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4671                                    DeclarationNameInfo NameInfo) {
4672   DeclarationName Name = NameInfo.getName();
4673
4674   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 
4675     if (Record->getIdentifier() && Record->getDeclName() == Name) {
4676       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4677       return true;
4678     }
4679
4680   return false;
4681 }
4682
4683 /// \brief Diagnose a declaration whose declarator-id has the given 
4684 /// nested-name-specifier.
4685 ///
4686 /// \param SS The nested-name-specifier of the declarator-id.
4687 ///
4688 /// \param DC The declaration context to which the nested-name-specifier 
4689 /// resolves.
4690 ///
4691 /// \param Name The name of the entity being declared.
4692 ///
4693 /// \param Loc The location of the name of the entity being declared.
4694 ///
4695 /// \returns true if we cannot safely recover from this error, false otherwise.
4696 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4697                                         DeclarationName Name,
4698                                         SourceLocation Loc) {
4699   DeclContext *Cur = CurContext;
4700   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4701     Cur = Cur->getParent();
4702
4703   // If the user provided a superfluous scope specifier that refers back to the
4704   // class in which the entity is already declared, diagnose and ignore it.
4705   //
4706   // class X {
4707   //   void X::f();
4708   // };
4709   //
4710   // Note, it was once ill-formed to give redundant qualification in all
4711   // contexts, but that rule was removed by DR482.
4712   if (Cur->Equals(DC)) {
4713     if (Cur->isRecord()) {
4714       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4715                                       : diag::err_member_extra_qualification)
4716         << Name << FixItHint::CreateRemoval(SS.getRange());
4717       SS.clear();
4718     } else {
4719       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4720     }
4721     return false;
4722   }
4723
4724   // Check whether the qualifying scope encloses the scope of the original
4725   // declaration.
4726   if (!Cur->Encloses(DC)) {
4727     if (Cur->isRecord())
4728       Diag(Loc, diag::err_member_qualification)
4729         << Name << SS.getRange();
4730     else if (isa<TranslationUnitDecl>(DC))
4731       Diag(Loc, diag::err_invalid_declarator_global_scope)
4732         << Name << SS.getRange();
4733     else if (isa<FunctionDecl>(Cur))
4734       Diag(Loc, diag::err_invalid_declarator_in_function) 
4735         << Name << SS.getRange();
4736     else if (isa<BlockDecl>(Cur))
4737       Diag(Loc, diag::err_invalid_declarator_in_block) 
4738         << Name << SS.getRange();
4739     else
4740       Diag(Loc, diag::err_invalid_declarator_scope)
4741       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4742     
4743     return true;
4744   }
4745
4746   if (Cur->isRecord()) {
4747     // Cannot qualify members within a class.
4748     Diag(Loc, diag::err_member_qualification)
4749       << Name << SS.getRange();
4750     SS.clear();
4751     
4752     // C++ constructors and destructors with incorrect scopes can break
4753     // our AST invariants by having the wrong underlying types. If
4754     // that's the case, then drop this declaration entirely.
4755     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4756          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4757         !Context.hasSameType(Name.getCXXNameType(),
4758                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4759       return true;
4760     
4761     return false;
4762   }
4763   
4764   // C++11 [dcl.meaning]p1:
4765   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4766   //   not begin with a decltype-specifer"
4767   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4768   while (SpecLoc.getPrefix())
4769     SpecLoc = SpecLoc.getPrefix();
4770   if (dyn_cast_or_null<DecltypeType>(
4771         SpecLoc.getNestedNameSpecifier()->getAsType()))
4772     Diag(Loc, diag::err_decltype_in_declarator)
4773       << SpecLoc.getTypeLoc().getSourceRange();
4774
4775   return false;
4776 }
4777
4778 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4779                                   MultiTemplateParamsArg TemplateParamLists) {
4780   // TODO: consider using NameInfo for diagnostic.
4781   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4782   DeclarationName Name = NameInfo.getName();
4783
4784   // All of these full declarators require an identifier.  If it doesn't have
4785   // one, the ParsedFreeStandingDeclSpec action should be used.
4786   if (!Name) {
4787     if (!D.isInvalidType())  // Reject this if we think it is valid.
4788       Diag(D.getDeclSpec().getLocStart(),
4789            diag::err_declarator_need_ident)
4790         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4791     return nullptr;
4792   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4793     return nullptr;
4794
4795   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4796   // we find one that is.
4797   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4798          (S->getFlags() & Scope::TemplateParamScope) != 0)
4799     S = S->getParent();
4800
4801   DeclContext *DC = CurContext;
4802   if (D.getCXXScopeSpec().isInvalid())
4803     D.setInvalidType();
4804   else if (D.getCXXScopeSpec().isSet()) {
4805     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 
4806                                         UPPC_DeclarationQualifier))
4807       return nullptr;
4808
4809     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4810     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4811     if (!DC || isa<EnumDecl>(DC)) {
4812       // If we could not compute the declaration context, it's because the
4813       // declaration context is dependent but does not refer to a class,
4814       // class template, or class template partial specialization. Complain
4815       // and return early, to avoid the coming semantic disaster.
4816       Diag(D.getIdentifierLoc(),
4817            diag::err_template_qualified_declarator_no_match)
4818         << D.getCXXScopeSpec().getScopeRep()
4819         << D.getCXXScopeSpec().getRange();
4820       return nullptr;
4821     }
4822     bool IsDependentContext = DC->isDependentContext();
4823
4824     if (!IsDependentContext && 
4825         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4826       return nullptr;
4827
4828     // If a class is incomplete, do not parse entities inside it.
4829     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4830       Diag(D.getIdentifierLoc(),
4831            diag::err_member_def_undefined_record)
4832         << Name << DC << D.getCXXScopeSpec().getRange();
4833       return nullptr;
4834     }
4835     if (!D.getDeclSpec().isFriendSpecified()) {
4836       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4837                                       Name, D.getIdentifierLoc())) {
4838         if (DC->isRecord())
4839           return nullptr;
4840
4841         D.setInvalidType();
4842       }
4843     }
4844
4845     // Check whether we need to rebuild the type of the given
4846     // declaration in the current instantiation.
4847     if (EnteringContext && IsDependentContext &&
4848         TemplateParamLists.size() != 0) {
4849       ContextRAII SavedContext(*this, DC);
4850       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4851         D.setInvalidType();
4852     }
4853   }
4854
4855   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4856   QualType R = TInfo->getType();
4857
4858   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4859     // If this is a typedef, we'll end up spewing multiple diagnostics.
4860     // Just return early; it's safer. If this is a function, let the
4861     // "constructor cannot have a return type" diagnostic handle it.
4862     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4863       return nullptr;
4864
4865   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4866                                       UPPC_DeclarationType))
4867     D.setInvalidType();
4868
4869   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4870                         ForRedeclaration);
4871
4872   // See if this is a redefinition of a variable in the same scope.
4873   if (!D.getCXXScopeSpec().isSet()) {
4874     bool IsLinkageLookup = false;
4875     bool CreateBuiltins = false;
4876
4877     // If the declaration we're planning to build will be a function
4878     // or object with linkage, then look for another declaration with
4879     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4880     //
4881     // If the declaration we're planning to build will be declared with
4882     // external linkage in the translation unit, create any builtin with
4883     // the same name.
4884     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4885       /* Do nothing*/;
4886     else if (CurContext->isFunctionOrMethod() &&
4887              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4888               R->isFunctionType())) {
4889       IsLinkageLookup = true;
4890       CreateBuiltins =
4891           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4892     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4893                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4894       CreateBuiltins = true;
4895
4896     if (IsLinkageLookup)
4897       Previous.clear(LookupRedeclarationWithLinkage);
4898
4899     LookupName(Previous, S, CreateBuiltins);
4900   } else { // Something like "int foo::x;"
4901     LookupQualifiedName(Previous, DC);
4902
4903     // C++ [dcl.meaning]p1:
4904     //   When the declarator-id is qualified, the declaration shall refer to a 
4905     //  previously declared member of the class or namespace to which the 
4906     //  qualifier refers (or, in the case of a namespace, of an element of the
4907     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4908     //  thereof; [...] 
4909     //
4910     // Note that we already checked the context above, and that we do not have
4911     // enough information to make sure that Previous contains the declaration
4912     // we want to match. For example, given:
4913     //
4914     //   class X {
4915     //     void f();
4916     //     void f(float);
4917     //   };
4918     //
4919     //   void X::f(int) { } // ill-formed
4920     //
4921     // In this case, Previous will point to the overload set
4922     // containing the two f's declared in X, but neither of them
4923     // matches.
4924     
4925     // C++ [dcl.meaning]p1:
4926     //   [...] the member shall not merely have been introduced by a 
4927     //   using-declaration in the scope of the class or namespace nominated by 
4928     //   the nested-name-specifier of the declarator-id.
4929     RemoveUsingDecls(Previous);
4930   }
4931
4932   if (Previous.isSingleResult() &&
4933       Previous.getFoundDecl()->isTemplateParameter()) {
4934     // Maybe we will complain about the shadowed template parameter.
4935     if (!D.isInvalidType())
4936       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4937                                       Previous.getFoundDecl());
4938
4939     // Just pretend that we didn't see the previous declaration.
4940     Previous.clear();
4941   }
4942
4943   // In C++, the previous declaration we find might be a tag type
4944   // (class or enum). In this case, the new declaration will hide the
4945   // tag type. Note that this does does not apply if we're declaring a
4946   // typedef (C++ [dcl.typedef]p4).
4947   if (Previous.isSingleTagDecl() &&
4948       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4949     Previous.clear();
4950
4951   // Check that there are no default arguments other than in the parameters
4952   // of a function declaration (C++ only).
4953   if (getLangOpts().CPlusPlus)
4954     CheckExtraCXXDefaultArguments(D);
4955
4956   if (D.getDeclSpec().isConceptSpecified()) {
4957     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
4958     // applied only to the definition of a function template or variable
4959     // template, declared in namespace scope
4960     if (!TemplateParamLists.size()) {
4961       Diag(D.getDeclSpec().getConceptSpecLoc(),
4962            diag:: err_concept_wrong_decl_kind);
4963       return nullptr;
4964     }
4965
4966     if (!DC->getRedeclContext()->isFileContext()) {
4967       Diag(D.getIdentifierLoc(),
4968            diag::err_concept_decls_may_only_appear_in_namespace_scope);
4969       return nullptr;
4970     }
4971   }
4972
4973   NamedDecl *New;
4974
4975   bool AddToScope = true;
4976   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4977     if (TemplateParamLists.size()) {
4978       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4979       return nullptr;
4980     }
4981
4982     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4983   } else if (R->isFunctionType()) {
4984     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4985                                   TemplateParamLists,
4986                                   AddToScope);
4987   } else {
4988     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4989                                   AddToScope);
4990   }
4991
4992   if (!New)
4993     return nullptr;
4994
4995   // If this has an identifier and is not an invalid redeclaration or 
4996   // function template specialization, add it to the scope stack.
4997   if (New->getDeclName() && AddToScope &&
4998        !(D.isRedeclaration() && New->isInvalidDecl())) {
4999     // Only make a locally-scoped extern declaration visible if it is the first
5000     // declaration of this entity. Qualified lookup for such an entity should
5001     // only find this declaration if there is no visible declaration of it.
5002     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5003     PushOnScopeChains(New, S, AddToContext);
5004     if (!AddToContext)
5005       CurContext->addHiddenDecl(New);
5006   }
5007
5008   return New;
5009 }
5010
5011 /// Helper method to turn variable array types into constant array
5012 /// types in certain situations which would otherwise be errors (for
5013 /// GCC compatibility).
5014 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5015                                                     ASTContext &Context,
5016                                                     bool &SizeIsNegative,
5017                                                     llvm::APSInt &Oversized) {
5018   // This method tries to turn a variable array into a constant
5019   // array even when the size isn't an ICE.  This is necessary
5020   // for compatibility with code that depends on gcc's buggy
5021   // constant expression folding, like struct {char x[(int)(char*)2];}
5022   SizeIsNegative = false;
5023   Oversized = 0;
5024   
5025   if (T->isDependentType())
5026     return QualType();
5027   
5028   QualifierCollector Qs;
5029   const Type *Ty = Qs.strip(T);
5030
5031   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5032     QualType Pointee = PTy->getPointeeType();
5033     QualType FixedType =
5034         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5035                                             Oversized);
5036     if (FixedType.isNull()) return FixedType;
5037     FixedType = Context.getPointerType(FixedType);
5038     return Qs.apply(Context, FixedType);
5039   }
5040   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5041     QualType Inner = PTy->getInnerType();
5042     QualType FixedType =
5043         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5044                                             Oversized);
5045     if (FixedType.isNull()) return FixedType;
5046     FixedType = Context.getParenType(FixedType);
5047     return Qs.apply(Context, FixedType);
5048   }
5049
5050   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5051   if (!VLATy)
5052     return QualType();
5053   // FIXME: We should probably handle this case
5054   if (VLATy->getElementType()->isVariablyModifiedType())
5055     return QualType();
5056
5057   llvm::APSInt Res;
5058   if (!VLATy->getSizeExpr() ||
5059       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5060     return QualType();
5061
5062   // Check whether the array size is negative.
5063   if (Res.isSigned() && Res.isNegative()) {
5064     SizeIsNegative = true;
5065     return QualType();
5066   }
5067
5068   // Check whether the array is too large to be addressed.
5069   unsigned ActiveSizeBits
5070     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5071                                               Res);
5072   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5073     Oversized = Res;
5074     return QualType();
5075   }
5076   
5077   return Context.getConstantArrayType(VLATy->getElementType(),
5078                                       Res, ArrayType::Normal, 0);
5079 }
5080
5081 static void
5082 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5083   SrcTL = SrcTL.getUnqualifiedLoc();
5084   DstTL = DstTL.getUnqualifiedLoc();
5085   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5086     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5087     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5088                                       DstPTL.getPointeeLoc());
5089     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5090     return;
5091   }
5092   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5093     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5094     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5095                                       DstPTL.getInnerLoc());
5096     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5097     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5098     return;
5099   }
5100   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5101   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5102   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5103   TypeLoc DstElemTL = DstATL.getElementLoc();
5104   DstElemTL.initializeFullCopy(SrcElemTL);
5105   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5106   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5107   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5108 }
5109
5110 /// Helper method to turn variable array types into constant array
5111 /// types in certain situations which would otherwise be errors (for
5112 /// GCC compatibility).
5113 static TypeSourceInfo*
5114 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5115                                               ASTContext &Context,
5116                                               bool &SizeIsNegative,
5117                                               llvm::APSInt &Oversized) {
5118   QualType FixedTy
5119     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5120                                           SizeIsNegative, Oversized);
5121   if (FixedTy.isNull())
5122     return nullptr;
5123   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5124   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5125                                     FixedTInfo->getTypeLoc());
5126   return FixedTInfo;
5127 }
5128
5129 /// \brief Register the given locally-scoped extern "C" declaration so
5130 /// that it can be found later for redeclarations. We include any extern "C"
5131 /// declaration that is not visible in the translation unit here, not just
5132 /// function-scope declarations.
5133 void
5134 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5135   if (!getLangOpts().CPlusPlus &&
5136       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5137     // Don't need to track declarations in the TU in C.
5138     return;
5139
5140   // Note that we have a locally-scoped external with this name.
5141   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5142 }
5143
5144 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5145   // FIXME: We can have multiple results via __attribute__((overloadable)).
5146   auto Result = Context.getExternCContextDecl()->lookup(Name);
5147   return Result.empty() ? nullptr : *Result.begin();
5148 }
5149
5150 /// \brief Diagnose function specifiers on a declaration of an identifier that
5151 /// does not identify a function.
5152 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5153   // FIXME: We should probably indicate the identifier in question to avoid
5154   // confusion for constructs like "inline int a(), b;"
5155   if (DS.isInlineSpecified())
5156     Diag(DS.getInlineSpecLoc(),
5157          diag::err_inline_non_function);
5158
5159   if (DS.isVirtualSpecified())
5160     Diag(DS.getVirtualSpecLoc(),
5161          diag::err_virtual_non_function);
5162
5163   if (DS.isExplicitSpecified())
5164     Diag(DS.getExplicitSpecLoc(),
5165          diag::err_explicit_non_function);
5166
5167   if (DS.isNoreturnSpecified())
5168     Diag(DS.getNoreturnSpecLoc(),
5169          diag::err_noreturn_non_function);
5170 }
5171
5172 NamedDecl*
5173 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5174                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5175   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5176   if (D.getCXXScopeSpec().isSet()) {
5177     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5178       << D.getCXXScopeSpec().getRange();
5179     D.setInvalidType();
5180     // Pretend we didn't see the scope specifier.
5181     DC = CurContext;
5182     Previous.clear();
5183   }
5184
5185   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5186
5187   if (D.getDeclSpec().isConstexprSpecified())
5188     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5189       << 1;
5190   if (D.getDeclSpec().isConceptSpecified())
5191     Diag(D.getDeclSpec().getConceptSpecLoc(),
5192          diag::err_concept_wrong_decl_kind);
5193
5194   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5195     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5196       << D.getName().getSourceRange();
5197     return nullptr;
5198   }
5199
5200   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5201   if (!NewTD) return nullptr;
5202
5203   // Handle attributes prior to checking for duplicates in MergeVarDecl
5204   ProcessDeclAttributes(S, NewTD, D);
5205
5206   CheckTypedefForVariablyModifiedType(S, NewTD);
5207
5208   bool Redeclaration = D.isRedeclaration();
5209   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5210   D.setRedeclaration(Redeclaration);
5211   return ND;
5212 }
5213
5214 void
5215 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5216   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5217   // then it shall have block scope.
5218   // Note that variably modified types must be fixed before merging the decl so
5219   // that redeclarations will match.
5220   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5221   QualType T = TInfo->getType();
5222   if (T->isVariablyModifiedType()) {
5223     getCurFunction()->setHasBranchProtectedScope();
5224
5225     if (S->getFnParent() == nullptr) {
5226       bool SizeIsNegative;
5227       llvm::APSInt Oversized;
5228       TypeSourceInfo *FixedTInfo =
5229         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5230                                                       SizeIsNegative,
5231                                                       Oversized);
5232       if (FixedTInfo) {
5233         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5234         NewTD->setTypeSourceInfo(FixedTInfo);
5235       } else {
5236         if (SizeIsNegative)
5237           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5238         else if (T->isVariableArrayType())
5239           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5240         else if (Oversized.getBoolValue())
5241           Diag(NewTD->getLocation(), diag::err_array_too_large) 
5242             << Oversized.toString(10);
5243         else
5244           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5245         NewTD->setInvalidDecl();
5246       }
5247     }
5248   }
5249 }
5250
5251
5252 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5253 /// declares a typedef-name, either using the 'typedef' type specifier or via
5254 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5255 NamedDecl*
5256 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5257                            LookupResult &Previous, bool &Redeclaration) {
5258   // Merge the decl with the existing one if appropriate. If the decl is
5259   // in an outer scope, it isn't the same thing.
5260   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5261                        /*AllowInlineNamespace*/false);
5262   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5263   if (!Previous.empty()) {
5264     Redeclaration = true;
5265     MergeTypedefNameDecl(S, NewTD, Previous);
5266   }
5267
5268   // If this is the C FILE type, notify the AST context.
5269   if (IdentifierInfo *II = NewTD->getIdentifier())
5270     if (!NewTD->isInvalidDecl() &&
5271         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5272       if (II->isStr("FILE"))
5273         Context.setFILEDecl(NewTD);
5274       else if (II->isStr("jmp_buf"))
5275         Context.setjmp_bufDecl(NewTD);
5276       else if (II->isStr("sigjmp_buf"))
5277         Context.setsigjmp_bufDecl(NewTD);
5278       else if (II->isStr("ucontext_t"))
5279         Context.setucontext_tDecl(NewTD);
5280     }
5281
5282   return NewTD;
5283 }
5284
5285 /// \brief Determines whether the given declaration is an out-of-scope
5286 /// previous declaration.
5287 ///
5288 /// This routine should be invoked when name lookup has found a
5289 /// previous declaration (PrevDecl) that is not in the scope where a
5290 /// new declaration by the same name is being introduced. If the new
5291 /// declaration occurs in a local scope, previous declarations with
5292 /// linkage may still be considered previous declarations (C99
5293 /// 6.2.2p4-5, C++ [basic.link]p6).
5294 ///
5295 /// \param PrevDecl the previous declaration found by name
5296 /// lookup
5297 ///
5298 /// \param DC the context in which the new declaration is being
5299 /// declared.
5300 ///
5301 /// \returns true if PrevDecl is an out-of-scope previous declaration
5302 /// for a new delcaration with the same name.
5303 static bool
5304 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5305                                 ASTContext &Context) {
5306   if (!PrevDecl)
5307     return false;
5308
5309   if (!PrevDecl->hasLinkage())
5310     return false;
5311
5312   if (Context.getLangOpts().CPlusPlus) {
5313     // C++ [basic.link]p6:
5314     //   If there is a visible declaration of an entity with linkage
5315     //   having the same name and type, ignoring entities declared
5316     //   outside the innermost enclosing namespace scope, the block
5317     //   scope declaration declares that same entity and receives the
5318     //   linkage of the previous declaration.
5319     DeclContext *OuterContext = DC->getRedeclContext();
5320     if (!OuterContext->isFunctionOrMethod())
5321       // This rule only applies to block-scope declarations.
5322       return false;
5323     
5324     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5325     if (PrevOuterContext->isRecord())
5326       // We found a member function: ignore it.
5327       return false;
5328     
5329     // Find the innermost enclosing namespace for the new and
5330     // previous declarations.
5331     OuterContext = OuterContext->getEnclosingNamespaceContext();
5332     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5333
5334     // The previous declaration is in a different namespace, so it
5335     // isn't the same function.
5336     if (!OuterContext->Equals(PrevOuterContext))
5337       return false;
5338   }
5339
5340   return true;
5341 }
5342
5343 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5344   CXXScopeSpec &SS = D.getCXXScopeSpec();
5345   if (!SS.isSet()) return;
5346   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5347 }
5348
5349 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5350   QualType type = decl->getType();
5351   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5352   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5353     // Various kinds of declaration aren't allowed to be __autoreleasing.
5354     unsigned kind = -1U;
5355     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5356       if (var->hasAttr<BlocksAttr>())
5357         kind = 0; // __block
5358       else if (!var->hasLocalStorage())
5359         kind = 1; // global
5360     } else if (isa<ObjCIvarDecl>(decl)) {
5361       kind = 3; // ivar
5362     } else if (isa<FieldDecl>(decl)) {
5363       kind = 2; // field
5364     }
5365
5366     if (kind != -1U) {
5367       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5368         << kind;
5369     }
5370   } else if (lifetime == Qualifiers::OCL_None) {
5371     // Try to infer lifetime.
5372     if (!type->isObjCLifetimeType())
5373       return false;
5374
5375     lifetime = type->getObjCARCImplicitLifetime();
5376     type = Context.getLifetimeQualifiedType(type, lifetime);
5377     decl->setType(type);
5378   }
5379   
5380   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5381     // Thread-local variables cannot have lifetime.
5382     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5383         var->getTLSKind()) {
5384       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5385         << var->getType();
5386       return true;
5387     }
5388   }
5389   
5390   return false;
5391 }
5392
5393 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5394   // Ensure that an auto decl is deduced otherwise the checks below might cache
5395   // the wrong linkage.
5396   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5397
5398   // 'weak' only applies to declarations with external linkage.
5399   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5400     if (!ND.isExternallyVisible()) {
5401       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5402       ND.dropAttr<WeakAttr>();
5403     }
5404   }
5405   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5406     if (ND.isExternallyVisible()) {
5407       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5408       ND.dropAttr<WeakRefAttr>();
5409       ND.dropAttr<AliasAttr>();
5410     }
5411   }
5412
5413   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5414     if (VD->hasInit()) {
5415       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5416         assert(VD->isThisDeclarationADefinition() &&
5417                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5418         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
5419         VD->dropAttr<AliasAttr>();
5420       }
5421     }
5422   }
5423
5424   // 'selectany' only applies to externally visible variable declarations.
5425   // It does not apply to functions.
5426   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5427     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5428       S.Diag(Attr->getLocation(),
5429              diag::err_attribute_selectany_non_extern_data);
5430       ND.dropAttr<SelectAnyAttr>();
5431     }
5432   }
5433
5434   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5435     // dll attributes require external linkage. Static locals may have external
5436     // linkage but still cannot be explicitly imported or exported.
5437     auto *VD = dyn_cast<VarDecl>(&ND);
5438     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5439       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5440         << &ND << Attr;
5441       ND.setInvalidDecl();
5442     }
5443   }
5444
5445   // Virtual functions cannot be marked as 'notail'.
5446   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5447     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5448       if (MD->isVirtual()) {
5449         S.Diag(ND.getLocation(),
5450                diag::err_invalid_attribute_on_virtual_function)
5451             << Attr;
5452         ND.dropAttr<NotTailCalledAttr>();
5453       }
5454 }
5455
5456 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5457                                            NamedDecl *NewDecl,
5458                                            bool IsSpecialization) {
5459   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5460     OldDecl = OldTD->getTemplatedDecl();
5461   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5462     NewDecl = NewTD->getTemplatedDecl();
5463
5464   if (!OldDecl || !NewDecl)
5465     return;
5466
5467   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5468   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5469   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5470   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5471
5472   // dllimport and dllexport are inheritable attributes so we have to exclude
5473   // inherited attribute instances.
5474   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5475                     (NewExportAttr && !NewExportAttr->isInherited());
5476
5477   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5478   // the only exception being explicit specializations.
5479   // Implicitly generated declarations are also excluded for now because there
5480   // is no other way to switch these to use dllimport or dllexport.
5481   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5482
5483   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5484     // Allow with a warning for free functions and global variables.
5485     bool JustWarn = false;
5486     if (!OldDecl->isCXXClassMember()) {
5487       auto *VD = dyn_cast<VarDecl>(OldDecl);
5488       if (VD && !VD->getDescribedVarTemplate())
5489         JustWarn = true;
5490       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5491       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5492         JustWarn = true;
5493     }
5494
5495     // We cannot change a declaration that's been used because IR has already
5496     // been emitted. Dllimported functions will still work though (modulo
5497     // address equality) as they can use the thunk.
5498     if (OldDecl->isUsed())
5499       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5500         JustWarn = false;
5501
5502     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5503                                : diag::err_attribute_dll_redeclaration;
5504     S.Diag(NewDecl->getLocation(), DiagID)
5505         << NewDecl
5506         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5507     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5508     if (!JustWarn) {
5509       NewDecl->setInvalidDecl();
5510       return;
5511     }
5512   }
5513
5514   // A redeclaration is not allowed to drop a dllimport attribute, the only
5515   // exceptions being inline function definitions, local extern declarations,
5516   // and qualified friend declarations.
5517   // NB: MSVC converts such a declaration to dllexport.
5518   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5519   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5520     // Ignore static data because out-of-line definitions are diagnosed
5521     // separately.
5522     IsStaticDataMember = VD->isStaticDataMember();
5523   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5524     IsInline = FD->isInlined();
5525     IsQualifiedFriend = FD->getQualifier() &&
5526                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5527   }
5528
5529   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5530       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5531     S.Diag(NewDecl->getLocation(),
5532            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5533       << NewDecl << OldImportAttr;
5534     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5535     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5536     OldDecl->dropAttr<DLLImportAttr>();
5537     NewDecl->dropAttr<DLLImportAttr>();
5538   } else if (IsInline && OldImportAttr &&
5539              !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5540     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5541     OldDecl->dropAttr<DLLImportAttr>();
5542     NewDecl->dropAttr<DLLImportAttr>();
5543     S.Diag(NewDecl->getLocation(),
5544            diag::warn_dllimport_dropped_from_inline_function)
5545         << NewDecl << OldImportAttr;
5546   }
5547 }
5548
5549 /// Given that we are within the definition of the given function,
5550 /// will that definition behave like C99's 'inline', where the
5551 /// definition is discarded except for optimization purposes?
5552 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5553   // Try to avoid calling GetGVALinkageForFunction.
5554
5555   // All cases of this require the 'inline' keyword.
5556   if (!FD->isInlined()) return false;
5557
5558   // This is only possible in C++ with the gnu_inline attribute.
5559   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5560     return false;
5561
5562   // Okay, go ahead and call the relatively-more-expensive function.
5563
5564 #ifndef NDEBUG
5565   // AST quite reasonably asserts that it's working on a function
5566   // definition.  We don't really have a way to tell it that we're
5567   // currently defining the function, so just lie to it in +Asserts
5568   // builds.  This is an awful hack.
5569   FD->setLazyBody(1);
5570 #endif
5571
5572   bool isC99Inline =
5573       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5574
5575 #ifndef NDEBUG
5576   FD->setLazyBody(0);
5577 #endif
5578
5579   return isC99Inline;
5580 }
5581
5582 /// Determine whether a variable is extern "C" prior to attaching
5583 /// an initializer. We can't just call isExternC() here, because that
5584 /// will also compute and cache whether the declaration is externally
5585 /// visible, which might change when we attach the initializer.
5586 ///
5587 /// This can only be used if the declaration is known to not be a
5588 /// redeclaration of an internal linkage declaration.
5589 ///
5590 /// For instance:
5591 ///
5592 ///   auto x = []{};
5593 ///
5594 /// Attaching the initializer here makes this declaration not externally
5595 /// visible, because its type has internal linkage.
5596 ///
5597 /// FIXME: This is a hack.
5598 template<typename T>
5599 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5600   if (S.getLangOpts().CPlusPlus) {
5601     // In C++, the overloadable attribute negates the effects of extern "C".
5602     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5603       return false;
5604
5605     // So do CUDA's host/device attributes if overloading is enabled.
5606     if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
5607         (D->template hasAttr<CUDADeviceAttr>() ||
5608          D->template hasAttr<CUDAHostAttr>()))
5609       return false;
5610   }
5611   return D->isExternC();
5612 }
5613
5614 static bool shouldConsiderLinkage(const VarDecl *VD) {
5615   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5616   if (DC->isFunctionOrMethod())
5617     return VD->hasExternalStorage();
5618   if (DC->isFileContext())
5619     return true;
5620   if (DC->isRecord())
5621     return false;
5622   llvm_unreachable("Unexpected context");
5623 }
5624
5625 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5626   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5627   if (DC->isFileContext() || DC->isFunctionOrMethod())
5628     return true;
5629   if (DC->isRecord())
5630     return false;
5631   llvm_unreachable("Unexpected context");
5632 }
5633
5634 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5635                           AttributeList::Kind Kind) {
5636   for (const AttributeList *L = AttrList; L; L = L->getNext())
5637     if (L->getKind() == Kind)
5638       return true;
5639   return false;
5640 }
5641
5642 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5643                           AttributeList::Kind Kind) {
5644   // Check decl attributes on the DeclSpec.
5645   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5646     return true;
5647
5648   // Walk the declarator structure, checking decl attributes that were in a type
5649   // position to the decl itself.
5650   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5651     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5652       return true;
5653   }
5654
5655   // Finally, check attributes on the decl itself.
5656   return hasParsedAttr(S, PD.getAttributes(), Kind);
5657 }
5658
5659 /// Adjust the \c DeclContext for a function or variable that might be a
5660 /// function-local external declaration.
5661 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5662   if (!DC->isFunctionOrMethod())
5663     return false;
5664
5665   // If this is a local extern function or variable declared within a function
5666   // template, don't add it into the enclosing namespace scope until it is
5667   // instantiated; it might have a dependent type right now.
5668   if (DC->isDependentContext())
5669     return true;
5670
5671   // C++11 [basic.link]p7:
5672   //   When a block scope declaration of an entity with linkage is not found to
5673   //   refer to some other declaration, then that entity is a member of the
5674   //   innermost enclosing namespace.
5675   //
5676   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5677   // semantically-enclosing namespace, not a lexically-enclosing one.
5678   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5679     DC = DC->getParent();
5680   return true;
5681 }
5682
5683 /// \brief Returns true if given declaration has external C language linkage.
5684 static bool isDeclExternC(const Decl *D) {
5685   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5686     return FD->isExternC();
5687   if (const auto *VD = dyn_cast<VarDecl>(D))
5688     return VD->isExternC();
5689
5690   llvm_unreachable("Unknown type of decl!");
5691 }
5692
5693 NamedDecl *
5694 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5695                               TypeSourceInfo *TInfo, LookupResult &Previous,
5696                               MultiTemplateParamsArg TemplateParamLists,
5697                               bool &AddToScope) {
5698   QualType R = TInfo->getType();
5699   DeclarationName Name = GetNameForDeclarator(D).getName();
5700
5701   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5702   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5703
5704   // dllimport globals without explicit storage class are treated as extern. We
5705   // have to change the storage class this early to get the right DeclContext.
5706   if (SC == SC_None && !DC->isRecord() &&
5707       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5708       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5709     SC = SC_Extern;
5710
5711   DeclContext *OriginalDC = DC;
5712   bool IsLocalExternDecl = SC == SC_Extern &&
5713                            adjustContextForLocalExternDecl(DC);
5714
5715   if (getLangOpts().OpenCL) {
5716     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5717     QualType NR = R;
5718     while (NR->isPointerType()) {
5719       if (NR->isFunctionPointerType()) {
5720         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5721         D.setInvalidType();
5722         break;
5723       }
5724       NR = NR->getPointeeType();
5725     }
5726
5727     if (!getOpenCLOptions().cl_khr_fp16) {
5728       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5729       // half array type (unless the cl_khr_fp16 extension is enabled).
5730       if (Context.getBaseElementType(R)->isHalfType()) {
5731         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5732         D.setInvalidType();
5733       }
5734     }
5735   }
5736
5737   if (SCSpec == DeclSpec::SCS_mutable) {
5738     // mutable can only appear on non-static class members, so it's always
5739     // an error here
5740     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5741     D.setInvalidType();
5742     SC = SC_None;
5743   }
5744
5745   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5746       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5747                               D.getDeclSpec().getStorageClassSpecLoc())) {
5748     // In C++11, the 'register' storage class specifier is deprecated.
5749     // Suppress the warning in system macros, it's used in macros in some
5750     // popular C system headers, such as in glibc's htonl() macro.
5751     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5752          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5753                                    : diag::warn_deprecated_register)
5754       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5755   }
5756
5757   IdentifierInfo *II = Name.getAsIdentifierInfo();
5758   if (!II) {
5759     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5760       << Name;
5761     return nullptr;
5762   }
5763
5764   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5765
5766   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5767     // C99 6.9p2: The storage-class specifiers auto and register shall not
5768     // appear in the declaration specifiers in an external declaration.
5769     // Global Register+Asm is a GNU extension we support.
5770     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5771       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5772       D.setInvalidType();
5773     }
5774   }
5775
5776   if (getLangOpts().OpenCL) {
5777     // OpenCL v1.2 s6.9.b p4:
5778     // The sampler type cannot be used with the __local and __global address
5779     // space qualifiers.
5780     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5781       R.getAddressSpace() == LangAS::opencl_global)) {
5782       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5783     }
5784
5785     // OpenCL 1.2 spec, p6.9 r:
5786     // The event type cannot be used to declare a program scope variable.
5787     // The event type cannot be used with the __local, __constant and __global
5788     // address space qualifiers.
5789     if (R->isEventT()) {
5790       if (S->getParent() == nullptr) {
5791         Diag(D.getLocStart(), diag::err_event_t_global_var);
5792         D.setInvalidType();
5793       }
5794
5795       if (R.getAddressSpace()) {
5796         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5797         D.setInvalidType();
5798       }
5799     }
5800   }
5801
5802   bool IsExplicitSpecialization = false;
5803   bool IsVariableTemplateSpecialization = false;
5804   bool IsPartialSpecialization = false;
5805   bool IsVariableTemplate = false;
5806   VarDecl *NewVD = nullptr;
5807   VarTemplateDecl *NewTemplate = nullptr;
5808   TemplateParameterList *TemplateParams = nullptr;
5809   if (!getLangOpts().CPlusPlus) {
5810     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5811                             D.getIdentifierLoc(), II,
5812                             R, TInfo, SC);
5813
5814     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5815       ParsingInitForAutoVars.insert(NewVD);
5816
5817     if (D.isInvalidType())
5818       NewVD->setInvalidDecl();
5819   } else {
5820     bool Invalid = false;
5821
5822     if (DC->isRecord() && !CurContext->isRecord()) {
5823       // This is an out-of-line definition of a static data member.
5824       switch (SC) {
5825       case SC_None:
5826         break;
5827       case SC_Static:
5828         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5829              diag::err_static_out_of_line)
5830           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5831         break;
5832       case SC_Auto:
5833       case SC_Register:
5834       case SC_Extern:
5835         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5836         // to names of variables declared in a block or to function parameters.
5837         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5838         // of class members
5839
5840         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5841              diag::err_storage_class_for_static_member)
5842           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5843         break;
5844       case SC_PrivateExtern:
5845         llvm_unreachable("C storage class in c++!");
5846       }
5847     }    
5848
5849     if (SC == SC_Static && CurContext->isRecord()) {
5850       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5851         if (RD->isLocalClass())
5852           Diag(D.getIdentifierLoc(),
5853                diag::err_static_data_member_not_allowed_in_local_class)
5854             << Name << RD->getDeclName();
5855
5856         // C++98 [class.union]p1: If a union contains a static data member,
5857         // the program is ill-formed. C++11 drops this restriction.
5858         if (RD->isUnion())
5859           Diag(D.getIdentifierLoc(),
5860                getLangOpts().CPlusPlus11
5861                  ? diag::warn_cxx98_compat_static_data_member_in_union
5862                  : diag::ext_static_data_member_in_union) << Name;
5863         // We conservatively disallow static data members in anonymous structs.
5864         else if (!RD->getDeclName())
5865           Diag(D.getIdentifierLoc(),
5866                diag::err_static_data_member_not_allowed_in_anon_struct)
5867             << Name << RD->isUnion();
5868       }
5869     }
5870
5871     // Match up the template parameter lists with the scope specifier, then
5872     // determine whether we have a template or a template specialization.
5873     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5874         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5875         D.getCXXScopeSpec(),
5876         D.getName().getKind() == UnqualifiedId::IK_TemplateId
5877             ? D.getName().TemplateId
5878             : nullptr,
5879         TemplateParamLists,
5880         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5881
5882     if (TemplateParams) {
5883       if (!TemplateParams->size() &&
5884           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5885         // There is an extraneous 'template<>' for this variable. Complain
5886         // about it, but allow the declaration of the variable.
5887         Diag(TemplateParams->getTemplateLoc(),
5888              diag::err_template_variable_noparams)
5889           << II
5890           << SourceRange(TemplateParams->getTemplateLoc(),
5891                          TemplateParams->getRAngleLoc());
5892         TemplateParams = nullptr;
5893       } else {
5894         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5895           // This is an explicit specialization or a partial specialization.
5896           // FIXME: Check that we can declare a specialization here.
5897           IsVariableTemplateSpecialization = true;
5898           IsPartialSpecialization = TemplateParams->size() > 0;
5899         } else { // if (TemplateParams->size() > 0)
5900           // This is a template declaration.
5901           IsVariableTemplate = true;
5902
5903           // Check that we can declare a template here.
5904           if (CheckTemplateDeclScope(S, TemplateParams))
5905             return nullptr;
5906
5907           // Only C++1y supports variable templates (N3651).
5908           Diag(D.getIdentifierLoc(),
5909                getLangOpts().CPlusPlus14
5910                    ? diag::warn_cxx11_compat_variable_template
5911                    : diag::ext_variable_template);
5912         }
5913       }
5914     } else {
5915       assert(
5916           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5917           "should have a 'template<>' for this decl");
5918     }
5919
5920     if (IsVariableTemplateSpecialization) {
5921       SourceLocation TemplateKWLoc =
5922           TemplateParamLists.size() > 0
5923               ? TemplateParamLists[0]->getTemplateLoc()
5924               : SourceLocation();
5925       DeclResult Res = ActOnVarTemplateSpecialization(
5926           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5927           IsPartialSpecialization);
5928       if (Res.isInvalid())
5929         return nullptr;
5930       NewVD = cast<VarDecl>(Res.get());
5931       AddToScope = false;
5932     } else
5933       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5934                               D.getIdentifierLoc(), II, R, TInfo, SC);
5935
5936     // If this is supposed to be a variable template, create it as such.
5937     if (IsVariableTemplate) {
5938       NewTemplate =
5939           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5940                                   TemplateParams, NewVD);
5941       NewVD->setDescribedVarTemplate(NewTemplate);
5942     }
5943
5944     // If this decl has an auto type in need of deduction, make a note of the
5945     // Decl so we can diagnose uses of it in its own initializer.
5946     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5947       ParsingInitForAutoVars.insert(NewVD);
5948
5949     if (D.isInvalidType() || Invalid) {
5950       NewVD->setInvalidDecl();
5951       if (NewTemplate)
5952         NewTemplate->setInvalidDecl();
5953     }
5954
5955     SetNestedNameSpecifier(NewVD, D);
5956
5957     // If we have any template parameter lists that don't directly belong to
5958     // the variable (matching the scope specifier), store them.
5959     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5960     if (TemplateParamLists.size() > VDTemplateParamLists)
5961       NewVD->setTemplateParameterListsInfo(
5962           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
5963
5964     if (D.getDeclSpec().isConstexprSpecified())
5965       NewVD->setConstexpr(true);
5966
5967     if (D.getDeclSpec().isConceptSpecified()) {
5968       NewVD->setConcept(true);
5969
5970       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
5971       // be declared with the thread_local, inline, friend, or constexpr
5972       // specifiers, [...]
5973       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
5974         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5975              diag::err_concept_decl_invalid_specifiers)
5976             << 0 << 0;
5977         NewVD->setInvalidDecl(true);
5978       }
5979
5980       if (D.getDeclSpec().isConstexprSpecified()) {
5981         Diag(D.getDeclSpec().getConstexprSpecLoc(),
5982              diag::err_concept_decl_invalid_specifiers)
5983             << 0 << 3;
5984         NewVD->setInvalidDecl(true);
5985       }
5986     }
5987   }
5988
5989   // Set the lexical context. If the declarator has a C++ scope specifier, the
5990   // lexical context will be different from the semantic context.
5991   NewVD->setLexicalDeclContext(CurContext);
5992   if (NewTemplate)
5993     NewTemplate->setLexicalDeclContext(CurContext);
5994
5995   if (IsLocalExternDecl)
5996     NewVD->setLocalExternDecl();
5997
5998   bool EmitTLSUnsupportedError = false;
5999   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6000     // C++11 [dcl.stc]p4:
6001     //   When thread_local is applied to a variable of block scope the
6002     //   storage-class-specifier static is implied if it does not appear
6003     //   explicitly.
6004     // Core issue: 'static' is not implied if the variable is declared
6005     //   'extern'.
6006     if (NewVD->hasLocalStorage() &&
6007         (SCSpec != DeclSpec::SCS_unspecified ||
6008          TSCS != DeclSpec::TSCS_thread_local ||
6009          !DC->isFunctionOrMethod()))
6010       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6011            diag::err_thread_non_global)
6012         << DeclSpec::getSpecifierName(TSCS);
6013     else if (!Context.getTargetInfo().isTLSSupported()) {
6014       if (getLangOpts().CUDA) {
6015         // Postpone error emission until we've collected attributes required to
6016         // figure out whether it's a host or device variable and whether the
6017         // error should be ignored.
6018         EmitTLSUnsupportedError = true;
6019         // We still need to mark the variable as TLS so it shows up in AST with
6020         // proper storage class for other tools to use even if we're not going
6021         // to emit any code for it.
6022         NewVD->setTSCSpec(TSCS);
6023       } else
6024         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6025              diag::err_thread_unsupported);
6026     } else
6027       NewVD->setTSCSpec(TSCS);
6028   }
6029
6030   // C99 6.7.4p3
6031   //   An inline definition of a function with external linkage shall
6032   //   not contain a definition of a modifiable object with static or
6033   //   thread storage duration...
6034   // We only apply this when the function is required to be defined
6035   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6036   // that a local variable with thread storage duration still has to
6037   // be marked 'static'.  Also note that it's possible to get these
6038   // semantics in C++ using __attribute__((gnu_inline)).
6039   if (SC == SC_Static && S->getFnParent() != nullptr &&
6040       !NewVD->getType().isConstQualified()) {
6041     FunctionDecl *CurFD = getCurFunctionDecl();
6042     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6043       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6044            diag::warn_static_local_in_extern_inline);
6045       MaybeSuggestAddingStaticToDecl(CurFD);
6046     }
6047   }
6048
6049   if (D.getDeclSpec().isModulePrivateSpecified()) {
6050     if (IsVariableTemplateSpecialization)
6051       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6052           << (IsPartialSpecialization ? 1 : 0)
6053           << FixItHint::CreateRemoval(
6054                  D.getDeclSpec().getModulePrivateSpecLoc());
6055     else if (IsExplicitSpecialization)
6056       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6057         << 2
6058         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6059     else if (NewVD->hasLocalStorage())
6060       Diag(NewVD->getLocation(), diag::err_module_private_local)
6061         << 0 << NewVD->getDeclName()
6062         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6063         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6064     else {
6065       NewVD->setModulePrivate();
6066       if (NewTemplate)
6067         NewTemplate->setModulePrivate();
6068     }
6069   }
6070
6071   // Handle attributes prior to checking for duplicates in MergeVarDecl
6072   ProcessDeclAttributes(S, NewVD, D);
6073
6074   if (getLangOpts().CUDA) {
6075     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6076       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6077            diag::err_thread_unsupported);
6078     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6079     // storage [duration]."
6080     if (SC == SC_None && S->getFnParent() != nullptr &&
6081         (NewVD->hasAttr<CUDASharedAttr>() ||
6082          NewVD->hasAttr<CUDAConstantAttr>())) {
6083       NewVD->setStorageClass(SC_Static);
6084     }
6085   }
6086
6087   // Ensure that dllimport globals without explicit storage class are treated as
6088   // extern. The storage class is set above using parsed attributes. Now we can
6089   // check the VarDecl itself.
6090   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6091          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6092          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6093
6094   // In auto-retain/release, infer strong retension for variables of
6095   // retainable type.
6096   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6097     NewVD->setInvalidDecl();
6098
6099   // Handle GNU asm-label extension (encoded as an attribute).
6100   if (Expr *E = (Expr*)D.getAsmLabel()) {
6101     // The parser guarantees this is a string.
6102     StringLiteral *SE = cast<StringLiteral>(E);
6103     StringRef Label = SE->getString();
6104     if (S->getFnParent() != nullptr) {
6105       switch (SC) {
6106       case SC_None:
6107       case SC_Auto:
6108         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6109         break;
6110       case SC_Register:
6111         // Local Named register
6112         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6113             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6114           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6115         break;
6116       case SC_Static:
6117       case SC_Extern:
6118       case SC_PrivateExtern:
6119         break;
6120       }
6121     } else if (SC == SC_Register) {
6122       // Global Named register
6123       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6124         const auto &TI = Context.getTargetInfo();
6125         bool HasSizeMismatch;
6126
6127         if (!TI.isValidGCCRegisterName(Label))
6128           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6129         else if (!TI.validateGlobalRegisterVariable(Label,
6130                                                     Context.getTypeSize(R),
6131                                                     HasSizeMismatch))
6132           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6133         else if (HasSizeMismatch)
6134           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6135       }
6136
6137       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6138         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6139         NewVD->setInvalidDecl(true);
6140       }
6141     }
6142
6143     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6144                                                 Context, Label, 0));
6145   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6146     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6147       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6148     if (I != ExtnameUndeclaredIdentifiers.end()) {
6149       if (isDeclExternC(NewVD)) {
6150         NewVD->addAttr(I->second);
6151         ExtnameUndeclaredIdentifiers.erase(I);
6152       } else
6153         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6154             << /*Variable*/1 << NewVD;
6155     }
6156   }
6157
6158   // Diagnose shadowed variables before filtering for scope.
6159   if (D.getCXXScopeSpec().isEmpty())
6160     CheckShadow(S, NewVD, Previous);
6161
6162   // Don't consider existing declarations that are in a different
6163   // scope and are out-of-semantic-context declarations (if the new
6164   // declaration has linkage).
6165   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6166                        D.getCXXScopeSpec().isNotEmpty() ||
6167                        IsExplicitSpecialization ||
6168                        IsVariableTemplateSpecialization);
6169
6170   // Check whether the previous declaration is in the same block scope. This
6171   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6172   if (getLangOpts().CPlusPlus &&
6173       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6174     NewVD->setPreviousDeclInSameBlockScope(
6175         Previous.isSingleResult() && !Previous.isShadowed() &&
6176         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6177
6178   if (!getLangOpts().CPlusPlus) {
6179     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6180   } else {
6181     // If this is an explicit specialization of a static data member, check it.
6182     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6183         CheckMemberSpecialization(NewVD, Previous))
6184       NewVD->setInvalidDecl();
6185
6186     // Merge the decl with the existing one if appropriate.
6187     if (!Previous.empty()) {
6188       if (Previous.isSingleResult() &&
6189           isa<FieldDecl>(Previous.getFoundDecl()) &&
6190           D.getCXXScopeSpec().isSet()) {
6191         // The user tried to define a non-static data member
6192         // out-of-line (C++ [dcl.meaning]p1).
6193         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6194           << D.getCXXScopeSpec().getRange();
6195         Previous.clear();
6196         NewVD->setInvalidDecl();
6197       }
6198     } else if (D.getCXXScopeSpec().isSet()) {
6199       // No previous declaration in the qualifying scope.
6200       Diag(D.getIdentifierLoc(), diag::err_no_member)
6201         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6202         << D.getCXXScopeSpec().getRange();
6203       NewVD->setInvalidDecl();
6204     }
6205
6206     if (!IsVariableTemplateSpecialization)
6207       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6208
6209     if (NewTemplate) {
6210       VarTemplateDecl *PrevVarTemplate =
6211           NewVD->getPreviousDecl()
6212               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6213               : nullptr;
6214
6215       // Check the template parameter list of this declaration, possibly
6216       // merging in the template parameter list from the previous variable
6217       // template declaration.
6218       if (CheckTemplateParameterList(
6219               TemplateParams,
6220               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6221                               : nullptr,
6222               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6223                DC->isDependentContext())
6224                   ? TPC_ClassTemplateMember
6225                   : TPC_VarTemplate))
6226         NewVD->setInvalidDecl();
6227
6228       // If we are providing an explicit specialization of a static variable
6229       // template, make a note of that.
6230       if (PrevVarTemplate &&
6231           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6232         PrevVarTemplate->setMemberSpecialization();
6233     }
6234   }
6235
6236   ProcessPragmaWeak(S, NewVD);
6237
6238   // If this is the first declaration of an extern C variable, update
6239   // the map of such variables.
6240   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6241       isIncompleteDeclExternC(*this, NewVD))
6242     RegisterLocallyScopedExternCDecl(NewVD, S);
6243
6244   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6245     Decl *ManglingContextDecl;
6246     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6247             NewVD->getDeclContext(), ManglingContextDecl)) {
6248       Context.setManglingNumber(
6249           NewVD, MCtx->getManglingNumber(
6250                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6251       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6252     }
6253   }
6254
6255   // Special handling of variable named 'main'.
6256   if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6257       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6258       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6259
6260     // C++ [basic.start.main]p3
6261     // A program that declares a variable main at global scope is ill-formed.
6262     if (getLangOpts().CPlusPlus)
6263       Diag(D.getLocStart(), diag::err_main_global_variable);
6264
6265     // In C, and external-linkage variable named main results in undefined
6266     // behavior.
6267     else if (NewVD->hasExternalFormalLinkage())
6268       Diag(D.getLocStart(), diag::warn_main_redefined);
6269   }
6270
6271   if (D.isRedeclaration() && !Previous.empty()) {
6272     checkDLLAttributeRedeclaration(
6273         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6274         IsExplicitSpecialization);
6275   }
6276
6277   if (NewTemplate) {
6278     if (NewVD->isInvalidDecl())
6279       NewTemplate->setInvalidDecl();
6280     ActOnDocumentableDecl(NewTemplate);
6281     return NewTemplate;
6282   }
6283
6284   return NewVD;
6285 }
6286
6287 /// \brief Diagnose variable or built-in function shadowing.  Implements
6288 /// -Wshadow.
6289 ///
6290 /// This method is called whenever a VarDecl is added to a "useful"
6291 /// scope.
6292 ///
6293 /// \param S the scope in which the shadowing name is being declared
6294 /// \param R the lookup of the name
6295 ///
6296 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6297   // Return if warning is ignored.
6298   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6299     return;
6300
6301   // Don't diagnose declarations at file scope.
6302   if (D->hasGlobalStorage())
6303     return;
6304
6305   DeclContext *NewDC = D->getDeclContext();
6306
6307   // Only diagnose if we're shadowing an unambiguous field or variable.
6308   if (R.getResultKind() != LookupResult::Found)
6309     return;
6310
6311   NamedDecl* ShadowedDecl = R.getFoundDecl();
6312   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6313     return;
6314
6315   // Fields are not shadowed by variables in C++ static methods.
6316   if (isa<FieldDecl>(ShadowedDecl))
6317     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6318       if (MD->isStatic())
6319         return;
6320
6321   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6322     if (shadowedVar->isExternC()) {
6323       // For shadowing external vars, make sure that we point to the global
6324       // declaration, not a locally scoped extern declaration.
6325       for (auto I : shadowedVar->redecls())
6326         if (I->isFileVarDecl()) {
6327           ShadowedDecl = I;
6328           break;
6329         }
6330     }
6331
6332   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6333
6334   // Only warn about certain kinds of shadowing for class members.
6335   if (NewDC && NewDC->isRecord()) {
6336     // In particular, don't warn about shadowing non-class members.
6337     if (!OldDC->isRecord())
6338       return;
6339
6340     // TODO: should we warn about static data members shadowing
6341     // static data members from base classes?
6342     
6343     // TODO: don't diagnose for inaccessible shadowed members.
6344     // This is hard to do perfectly because we might friend the
6345     // shadowing context, but that's just a false negative.
6346   }
6347
6348   // Determine what kind of declaration we're shadowing.
6349   unsigned Kind;
6350   if (isa<RecordDecl>(OldDC)) {
6351     if (isa<FieldDecl>(ShadowedDecl))
6352       Kind = 3; // field
6353     else
6354       Kind = 2; // static data member
6355   } else if (OldDC->isFileContext())
6356     Kind = 1; // global
6357   else
6358     Kind = 0; // local
6359
6360   DeclarationName Name = R.getLookupName();
6361
6362   // Emit warning and note.
6363   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6364     return;
6365   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6366   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6367 }
6368
6369 /// \brief Check -Wshadow without the advantage of a previous lookup.
6370 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6371   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6372     return;
6373
6374   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6375                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6376   LookupName(R, S);
6377   CheckShadow(S, D, R);
6378 }
6379
6380 /// Check for conflict between this global or extern "C" declaration and
6381 /// previous global or extern "C" declarations. This is only used in C++.
6382 template<typename T>
6383 static bool checkGlobalOrExternCConflict(
6384     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6385   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6386   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6387
6388   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6389     // The common case: this global doesn't conflict with any extern "C"
6390     // declaration.
6391     return false;
6392   }
6393
6394   if (Prev) {
6395     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6396       // Both the old and new declarations have C language linkage. This is a
6397       // redeclaration.
6398       Previous.clear();
6399       Previous.addDecl(Prev);
6400       return true;
6401     }
6402
6403     // This is a global, non-extern "C" declaration, and there is a previous
6404     // non-global extern "C" declaration. Diagnose if this is a variable
6405     // declaration.
6406     if (!isa<VarDecl>(ND))
6407       return false;
6408   } else {
6409     // The declaration is extern "C". Check for any declaration in the
6410     // translation unit which might conflict.
6411     if (IsGlobal) {
6412       // We have already performed the lookup into the translation unit.
6413       IsGlobal = false;
6414       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6415            I != E; ++I) {
6416         if (isa<VarDecl>(*I)) {
6417           Prev = *I;
6418           break;
6419         }
6420       }
6421     } else {
6422       DeclContext::lookup_result R =
6423           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6424       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6425            I != E; ++I) {
6426         if (isa<VarDecl>(*I)) {
6427           Prev = *I;
6428           break;
6429         }
6430         // FIXME: If we have any other entity with this name in global scope,
6431         // the declaration is ill-formed, but that is a defect: it breaks the
6432         // 'stat' hack, for instance. Only variables can have mangled name
6433         // clashes with extern "C" declarations, so only they deserve a
6434         // diagnostic.
6435       }
6436     }
6437
6438     if (!Prev)
6439       return false;
6440   }
6441
6442   // Use the first declaration's location to ensure we point at something which
6443   // is lexically inside an extern "C" linkage-spec.
6444   assert(Prev && "should have found a previous declaration to diagnose");
6445   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6446     Prev = FD->getFirstDecl();
6447   else
6448     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6449
6450   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6451     << IsGlobal << ND;
6452   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6453     << IsGlobal;
6454   return false;
6455 }
6456
6457 /// Apply special rules for handling extern "C" declarations. Returns \c true
6458 /// if we have found that this is a redeclaration of some prior entity.
6459 ///
6460 /// Per C++ [dcl.link]p6:
6461 ///   Two declarations [for a function or variable] with C language linkage
6462 ///   with the same name that appear in different scopes refer to the same
6463 ///   [entity]. An entity with C language linkage shall not be declared with
6464 ///   the same name as an entity in global scope.
6465 template<typename T>
6466 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6467                                                   LookupResult &Previous) {
6468   if (!S.getLangOpts().CPlusPlus) {
6469     // In C, when declaring a global variable, look for a corresponding 'extern'
6470     // variable declared in function scope. We don't need this in C++, because
6471     // we find local extern decls in the surrounding file-scope DeclContext.
6472     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6473       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6474         Previous.clear();
6475         Previous.addDecl(Prev);
6476         return true;
6477       }
6478     }
6479     return false;
6480   }
6481
6482   // A declaration in the translation unit can conflict with an extern "C"
6483   // declaration.
6484   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6485     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6486
6487   // An extern "C" declaration can conflict with a declaration in the
6488   // translation unit or can be a redeclaration of an extern "C" declaration
6489   // in another scope.
6490   if (isIncompleteDeclExternC(S,ND))
6491     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6492
6493   // Neither global nor extern "C": nothing to do.
6494   return false;
6495 }
6496
6497 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6498   // If the decl is already known invalid, don't check it.
6499   if (NewVD->isInvalidDecl())
6500     return;
6501
6502   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6503   QualType T = TInfo->getType();
6504
6505   // Defer checking an 'auto' type until its initializer is attached.
6506   if (T->isUndeducedType())
6507     return;
6508
6509   if (NewVD->hasAttrs())
6510     CheckAlignasUnderalignment(NewVD);
6511
6512   if (T->isObjCObjectType()) {
6513     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6514       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6515     T = Context.getObjCObjectPointerType(T);
6516     NewVD->setType(T);
6517   }
6518
6519   // Emit an error if an address space was applied to decl with local storage.
6520   // This includes arrays of objects with address space qualifiers, but not
6521   // automatic variables that point to other address spaces.
6522   // ISO/IEC TR 18037 S5.1.2
6523   if (!getLangOpts().OpenCL
6524       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6525     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6526     NewVD->setInvalidDecl();
6527     return;
6528   }
6529
6530   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6531   // scope.
6532   if (getLangOpts().OpenCLVersion == 120 &&
6533       !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6534       NewVD->isStaticLocal()) {
6535     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6536     NewVD->setInvalidDecl();
6537     return;
6538   }
6539
6540   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6541   // __constant address space.
6542   // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6543   // variables inside a function can also be declared in the global
6544   // address space.
6545   if (getLangOpts().OpenCL) {
6546     if (NewVD->isFileVarDecl()) {
6547       if (!T->isSamplerT() &&
6548           !(T.getAddressSpace() == LangAS::opencl_constant ||
6549             (T.getAddressSpace() == LangAS::opencl_global &&
6550              getLangOpts().OpenCLVersion == 200))) {
6551         if (getLangOpts().OpenCLVersion == 200)
6552           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6553               << "global or constant";
6554         else
6555           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6556               << "constant";
6557         NewVD->setInvalidDecl();
6558         return;
6559       }
6560     } else {
6561       // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6562       // variables inside a function can also be declared in the global
6563       // address space.
6564       if (NewVD->isStaticLocal() &&
6565           !(T.getAddressSpace() == LangAS::opencl_constant ||
6566             (T.getAddressSpace() == LangAS::opencl_global &&
6567              getLangOpts().OpenCLVersion == 200))) {
6568         if (getLangOpts().OpenCLVersion == 200)
6569           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6570               << "global or constant";
6571         else
6572           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6573               << "constant";
6574         NewVD->setInvalidDecl();
6575         return;
6576       }
6577       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6578       // in functions.
6579       if (T.getAddressSpace() == LangAS::opencl_constant ||
6580           T.getAddressSpace() == LangAS::opencl_local) {
6581         FunctionDecl *FD = getCurFunctionDecl();
6582         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6583           if (T.getAddressSpace() == LangAS::opencl_constant)
6584             Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable)
6585                 << "constant";
6586           else
6587             Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable)
6588                 << "local";
6589           NewVD->setInvalidDecl();
6590           return;
6591         }
6592       }
6593     }
6594   }
6595
6596   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6597       && !NewVD->hasAttr<BlocksAttr>()) {
6598     if (getLangOpts().getGC() != LangOptions::NonGC)
6599       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6600     else {
6601       assert(!getLangOpts().ObjCAutoRefCount);
6602       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6603     }
6604   }
6605   
6606   bool isVM = T->isVariablyModifiedType();
6607   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6608       NewVD->hasAttr<BlocksAttr>())
6609     getCurFunction()->setHasBranchProtectedScope();
6610
6611   if ((isVM && NewVD->hasLinkage()) ||
6612       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6613     bool SizeIsNegative;
6614     llvm::APSInt Oversized;
6615     TypeSourceInfo *FixedTInfo =
6616       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6617                                                     SizeIsNegative, Oversized);
6618     if (!FixedTInfo && T->isVariableArrayType()) {
6619       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6620       // FIXME: This won't give the correct result for
6621       // int a[10][n];
6622       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6623
6624       if (NewVD->isFileVarDecl())
6625         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6626         << SizeRange;
6627       else if (NewVD->isStaticLocal())
6628         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6629         << SizeRange;
6630       else
6631         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6632         << SizeRange;
6633       NewVD->setInvalidDecl();
6634       return;
6635     }
6636
6637     if (!FixedTInfo) {
6638       if (NewVD->isFileVarDecl())
6639         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6640       else
6641         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6642       NewVD->setInvalidDecl();
6643       return;
6644     }
6645
6646     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6647     NewVD->setType(FixedTInfo->getType());
6648     NewVD->setTypeSourceInfo(FixedTInfo);
6649   }
6650
6651   if (T->isVoidType()) {
6652     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6653     //                    of objects and functions.
6654     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6655       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6656         << T;
6657       NewVD->setInvalidDecl();
6658       return;
6659     }
6660   }
6661
6662   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6663     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6664     NewVD->setInvalidDecl();
6665     return;
6666   }
6667
6668   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6669     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6670     NewVD->setInvalidDecl();
6671     return;
6672   }
6673
6674   if (NewVD->isConstexpr() && !T->isDependentType() &&
6675       RequireLiteralType(NewVD->getLocation(), T,
6676                          diag::err_constexpr_var_non_literal)) {
6677     NewVD->setInvalidDecl();
6678     return;
6679   }
6680 }
6681
6682 /// \brief Perform semantic checking on a newly-created variable
6683 /// declaration.
6684 ///
6685 /// This routine performs all of the type-checking required for a
6686 /// variable declaration once it has been built. It is used both to
6687 /// check variables after they have been parsed and their declarators
6688 /// have been translated into a declaration, and to check variables
6689 /// that have been instantiated from a template.
6690 ///
6691 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6692 ///
6693 /// Returns true if the variable declaration is a redeclaration.
6694 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6695   CheckVariableDeclarationType(NewVD);
6696
6697   // If the decl is already known invalid, don't check it.
6698   if (NewVD->isInvalidDecl())
6699     return false;
6700
6701   // If we did not find anything by this name, look for a non-visible
6702   // extern "C" declaration with the same name.
6703   if (Previous.empty() &&
6704       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6705     Previous.setShadowed();
6706
6707   if (!Previous.empty()) {
6708     MergeVarDecl(NewVD, Previous);
6709     return true;
6710   }
6711   return false;
6712 }
6713
6714 namespace {
6715 struct FindOverriddenMethod {
6716   Sema *S;
6717   CXXMethodDecl *Method;
6718
6719   /// Member lookup function that determines whether a given C++
6720   /// method overrides a method in a base class, to be used with
6721   /// CXXRecordDecl::lookupInBases().
6722   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6723     RecordDecl *BaseRecord =
6724         Specifier->getType()->getAs<RecordType>()->getDecl();
6725
6726     DeclarationName Name = Method->getDeclName();
6727
6728     // FIXME: Do we care about other names here too?
6729     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6730       // We really want to find the base class destructor here.
6731       QualType T = S->Context.getTypeDeclType(BaseRecord);
6732       CanQualType CT = S->Context.getCanonicalType(T);
6733
6734       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
6735     }
6736
6737     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6738          Path.Decls = Path.Decls.slice(1)) {
6739       NamedDecl *D = Path.Decls.front();
6740       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6741         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
6742           return true;
6743       }
6744     }
6745
6746     return false;
6747   }
6748 };
6749
6750 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6751 } // end anonymous namespace
6752
6753 /// \brief Report an error regarding overriding, along with any relevant
6754 /// overriden methods.
6755 ///
6756 /// \param DiagID the primary error to report.
6757 /// \param MD the overriding method.
6758 /// \param OEK which overrides to include as notes.
6759 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6760                             OverrideErrorKind OEK = OEK_All) {
6761   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6762   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6763                                       E = MD->end_overridden_methods();
6764        I != E; ++I) {
6765     // This check (& the OEK parameter) could be replaced by a predicate, but
6766     // without lambdas that would be overkill. This is still nicer than writing
6767     // out the diag loop 3 times.
6768     if ((OEK == OEK_All) ||
6769         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6770         (OEK == OEK_Deleted && (*I)->isDeleted()))
6771       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6772   }
6773 }
6774
6775 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6776 /// and if so, check that it's a valid override and remember it.
6777 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6778   // Look for methods in base classes that this method might override.
6779   CXXBasePaths Paths;
6780   FindOverriddenMethod FOM;
6781   FOM.Method = MD;
6782   FOM.S = this;
6783   bool hasDeletedOverridenMethods = false;
6784   bool hasNonDeletedOverridenMethods = false;
6785   bool AddedAny = false;
6786   if (DC->lookupInBases(FOM, Paths)) {
6787     for (auto *I : Paths.found_decls()) {
6788       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6789         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6790         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6791             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6792             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6793             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6794           hasDeletedOverridenMethods |= OldMD->isDeleted();
6795           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6796           AddedAny = true;
6797         }
6798       }
6799     }
6800   }
6801
6802   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6803     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6804   }
6805   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6806     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6807   }
6808
6809   return AddedAny;
6810 }
6811
6812 namespace {
6813   // Struct for holding all of the extra arguments needed by
6814   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6815   struct ActOnFDArgs {
6816     Scope *S;
6817     Declarator &D;
6818     MultiTemplateParamsArg TemplateParamLists;
6819     bool AddToScope;
6820   };
6821 }
6822
6823 namespace {
6824
6825 // Callback to only accept typo corrections that have a non-zero edit distance.
6826 // Also only accept corrections that have the same parent decl.
6827 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6828  public:
6829   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6830                             CXXRecordDecl *Parent)
6831       : Context(Context), OriginalFD(TypoFD),
6832         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6833
6834   bool ValidateCandidate(const TypoCorrection &candidate) override {
6835     if (candidate.getEditDistance() == 0)
6836       return false;
6837
6838     SmallVector<unsigned, 1> MismatchedParams;
6839     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6840                                           CDeclEnd = candidate.end();
6841          CDecl != CDeclEnd; ++CDecl) {
6842       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6843
6844       if (FD && !FD->hasBody() &&
6845           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6846         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6847           CXXRecordDecl *Parent = MD->getParent();
6848           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6849             return true;
6850         } else if (!ExpectedParent) {
6851           return true;
6852         }
6853       }
6854     }
6855
6856     return false;
6857   }
6858
6859  private:
6860   ASTContext &Context;
6861   FunctionDecl *OriginalFD;
6862   CXXRecordDecl *ExpectedParent;
6863 };
6864
6865 }
6866
6867 /// \brief Generate diagnostics for an invalid function redeclaration.
6868 ///
6869 /// This routine handles generating the diagnostic messages for an invalid
6870 /// function redeclaration, including finding possible similar declarations
6871 /// or performing typo correction if there are no previous declarations with
6872 /// the same name.
6873 ///
6874 /// Returns a NamedDecl iff typo correction was performed and substituting in
6875 /// the new declaration name does not cause new errors.
6876 static NamedDecl *DiagnoseInvalidRedeclaration(
6877     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6878     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6879   DeclarationName Name = NewFD->getDeclName();
6880   DeclContext *NewDC = NewFD->getDeclContext();
6881   SmallVector<unsigned, 1> MismatchedParams;
6882   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6883   TypoCorrection Correction;
6884   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6885   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6886                                    : diag::err_member_decl_does_not_match;
6887   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6888                     IsLocalFriend ? Sema::LookupLocalFriendName
6889                                   : Sema::LookupOrdinaryName,
6890                     Sema::ForRedeclaration);
6891
6892   NewFD->setInvalidDecl();
6893   if (IsLocalFriend)
6894     SemaRef.LookupName(Prev, S);
6895   else
6896     SemaRef.LookupQualifiedName(Prev, NewDC);
6897   assert(!Prev.isAmbiguous() &&
6898          "Cannot have an ambiguity in previous-declaration lookup");
6899   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6900   if (!Prev.empty()) {
6901     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6902          Func != FuncEnd; ++Func) {
6903       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6904       if (FD &&
6905           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6906         // Add 1 to the index so that 0 can mean the mismatch didn't
6907         // involve a parameter
6908         unsigned ParamNum =
6909             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6910         NearMatches.push_back(std::make_pair(FD, ParamNum));
6911       }
6912     }
6913   // If the qualified name lookup yielded nothing, try typo correction
6914   } else if ((Correction = SemaRef.CorrectTypo(
6915                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6916                   &ExtraArgs.D.getCXXScopeSpec(),
6917                   llvm::make_unique<DifferentNameValidatorCCC>(
6918                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
6919                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6920     // Set up everything for the call to ActOnFunctionDeclarator
6921     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6922                               ExtraArgs.D.getIdentifierLoc());
6923     Previous.clear();
6924     Previous.setLookupName(Correction.getCorrection());
6925     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6926                                     CDeclEnd = Correction.end();
6927          CDecl != CDeclEnd; ++CDecl) {
6928       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6929       if (FD && !FD->hasBody() &&
6930           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6931         Previous.addDecl(FD);
6932       }
6933     }
6934     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6935
6936     NamedDecl *Result;
6937     // Retry building the function declaration with the new previous
6938     // declarations, and with errors suppressed.
6939     {
6940       // Trap errors.
6941       Sema::SFINAETrap Trap(SemaRef);
6942
6943       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6944       // pieces need to verify the typo-corrected C++ declaration and hopefully
6945       // eliminate the need for the parameter pack ExtraArgs.
6946       Result = SemaRef.ActOnFunctionDeclarator(
6947           ExtraArgs.S, ExtraArgs.D,
6948           Correction.getCorrectionDecl()->getDeclContext(),
6949           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6950           ExtraArgs.AddToScope);
6951
6952       if (Trap.hasErrorOccurred())
6953         Result = nullptr;
6954     }
6955
6956     if (Result) {
6957       // Determine which correction we picked.
6958       Decl *Canonical = Result->getCanonicalDecl();
6959       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6960            I != E; ++I)
6961         if ((*I)->getCanonicalDecl() == Canonical)
6962           Correction.setCorrectionDecl(*I);
6963
6964       SemaRef.diagnoseTypo(
6965           Correction,
6966           SemaRef.PDiag(IsLocalFriend
6967                           ? diag::err_no_matching_local_friend_suggest
6968                           : diag::err_member_decl_does_not_match_suggest)
6969             << Name << NewDC << IsDefinition);
6970       return Result;
6971     }
6972
6973     // Pretend the typo correction never occurred
6974     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6975                               ExtraArgs.D.getIdentifierLoc());
6976     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6977     Previous.clear();
6978     Previous.setLookupName(Name);
6979   }
6980
6981   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6982       << Name << NewDC << IsDefinition << NewFD->getLocation();
6983
6984   bool NewFDisConst = false;
6985   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6986     NewFDisConst = NewMD->isConst();
6987
6988   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6989        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6990        NearMatch != NearMatchEnd; ++NearMatch) {
6991     FunctionDecl *FD = NearMatch->first;
6992     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6993     bool FDisConst = MD && MD->isConst();
6994     bool IsMember = MD || !IsLocalFriend;
6995
6996     // FIXME: These notes are poorly worded for the local friend case.
6997     if (unsigned Idx = NearMatch->second) {
6998       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6999       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7000       if (Loc.isInvalid()) Loc = FD->getLocation();
7001       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7002                                  : diag::note_local_decl_close_param_match)
7003         << Idx << FDParam->getType()
7004         << NewFD->getParamDecl(Idx - 1)->getType();
7005     } else if (FDisConst != NewFDisConst) {
7006       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7007           << NewFDisConst << FD->getSourceRange().getEnd();
7008     } else
7009       SemaRef.Diag(FD->getLocation(),
7010                    IsMember ? diag::note_member_def_close_match
7011                             : diag::note_local_decl_close_match);
7012   }
7013   return nullptr;
7014 }
7015
7016 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7017   switch (D.getDeclSpec().getStorageClassSpec()) {
7018   default: llvm_unreachable("Unknown storage class!");
7019   case DeclSpec::SCS_auto:
7020   case DeclSpec::SCS_register:
7021   case DeclSpec::SCS_mutable:
7022     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7023                  diag::err_typecheck_sclass_func);
7024     D.setInvalidType();
7025     break;
7026   case DeclSpec::SCS_unspecified: break;
7027   case DeclSpec::SCS_extern:
7028     if (D.getDeclSpec().isExternInLinkageSpec())
7029       return SC_None;
7030     return SC_Extern;
7031   case DeclSpec::SCS_static: {
7032     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7033       // C99 6.7.1p5:
7034       //   The declaration of an identifier for a function that has
7035       //   block scope shall have no explicit storage-class specifier
7036       //   other than extern
7037       // See also (C++ [dcl.stc]p4).
7038       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7039                    diag::err_static_block_func);
7040       break;
7041     } else
7042       return SC_Static;
7043   }
7044   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7045   }
7046
7047   // No explicit storage class has already been returned
7048   return SC_None;
7049 }
7050
7051 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7052                                            DeclContext *DC, QualType &R,
7053                                            TypeSourceInfo *TInfo,
7054                                            StorageClass SC,
7055                                            bool &IsVirtualOkay) {
7056   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7057   DeclarationName Name = NameInfo.getName();
7058
7059   FunctionDecl *NewFD = nullptr;
7060   bool isInline = D.getDeclSpec().isInlineSpecified();
7061
7062   if (!SemaRef.getLangOpts().CPlusPlus) {
7063     // Determine whether the function was written with a
7064     // prototype. This true when:
7065     //   - there is a prototype in the declarator, or
7066     //   - the type R of the function is some kind of typedef or other reference
7067     //     to a type name (which eventually refers to a function type).
7068     bool HasPrototype =
7069       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7070       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7071
7072     NewFD = FunctionDecl::Create(SemaRef.Context, DC, 
7073                                  D.getLocStart(), NameInfo, R, 
7074                                  TInfo, SC, isInline, 
7075                                  HasPrototype, false);
7076     if (D.isInvalidType())
7077       NewFD->setInvalidDecl();
7078
7079     return NewFD;
7080   }
7081
7082   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7083   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7084
7085   // Check that the return type is not an abstract class type.
7086   // For record types, this is done by the AbstractClassUsageDiagnoser once
7087   // the class has been completely parsed.
7088   if (!DC->isRecord() &&
7089       SemaRef.RequireNonAbstractType(
7090           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7091           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7092     D.setInvalidType();
7093
7094   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7095     // This is a C++ constructor declaration.
7096     assert(DC->isRecord() &&
7097            "Constructors can only be declared in a member context");
7098
7099     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7100     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7101                                       D.getLocStart(), NameInfo,
7102                                       R, TInfo, isExplicit, isInline,
7103                                       /*isImplicitlyDeclared=*/false,
7104                                       isConstexpr);
7105
7106   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7107     // This is a C++ destructor declaration.
7108     if (DC->isRecord()) {
7109       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7110       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7111       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7112                                         SemaRef.Context, Record,
7113                                         D.getLocStart(),
7114                                         NameInfo, R, TInfo, isInline,
7115                                         /*isImplicitlyDeclared=*/false);
7116
7117       // If the class is complete, then we now create the implicit exception
7118       // specification. If the class is incomplete or dependent, we can't do
7119       // it yet.
7120       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7121           Record->getDefinition() && !Record->isBeingDefined() &&
7122           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7123         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7124       }
7125
7126       IsVirtualOkay = true;
7127       return NewDD;
7128
7129     } else {
7130       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7131       D.setInvalidType();
7132
7133       // Create a FunctionDecl to satisfy the function definition parsing
7134       // code path.
7135       return FunctionDecl::Create(SemaRef.Context, DC,
7136                                   D.getLocStart(),
7137                                   D.getIdentifierLoc(), Name, R, TInfo,
7138                                   SC, isInline,
7139                                   /*hasPrototype=*/true, isConstexpr);
7140     }
7141
7142   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7143     if (!DC->isRecord()) {
7144       SemaRef.Diag(D.getIdentifierLoc(),
7145            diag::err_conv_function_not_member);
7146       return nullptr;
7147     }
7148
7149     SemaRef.CheckConversionDeclarator(D, R, SC);
7150     IsVirtualOkay = true;
7151     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7152                                      D.getLocStart(), NameInfo,
7153                                      R, TInfo, isInline, isExplicit,
7154                                      isConstexpr, SourceLocation());
7155
7156   } else if (DC->isRecord()) {
7157     // If the name of the function is the same as the name of the record,
7158     // then this must be an invalid constructor that has a return type.
7159     // (The parser checks for a return type and makes the declarator a
7160     // constructor if it has no return type).
7161     if (Name.getAsIdentifierInfo() &&
7162         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7163       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7164         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7165         << SourceRange(D.getIdentifierLoc());
7166       return nullptr;
7167     }
7168
7169     // This is a C++ method declaration.
7170     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7171                                                cast<CXXRecordDecl>(DC),
7172                                                D.getLocStart(), NameInfo, R,
7173                                                TInfo, SC, isInline,
7174                                                isConstexpr, SourceLocation());
7175     IsVirtualOkay = !Ret->isStatic();
7176     return Ret;
7177   } else {
7178     bool isFriend =
7179         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7180     if (!isFriend && SemaRef.CurContext->isRecord())
7181       return nullptr;
7182
7183     // Determine whether the function was written with a
7184     // prototype. This true when:
7185     //   - we're in C++ (where every function has a prototype),
7186     return FunctionDecl::Create(SemaRef.Context, DC,
7187                                 D.getLocStart(),
7188                                 NameInfo, R, TInfo, SC, isInline,
7189                                 true/*HasPrototype*/, isConstexpr);
7190   }
7191 }
7192
7193 enum OpenCLParamType {
7194   ValidKernelParam,
7195   PtrPtrKernelParam,
7196   PtrKernelParam,
7197   PrivatePtrKernelParam,
7198   InvalidKernelParam,
7199   RecordKernelParam
7200 };
7201
7202 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7203   if (PT->isPointerType()) {
7204     QualType PointeeType = PT->getPointeeType();
7205     if (PointeeType->isPointerType())
7206       return PtrPtrKernelParam;
7207     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7208                                               : PtrKernelParam;
7209   }
7210
7211   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7212   // be used as builtin types.
7213
7214   if (PT->isImageType())
7215     return PtrKernelParam;
7216
7217   if (PT->isBooleanType())
7218     return InvalidKernelParam;
7219
7220   if (PT->isEventT())
7221     return InvalidKernelParam;
7222
7223   if (PT->isHalfType())
7224     return InvalidKernelParam;
7225
7226   if (PT->isRecordType())
7227     return RecordKernelParam;
7228
7229   return ValidKernelParam;
7230 }
7231
7232 static void checkIsValidOpenCLKernelParameter(
7233   Sema &S,
7234   Declarator &D,
7235   ParmVarDecl *Param,
7236   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7237   QualType PT = Param->getType();
7238
7239   // Cache the valid types we encounter to avoid rechecking structs that are
7240   // used again
7241   if (ValidTypes.count(PT.getTypePtr()))
7242     return;
7243
7244   switch (getOpenCLKernelParameterType(PT)) {
7245   case PtrPtrKernelParam:
7246     // OpenCL v1.2 s6.9.a:
7247     // A kernel function argument cannot be declared as a
7248     // pointer to a pointer type.
7249     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7250     D.setInvalidType();
7251     return;
7252
7253   case PrivatePtrKernelParam:
7254     // OpenCL v1.2 s6.9.a:
7255     // A kernel function argument cannot be declared as a
7256     // pointer to the private address space.
7257     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7258     D.setInvalidType();
7259     return;
7260
7261     // OpenCL v1.2 s6.9.k:
7262     // Arguments to kernel functions in a program cannot be declared with the
7263     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7264     // uintptr_t or a struct and/or union that contain fields declared to be
7265     // one of these built-in scalar types.
7266
7267   case InvalidKernelParam:
7268     // OpenCL v1.2 s6.8 n:
7269     // A kernel function argument cannot be declared
7270     // of event_t type.
7271     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7272     D.setInvalidType();
7273     return;
7274
7275   case PtrKernelParam:
7276   case ValidKernelParam:
7277     ValidTypes.insert(PT.getTypePtr());
7278     return;
7279
7280   case RecordKernelParam:
7281     break;
7282   }
7283
7284   // Track nested structs we will inspect
7285   SmallVector<const Decl *, 4> VisitStack;
7286
7287   // Track where we are in the nested structs. Items will migrate from
7288   // VisitStack to HistoryStack as we do the DFS for bad field.
7289   SmallVector<const FieldDecl *, 4> HistoryStack;
7290   HistoryStack.push_back(nullptr);
7291
7292   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7293   VisitStack.push_back(PD);
7294
7295   assert(VisitStack.back() && "First decl null?");
7296
7297   do {
7298     const Decl *Next = VisitStack.pop_back_val();
7299     if (!Next) {
7300       assert(!HistoryStack.empty());
7301       // Found a marker, we have gone up a level
7302       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7303         ValidTypes.insert(Hist->getType().getTypePtr());
7304
7305       continue;
7306     }
7307
7308     // Adds everything except the original parameter declaration (which is not a
7309     // field itself) to the history stack.
7310     const RecordDecl *RD;
7311     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7312       HistoryStack.push_back(Field);
7313       RD = Field->getType()->castAs<RecordType>()->getDecl();
7314     } else {
7315       RD = cast<RecordDecl>(Next);
7316     }
7317
7318     // Add a null marker so we know when we've gone back up a level
7319     VisitStack.push_back(nullptr);
7320
7321     for (const auto *FD : RD->fields()) {
7322       QualType QT = FD->getType();
7323
7324       if (ValidTypes.count(QT.getTypePtr()))
7325         continue;
7326
7327       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7328       if (ParamType == ValidKernelParam)
7329         continue;
7330
7331       if (ParamType == RecordKernelParam) {
7332         VisitStack.push_back(FD);
7333         continue;
7334       }
7335
7336       // OpenCL v1.2 s6.9.p:
7337       // Arguments to kernel functions that are declared to be a struct or union
7338       // do not allow OpenCL objects to be passed as elements of the struct or
7339       // union.
7340       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7341           ParamType == PrivatePtrKernelParam) {
7342         S.Diag(Param->getLocation(),
7343                diag::err_record_with_pointers_kernel_param)
7344           << PT->isUnionType()
7345           << PT;
7346       } else {
7347         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7348       }
7349
7350       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7351         << PD->getDeclName();
7352
7353       // We have an error, now let's go back up through history and show where
7354       // the offending field came from
7355       for (ArrayRef<const FieldDecl *>::const_iterator
7356                I = HistoryStack.begin() + 1,
7357                E = HistoryStack.end();
7358            I != E; ++I) {
7359         const FieldDecl *OuterField = *I;
7360         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7361           << OuterField->getType();
7362       }
7363
7364       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7365         << QT->isPointerType()
7366         << QT;
7367       D.setInvalidType();
7368       return;
7369     }
7370   } while (!VisitStack.empty());
7371 }
7372
7373 NamedDecl*
7374 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7375                               TypeSourceInfo *TInfo, LookupResult &Previous,
7376                               MultiTemplateParamsArg TemplateParamLists,
7377                               bool &AddToScope) {
7378   QualType R = TInfo->getType();
7379
7380   assert(R.getTypePtr()->isFunctionType());
7381
7382   // TODO: consider using NameInfo for diagnostic.
7383   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7384   DeclarationName Name = NameInfo.getName();
7385   StorageClass SC = getFunctionStorageClass(*this, D);
7386
7387   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7388     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7389          diag::err_invalid_thread)
7390       << DeclSpec::getSpecifierName(TSCS);
7391
7392   if (D.isFirstDeclarationOfMember())
7393     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7394                            D.getIdentifierLoc());
7395
7396   bool isFriend = false;
7397   FunctionTemplateDecl *FunctionTemplate = nullptr;
7398   bool isExplicitSpecialization = false;
7399   bool isFunctionTemplateSpecialization = false;
7400
7401   bool isDependentClassScopeExplicitSpecialization = false;
7402   bool HasExplicitTemplateArgs = false;
7403   TemplateArgumentListInfo TemplateArgs;
7404
7405   bool isVirtualOkay = false;
7406
7407   DeclContext *OriginalDC = DC;
7408   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7409
7410   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7411                                               isVirtualOkay);
7412   if (!NewFD) return nullptr;
7413
7414   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7415     NewFD->setTopLevelDeclInObjCContainer();
7416
7417   // Set the lexical context. If this is a function-scope declaration, or has a
7418   // C++ scope specifier, or is the object of a friend declaration, the lexical
7419   // context will be different from the semantic context.
7420   NewFD->setLexicalDeclContext(CurContext);
7421
7422   if (IsLocalExternDecl)
7423     NewFD->setLocalExternDecl();
7424
7425   if (getLangOpts().CPlusPlus) {
7426     bool isInline = D.getDeclSpec().isInlineSpecified();
7427     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7428     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7429     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7430     bool isConcept = D.getDeclSpec().isConceptSpecified();
7431     isFriend = D.getDeclSpec().isFriendSpecified();
7432     if (isFriend && !isInline && D.isFunctionDefinition()) {
7433       // C++ [class.friend]p5
7434       //   A function can be defined in a friend declaration of a
7435       //   class . . . . Such a function is implicitly inline.
7436       NewFD->setImplicitlyInline();
7437     }
7438
7439     // If this is a method defined in an __interface, and is not a constructor
7440     // or an overloaded operator, then set the pure flag (isVirtual will already
7441     // return true).
7442     if (const CXXRecordDecl *Parent =
7443           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7444       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7445         NewFD->setPure(true);
7446
7447       // C++ [class.union]p2
7448       //   A union can have member functions, but not virtual functions.
7449       if (isVirtual && Parent->isUnion())
7450         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7451     }
7452
7453     SetNestedNameSpecifier(NewFD, D);
7454     isExplicitSpecialization = false;
7455     isFunctionTemplateSpecialization = false;
7456     if (D.isInvalidType())
7457       NewFD->setInvalidDecl();
7458
7459     // Match up the template parameter lists with the scope specifier, then
7460     // determine whether we have a template or a template specialization.
7461     bool Invalid = false;
7462     if (TemplateParameterList *TemplateParams =
7463             MatchTemplateParametersToScopeSpecifier(
7464                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7465                 D.getCXXScopeSpec(),
7466                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7467                     ? D.getName().TemplateId
7468                     : nullptr,
7469                 TemplateParamLists, isFriend, isExplicitSpecialization,
7470                 Invalid)) {
7471       if (TemplateParams->size() > 0) {
7472         // This is a function template
7473
7474         // Check that we can declare a template here.
7475         if (CheckTemplateDeclScope(S, TemplateParams))
7476           NewFD->setInvalidDecl();
7477
7478         // A destructor cannot be a template.
7479         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7480           Diag(NewFD->getLocation(), diag::err_destructor_template);
7481           NewFD->setInvalidDecl();
7482         }
7483         
7484         // If we're adding a template to a dependent context, we may need to 
7485         // rebuilding some of the types used within the template parameter list,
7486         // now that we know what the current instantiation is.
7487         if (DC->isDependentContext()) {
7488           ContextRAII SavedContext(*this, DC);
7489           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7490             Invalid = true;
7491         }
7492         
7493
7494         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7495                                                         NewFD->getLocation(),
7496                                                         Name, TemplateParams,
7497                                                         NewFD);
7498         FunctionTemplate->setLexicalDeclContext(CurContext);
7499         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7500
7501         // For source fidelity, store the other template param lists.
7502         if (TemplateParamLists.size() > 1) {
7503           NewFD->setTemplateParameterListsInfo(Context,
7504                                                TemplateParamLists.drop_back(1));
7505         }
7506       } else {
7507         // This is a function template specialization.
7508         isFunctionTemplateSpecialization = true;
7509         // For source fidelity, store all the template param lists.
7510         if (TemplateParamLists.size() > 0)
7511           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7512
7513         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7514         if (isFriend) {
7515           // We want to remove the "template<>", found here.
7516           SourceRange RemoveRange = TemplateParams->getSourceRange();
7517
7518           // If we remove the template<> and the name is not a
7519           // template-id, we're actually silently creating a problem:
7520           // the friend declaration will refer to an untemplated decl,
7521           // and clearly the user wants a template specialization.  So
7522           // we need to insert '<>' after the name.
7523           SourceLocation InsertLoc;
7524           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7525             InsertLoc = D.getName().getSourceRange().getEnd();
7526             InsertLoc = getLocForEndOfToken(InsertLoc);
7527           }
7528
7529           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7530             << Name << RemoveRange
7531             << FixItHint::CreateRemoval(RemoveRange)
7532             << FixItHint::CreateInsertion(InsertLoc, "<>");
7533         }
7534       }
7535     }
7536     else {
7537       // All template param lists were matched against the scope specifier:
7538       // this is NOT (an explicit specialization of) a template.
7539       if (TemplateParamLists.size() > 0)
7540         // For source fidelity, store all the template param lists.
7541         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7542     }
7543
7544     if (Invalid) {
7545       NewFD->setInvalidDecl();
7546       if (FunctionTemplate)
7547         FunctionTemplate->setInvalidDecl();
7548     }
7549
7550     // C++ [dcl.fct.spec]p5:
7551     //   The virtual specifier shall only be used in declarations of
7552     //   nonstatic class member functions that appear within a
7553     //   member-specification of a class declaration; see 10.3.
7554     //
7555     if (isVirtual && !NewFD->isInvalidDecl()) {
7556       if (!isVirtualOkay) {
7557         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7558              diag::err_virtual_non_function);
7559       } else if (!CurContext->isRecord()) {
7560         // 'virtual' was specified outside of the class.
7561         Diag(D.getDeclSpec().getVirtualSpecLoc(), 
7562              diag::err_virtual_out_of_class)
7563           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7564       } else if (NewFD->getDescribedFunctionTemplate()) {
7565         // C++ [temp.mem]p3:
7566         //  A member function template shall not be virtual.
7567         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7568              diag::err_virtual_member_function_template)
7569           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7570       } else {
7571         // Okay: Add virtual to the method.
7572         NewFD->setVirtualAsWritten(true);
7573       }
7574
7575       if (getLangOpts().CPlusPlus14 &&
7576           NewFD->getReturnType()->isUndeducedType())
7577         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7578     }
7579
7580     if (getLangOpts().CPlusPlus14 &&
7581         (NewFD->isDependentContext() ||
7582          (isFriend && CurContext->isDependentContext())) &&
7583         NewFD->getReturnType()->isUndeducedType()) {
7584       // If the function template is referenced directly (for instance, as a
7585       // member of the current instantiation), pretend it has a dependent type.
7586       // This is not really justified by the standard, but is the only sane
7587       // thing to do.
7588       // FIXME: For a friend function, we have not marked the function as being
7589       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7590       const FunctionProtoType *FPT =
7591           NewFD->getType()->castAs<FunctionProtoType>();
7592       QualType Result =
7593           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7594       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7595                                              FPT->getExtProtoInfo()));
7596     }
7597
7598     // C++ [dcl.fct.spec]p3:
7599     //  The inline specifier shall not appear on a block scope function 
7600     //  declaration.
7601     if (isInline && !NewFD->isInvalidDecl()) {
7602       if (CurContext->isFunctionOrMethod()) {
7603         // 'inline' is not allowed on block scope function declaration.
7604         Diag(D.getDeclSpec().getInlineSpecLoc(), 
7605              diag::err_inline_declaration_block_scope) << Name
7606           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7607       }
7608     }
7609
7610     // C++ [dcl.fct.spec]p6:
7611     //  The explicit specifier shall be used only in the declaration of a
7612     //  constructor or conversion function within its class definition; 
7613     //  see 12.3.1 and 12.3.2.
7614     if (isExplicit && !NewFD->isInvalidDecl()) {
7615       if (!CurContext->isRecord()) {
7616         // 'explicit' was specified outside of the class.
7617         Diag(D.getDeclSpec().getExplicitSpecLoc(), 
7618              diag::err_explicit_out_of_class)
7619           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7620       } else if (!isa<CXXConstructorDecl>(NewFD) && 
7621                  !isa<CXXConversionDecl>(NewFD)) {
7622         // 'explicit' was specified on a function that wasn't a constructor
7623         // or conversion function.
7624         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7625              diag::err_explicit_non_ctor_or_conv_function)
7626           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7627       }      
7628     }
7629
7630     if (isConstexpr) {
7631       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7632       // are implicitly inline.
7633       NewFD->setImplicitlyInline();
7634
7635       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7636       // be either constructors or to return a literal type. Therefore,
7637       // destructors cannot be declared constexpr.
7638       if (isa<CXXDestructorDecl>(NewFD))
7639         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7640     }
7641
7642     if (isConcept) {
7643       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7644       // applied only to the definition of a function template [...]
7645       if (!D.isFunctionDefinition()) {
7646         Diag(D.getDeclSpec().getConceptSpecLoc(),
7647              diag::err_function_concept_not_defined);
7648         NewFD->setInvalidDecl();
7649       }
7650
7651       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7652       // have no exception-specification and is treated as if it were specified
7653       // with noexcept(true) (15.4). [...]
7654       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7655         if (FPT->hasExceptionSpec()) {
7656           SourceRange Range;
7657           if (D.isFunctionDeclarator())
7658             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7659           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7660               << FixItHint::CreateRemoval(Range);
7661           NewFD->setInvalidDecl();
7662         } else {
7663           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7664         }
7665
7666         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7667         // following restrictions:
7668         // - The declaration's parameter list shall be equivalent to an empty
7669         //   parameter list.
7670         if (FPT->getNumParams() > 0 || FPT->isVariadic())
7671           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7672       }
7673
7674       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7675       // implicity defined to be a constexpr declaration (implicitly inline)
7676       NewFD->setImplicitlyInline();
7677
7678       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7679       // be declared with the thread_local, inline, friend, or constexpr
7680       // specifiers, [...]
7681       if (isInline) {
7682         Diag(D.getDeclSpec().getInlineSpecLoc(),
7683              diag::err_concept_decl_invalid_specifiers)
7684             << 1 << 1;
7685         NewFD->setInvalidDecl(true);
7686       }
7687
7688       if (isFriend) {
7689         Diag(D.getDeclSpec().getFriendSpecLoc(),
7690              diag::err_concept_decl_invalid_specifiers)
7691             << 1 << 2;
7692         NewFD->setInvalidDecl(true);
7693       }
7694
7695       if (isConstexpr) {
7696         Diag(D.getDeclSpec().getConstexprSpecLoc(),
7697              diag::err_concept_decl_invalid_specifiers)
7698             << 1 << 3;
7699         NewFD->setInvalidDecl(true);
7700       }
7701     }
7702
7703     // If __module_private__ was specified, mark the function accordingly.
7704     if (D.getDeclSpec().isModulePrivateSpecified()) {
7705       if (isFunctionTemplateSpecialization) {
7706         SourceLocation ModulePrivateLoc
7707           = D.getDeclSpec().getModulePrivateSpecLoc();
7708         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7709           << 0
7710           << FixItHint::CreateRemoval(ModulePrivateLoc);
7711       } else {
7712         NewFD->setModulePrivate();
7713         if (FunctionTemplate)
7714           FunctionTemplate->setModulePrivate();
7715       }
7716     }
7717
7718     if (isFriend) {
7719       if (FunctionTemplate) {
7720         FunctionTemplate->setObjectOfFriendDecl();
7721         FunctionTemplate->setAccess(AS_public);
7722       }
7723       NewFD->setObjectOfFriendDecl();
7724       NewFD->setAccess(AS_public);
7725     }
7726
7727     // If a function is defined as defaulted or deleted, mark it as such now.
7728     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7729     // definition kind to FDK_Definition.
7730     switch (D.getFunctionDefinitionKind()) {
7731       case FDK_Declaration:
7732       case FDK_Definition:
7733         break;
7734         
7735       case FDK_Defaulted:
7736         NewFD->setDefaulted();
7737         break;
7738         
7739       case FDK_Deleted:
7740         NewFD->setDeletedAsWritten();
7741         break;
7742     }
7743
7744     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7745         D.isFunctionDefinition()) {
7746       // C++ [class.mfct]p2:
7747       //   A member function may be defined (8.4) in its class definition, in 
7748       //   which case it is an inline member function (7.1.2)
7749       NewFD->setImplicitlyInline();
7750     }
7751
7752     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7753         !CurContext->isRecord()) {
7754       // C++ [class.static]p1:
7755       //   A data or function member of a class may be declared static
7756       //   in a class definition, in which case it is a static member of
7757       //   the class.
7758
7759       // Complain about the 'static' specifier if it's on an out-of-line
7760       // member function definition.
7761       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7762            diag::err_static_out_of_line)
7763         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7764     }
7765
7766     // C++11 [except.spec]p15:
7767     //   A deallocation function with no exception-specification is treated
7768     //   as if it were specified with noexcept(true).
7769     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7770     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7771          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7772         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7773       NewFD->setType(Context.getFunctionType(
7774           FPT->getReturnType(), FPT->getParamTypes(),
7775           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7776   }
7777
7778   // Filter out previous declarations that don't match the scope.
7779   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7780                        D.getCXXScopeSpec().isNotEmpty() ||
7781                        isExplicitSpecialization ||
7782                        isFunctionTemplateSpecialization);
7783
7784   // Handle GNU asm-label extension (encoded as an attribute).
7785   if (Expr *E = (Expr*) D.getAsmLabel()) {
7786     // The parser guarantees this is a string.
7787     StringLiteral *SE = cast<StringLiteral>(E);
7788     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7789                                                 SE->getString(), 0));
7790   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7791     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7792       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7793     if (I != ExtnameUndeclaredIdentifiers.end()) {
7794       if (isDeclExternC(NewFD)) {
7795         NewFD->addAttr(I->second);
7796         ExtnameUndeclaredIdentifiers.erase(I);
7797       } else
7798         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
7799             << /*Variable*/0 << NewFD;
7800     }
7801   }
7802
7803   // Copy the parameter declarations from the declarator D to the function
7804   // declaration NewFD, if they are available.  First scavenge them into Params.
7805   SmallVector<ParmVarDecl*, 16> Params;
7806   if (D.isFunctionDeclarator()) {
7807     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7808
7809     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7810     // function that takes no arguments, not a function that takes a
7811     // single void argument.
7812     // We let through "const void" here because Sema::GetTypeForDeclarator
7813     // already checks for that case.
7814     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7815       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7816         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7817         assert(Param->getDeclContext() != NewFD && "Was set before ?");
7818         Param->setDeclContext(NewFD);
7819         Params.push_back(Param);
7820
7821         if (Param->isInvalidDecl())
7822           NewFD->setInvalidDecl();
7823       }
7824     }
7825
7826   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7827     // When we're declaring a function with a typedef, typeof, etc as in the
7828     // following example, we'll need to synthesize (unnamed)
7829     // parameters for use in the declaration.
7830     //
7831     // @code
7832     // typedef void fn(int);
7833     // fn f;
7834     // @endcode
7835
7836     // Synthesize a parameter for each argument type.
7837     for (const auto &AI : FT->param_types()) {
7838       ParmVarDecl *Param =
7839           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7840       Param->setScopeInfo(0, Params.size());
7841       Params.push_back(Param);
7842     }
7843   } else {
7844     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7845            "Should not need args for typedef of non-prototype fn");
7846   }
7847
7848   // Finally, we know we have the right number of parameters, install them.
7849   NewFD->setParams(Params);
7850
7851   // Find all anonymous symbols defined during the declaration of this function
7852   // and add to NewFD. This lets us track decls such 'enum Y' in:
7853   //
7854   //   void f(enum Y {AA} x) {}
7855   //
7856   // which would otherwise incorrectly end up in the translation unit scope.
7857   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7858   DeclsInPrototypeScope.clear();
7859
7860   if (D.getDeclSpec().isNoreturnSpecified())
7861     NewFD->addAttr(
7862         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7863                                        Context, 0));
7864
7865   // Functions returning a variably modified type violate C99 6.7.5.2p2
7866   // because all functions have linkage.
7867   if (!NewFD->isInvalidDecl() &&
7868       NewFD->getReturnType()->isVariablyModifiedType()) {
7869     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7870     NewFD->setInvalidDecl();
7871   }
7872
7873   // Apply an implicit SectionAttr if #pragma code_seg is active.
7874   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
7875       !NewFD->hasAttr<SectionAttr>()) {
7876     NewFD->addAttr(
7877         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7878                                     CodeSegStack.CurrentValue->getString(),
7879                                     CodeSegStack.CurrentPragmaLocation));
7880     if (UnifySection(CodeSegStack.CurrentValue->getString(),
7881                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
7882                          ASTContext::PSF_Read,
7883                      NewFD))
7884       NewFD->dropAttr<SectionAttr>();
7885   }
7886
7887   // Handle attributes.
7888   ProcessDeclAttributes(S, NewFD, D);
7889
7890   if (getLangOpts().OpenCL) {
7891     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7892     // type declaration will generate a compilation error.
7893     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
7894     if (AddressSpace == LangAS::opencl_local ||
7895         AddressSpace == LangAS::opencl_global ||
7896         AddressSpace == LangAS::opencl_constant) {
7897       Diag(NewFD->getLocation(),
7898            diag::err_opencl_return_value_with_address_space);
7899       NewFD->setInvalidDecl();
7900     }
7901   }
7902
7903   if (!getLangOpts().CPlusPlus) {
7904     // Perform semantic checking on the function declaration.
7905     bool isExplicitSpecialization=false;
7906     if (!NewFD->isInvalidDecl() && NewFD->isMain())
7907       CheckMain(NewFD, D.getDeclSpec());
7908
7909     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7910       CheckMSVCRTEntryPoint(NewFD);
7911
7912     if (!NewFD->isInvalidDecl())
7913       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7914                                                   isExplicitSpecialization));
7915     else if (!Previous.empty())
7916       // Recover gracefully from an invalid redeclaration.
7917       D.setRedeclaration(true);
7918     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7919             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7920            "previous declaration set still overloaded");
7921
7922     // Diagnose no-prototype function declarations with calling conventions that
7923     // don't support variadic calls. Only do this in C and do it after merging
7924     // possibly prototyped redeclarations.
7925     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
7926     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
7927       CallingConv CC = FT->getExtInfo().getCC();
7928       if (!supportsVariadicCall(CC)) {
7929         // Windows system headers sometimes accidentally use stdcall without
7930         // (void) parameters, so we relax this to a warning.
7931         int DiagID =
7932             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
7933         Diag(NewFD->getLocation(), DiagID)
7934             << FunctionType::getNameForCallConv(CC);
7935       }
7936     }
7937   } else {
7938     // C++11 [replacement.functions]p3:
7939     //  The program's definitions shall not be specified as inline.
7940     //
7941     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7942     //
7943     // Suppress the diagnostic if the function is __attribute__((used)), since
7944     // that forces an external definition to be emitted.
7945     if (D.getDeclSpec().isInlineSpecified() &&
7946         NewFD->isReplaceableGlobalAllocationFunction() &&
7947         !NewFD->hasAttr<UsedAttr>())
7948       Diag(D.getDeclSpec().getInlineSpecLoc(),
7949            diag::ext_operator_new_delete_declared_inline)
7950         << NewFD->getDeclName();
7951
7952     // If the declarator is a template-id, translate the parser's template 
7953     // argument list into our AST format.
7954     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7955       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7956       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7957       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7958       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7959                                          TemplateId->NumArgs);
7960       translateTemplateArguments(TemplateArgsPtr,
7961                                  TemplateArgs);
7962     
7963       HasExplicitTemplateArgs = true;
7964     
7965       if (NewFD->isInvalidDecl()) {
7966         HasExplicitTemplateArgs = false;
7967       } else if (FunctionTemplate) {
7968         // Function template with explicit template arguments.
7969         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7970           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7971
7972         HasExplicitTemplateArgs = false;
7973       } else {
7974         assert((isFunctionTemplateSpecialization ||
7975                 D.getDeclSpec().isFriendSpecified()) &&
7976                "should have a 'template<>' for this decl");
7977         // "friend void foo<>(int);" is an implicit specialization decl.
7978         isFunctionTemplateSpecialization = true;
7979       }
7980     } else if (isFriend && isFunctionTemplateSpecialization) {
7981       // This combination is only possible in a recovery case;  the user
7982       // wrote something like:
7983       //   template <> friend void foo(int);
7984       // which we're recovering from as if the user had written:
7985       //   friend void foo<>(int);
7986       // Go ahead and fake up a template id.
7987       HasExplicitTemplateArgs = true;
7988       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7989       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7990     }
7991
7992     // If it's a friend (and only if it's a friend), it's possible
7993     // that either the specialized function type or the specialized
7994     // template is dependent, and therefore matching will fail.  In
7995     // this case, don't check the specialization yet.
7996     bool InstantiationDependent = false;
7997     if (isFunctionTemplateSpecialization && isFriend &&
7998         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7999          TemplateSpecializationType::anyDependentTemplateArguments(
8000             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
8001             InstantiationDependent))) {
8002       assert(HasExplicitTemplateArgs &&
8003              "friend function specialization without template args");
8004       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8005                                                        Previous))
8006         NewFD->setInvalidDecl();
8007     } else if (isFunctionTemplateSpecialization) {
8008       if (CurContext->isDependentContext() && CurContext->isRecord() 
8009           && !isFriend) {
8010         isDependentClassScopeExplicitSpecialization = true;
8011         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 
8012           diag::ext_function_specialization_in_class :
8013           diag::err_function_specialization_in_class)
8014           << NewFD->getDeclName();
8015       } else if (CheckFunctionTemplateSpecialization(NewFD,
8016                                   (HasExplicitTemplateArgs ? &TemplateArgs
8017                                                            : nullptr),
8018                                                      Previous))
8019         NewFD->setInvalidDecl();
8020       
8021       // C++ [dcl.stc]p1:
8022       //   A storage-class-specifier shall not be specified in an explicit
8023       //   specialization (14.7.3)
8024       FunctionTemplateSpecializationInfo *Info =
8025           NewFD->getTemplateSpecializationInfo();
8026       if (Info && SC != SC_None) {
8027         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8028           Diag(NewFD->getLocation(),
8029                diag::err_explicit_specialization_inconsistent_storage_class)
8030             << SC
8031             << FixItHint::CreateRemoval(
8032                                       D.getDeclSpec().getStorageClassSpecLoc());
8033             
8034         else
8035           Diag(NewFD->getLocation(), 
8036                diag::ext_explicit_specialization_storage_class)
8037             << FixItHint::CreateRemoval(
8038                                       D.getDeclSpec().getStorageClassSpecLoc());
8039       }
8040       
8041     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8042       if (CheckMemberSpecialization(NewFD, Previous))
8043           NewFD->setInvalidDecl();
8044     }
8045
8046     // Perform semantic checking on the function declaration.
8047     if (!isDependentClassScopeExplicitSpecialization) {
8048       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8049         CheckMain(NewFD, D.getDeclSpec());
8050
8051       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8052         CheckMSVCRTEntryPoint(NewFD);
8053
8054       if (!NewFD->isInvalidDecl())
8055         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8056                                                     isExplicitSpecialization));
8057       else if (!Previous.empty())
8058         // Recover gracefully from an invalid redeclaration.
8059         D.setRedeclaration(true);
8060     }
8061
8062     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8063             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8064            "previous declaration set still overloaded");
8065
8066     NamedDecl *PrincipalDecl = (FunctionTemplate
8067                                 ? cast<NamedDecl>(FunctionTemplate)
8068                                 : NewFD);
8069
8070     if (isFriend && D.isRedeclaration()) {
8071       AccessSpecifier Access = AS_public;
8072       if (!NewFD->isInvalidDecl())
8073         Access = NewFD->getPreviousDecl()->getAccess();
8074
8075       NewFD->setAccess(Access);
8076       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8077     }
8078
8079     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8080         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8081       PrincipalDecl->setNonMemberOperator();
8082
8083     // If we have a function template, check the template parameter
8084     // list. This will check and merge default template arguments.
8085     if (FunctionTemplate) {
8086       FunctionTemplateDecl *PrevTemplate = 
8087                                      FunctionTemplate->getPreviousDecl();
8088       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8089                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8090                                     : nullptr,
8091                             D.getDeclSpec().isFriendSpecified()
8092                               ? (D.isFunctionDefinition()
8093                                    ? TPC_FriendFunctionTemplateDefinition
8094                                    : TPC_FriendFunctionTemplate)
8095                               : (D.getCXXScopeSpec().isSet() && 
8096                                  DC && DC->isRecord() && 
8097                                  DC->isDependentContext())
8098                                   ? TPC_ClassTemplateMember
8099                                   : TPC_FunctionTemplate);
8100     }
8101
8102     if (NewFD->isInvalidDecl()) {
8103       // Ignore all the rest of this.
8104     } else if (!D.isRedeclaration()) {
8105       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8106                                        AddToScope };
8107       // Fake up an access specifier if it's supposed to be a class member.
8108       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8109         NewFD->setAccess(AS_public);
8110
8111       // Qualified decls generally require a previous declaration.
8112       if (D.getCXXScopeSpec().isSet()) {
8113         // ...with the major exception of templated-scope or
8114         // dependent-scope friend declarations.
8115
8116         // TODO: we currently also suppress this check in dependent
8117         // contexts because (1) the parameter depth will be off when
8118         // matching friend templates and (2) we might actually be
8119         // selecting a friend based on a dependent factor.  But there
8120         // are situations where these conditions don't apply and we
8121         // can actually do this check immediately.
8122         if (isFriend &&
8123             (TemplateParamLists.size() ||
8124              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8125              CurContext->isDependentContext())) {
8126           // ignore these
8127         } else {
8128           // The user tried to provide an out-of-line definition for a
8129           // function that is a member of a class or namespace, but there
8130           // was no such member function declared (C++ [class.mfct]p2,
8131           // C++ [namespace.memdef]p2). For example:
8132           //
8133           // class X {
8134           //   void f() const;
8135           // };
8136           //
8137           // void X::f() { } // ill-formed
8138           //
8139           // Complain about this problem, and attempt to suggest close
8140           // matches (e.g., those that differ only in cv-qualifiers and
8141           // whether the parameter types are references).
8142
8143           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8144                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8145             AddToScope = ExtraArgs.AddToScope;
8146             return Result;
8147           }
8148         }
8149
8150         // Unqualified local friend declarations are required to resolve
8151         // to something.
8152       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8153         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8154                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8155           AddToScope = ExtraArgs.AddToScope;
8156           return Result;
8157         }
8158       }
8159
8160     } else if (!D.isFunctionDefinition() &&
8161                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8162                !isFriend && !isFunctionTemplateSpecialization &&
8163                !isExplicitSpecialization) {
8164       // An out-of-line member function declaration must also be a
8165       // definition (C++ [class.mfct]p2).
8166       // Note that this is not the case for explicit specializations of
8167       // function templates or member functions of class templates, per
8168       // C++ [temp.expl.spec]p2. We also allow these declarations as an 
8169       // extension for compatibility with old SWIG code which likes to 
8170       // generate them.
8171       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8172         << D.getCXXScopeSpec().getRange();
8173     }
8174   }
8175
8176   ProcessPragmaWeak(S, NewFD);
8177   checkAttributesAfterMerging(*this, *NewFD);
8178
8179   AddKnownFunctionAttributes(NewFD);
8180
8181   if (NewFD->hasAttr<OverloadableAttr>() && 
8182       !NewFD->getType()->getAs<FunctionProtoType>()) {
8183     Diag(NewFD->getLocation(),
8184          diag::err_attribute_overloadable_no_prototype)
8185       << NewFD;
8186
8187     // Turn this into a variadic function with no parameters.
8188     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8189     FunctionProtoType::ExtProtoInfo EPI(
8190         Context.getDefaultCallingConvention(true, false));
8191     EPI.Variadic = true;
8192     EPI.ExtInfo = FT->getExtInfo();
8193
8194     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8195     NewFD->setType(R);
8196   }
8197
8198   // If there's a #pragma GCC visibility in scope, and this isn't a class
8199   // member, set the visibility of this function.
8200   if (!DC->isRecord() && NewFD->isExternallyVisible())
8201     AddPushedVisibilityAttribute(NewFD);
8202
8203   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8204   // marking the function.
8205   AddCFAuditedAttribute(NewFD);
8206
8207   // If this is a function definition, check if we have to apply optnone due to
8208   // a pragma.
8209   if(D.isFunctionDefinition())
8210     AddRangeBasedOptnone(NewFD);
8211
8212   // If this is the first declaration of an extern C variable, update
8213   // the map of such variables.
8214   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8215       isIncompleteDeclExternC(*this, NewFD))
8216     RegisterLocallyScopedExternCDecl(NewFD, S);
8217
8218   // Set this FunctionDecl's range up to the right paren.
8219   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8220
8221   if (D.isRedeclaration() && !Previous.empty()) {
8222     checkDLLAttributeRedeclaration(
8223         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8224         isExplicitSpecialization || isFunctionTemplateSpecialization);
8225   }
8226
8227   if (getLangOpts().CPlusPlus) {
8228     if (FunctionTemplate) {
8229       if (NewFD->isInvalidDecl())
8230         FunctionTemplate->setInvalidDecl();
8231       return FunctionTemplate;
8232     }
8233   }
8234
8235   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8236     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8237     if ((getLangOpts().OpenCLVersion >= 120)
8238         && (SC == SC_Static)) {
8239       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8240       D.setInvalidType();
8241     }
8242     
8243     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8244     if (!NewFD->getReturnType()->isVoidType()) {
8245       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8246       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8247           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8248                                 : FixItHint());
8249       D.setInvalidType();
8250     }
8251
8252     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8253     for (auto Param : NewFD->params())
8254       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8255   }
8256
8257   MarkUnusedFileScopedDecl(NewFD);
8258
8259   if (getLangOpts().CUDA)
8260     if (IdentifierInfo *II = NewFD->getIdentifier())
8261       if (!NewFD->isInvalidDecl() &&
8262           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8263         if (II->isStr("cudaConfigureCall")) {
8264           if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8265             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8266
8267           Context.setcudaConfigureCallDecl(NewFD);
8268         }
8269       }
8270   
8271   // Here we have an function template explicit specialization at class scope.
8272   // The actually specialization will be postponed to template instatiation
8273   // time via the ClassScopeFunctionSpecializationDecl node.
8274   if (isDependentClassScopeExplicitSpecialization) {
8275     ClassScopeFunctionSpecializationDecl *NewSpec =
8276                          ClassScopeFunctionSpecializationDecl::Create(
8277                                 Context, CurContext, SourceLocation(), 
8278                                 cast<CXXMethodDecl>(NewFD),
8279                                 HasExplicitTemplateArgs, TemplateArgs);
8280     CurContext->addDecl(NewSpec);
8281     AddToScope = false;
8282   }
8283
8284   return NewFD;
8285 }
8286
8287 /// \brief Perform semantic checking of a new function declaration.
8288 ///
8289 /// Performs semantic analysis of the new function declaration
8290 /// NewFD. This routine performs all semantic checking that does not
8291 /// require the actual declarator involved in the declaration, and is
8292 /// used both for the declaration of functions as they are parsed
8293 /// (called via ActOnDeclarator) and for the declaration of functions
8294 /// that have been instantiated via C++ template instantiation (called
8295 /// via InstantiateDecl).
8296 ///
8297 /// \param IsExplicitSpecialization whether this new function declaration is
8298 /// an explicit specialization of the previous declaration.
8299 ///
8300 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8301 ///
8302 /// \returns true if the function declaration is a redeclaration.
8303 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8304                                     LookupResult &Previous,
8305                                     bool IsExplicitSpecialization) {
8306   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8307          "Variably modified return types are not handled here");
8308
8309   // Determine whether the type of this function should be merged with
8310   // a previous visible declaration. This never happens for functions in C++,
8311   // and always happens in C if the previous declaration was visible.
8312   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8313                                !Previous.isShadowed();
8314
8315   bool Redeclaration = false;
8316   NamedDecl *OldDecl = nullptr;
8317
8318   // Merge or overload the declaration with an existing declaration of
8319   // the same name, if appropriate.
8320   if (!Previous.empty()) {
8321     // Determine whether NewFD is an overload of PrevDecl or
8322     // a declaration that requires merging. If it's an overload,
8323     // there's no more work to do here; we'll just add the new
8324     // function to the scope.
8325     if (!AllowOverloadingOfFunction(Previous, Context)) {
8326       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8327       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8328         Redeclaration = true;
8329         OldDecl = Candidate;
8330       }
8331     } else {
8332       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8333                             /*NewIsUsingDecl*/ false)) {
8334       case Ovl_Match:
8335         Redeclaration = true;
8336         break;
8337
8338       case Ovl_NonFunction:
8339         Redeclaration = true;
8340         break;
8341
8342       case Ovl_Overload:
8343         Redeclaration = false;
8344         break;
8345       }
8346
8347       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8348         // If a function name is overloadable in C, then every function
8349         // with that name must be marked "overloadable".
8350         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8351           << Redeclaration << NewFD;
8352         NamedDecl *OverloadedDecl = nullptr;
8353         if (Redeclaration)
8354           OverloadedDecl = OldDecl;
8355         else if (!Previous.empty())
8356           OverloadedDecl = Previous.getRepresentativeDecl();
8357         if (OverloadedDecl)
8358           Diag(OverloadedDecl->getLocation(),
8359                diag::note_attribute_overloadable_prev_overload);
8360         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8361       }
8362     }
8363   }
8364
8365   // Check for a previous extern "C" declaration with this name.
8366   if (!Redeclaration &&
8367       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8368     if (!Previous.empty()) {
8369       // This is an extern "C" declaration with the same name as a previous
8370       // declaration, and thus redeclares that entity...
8371       Redeclaration = true;
8372       OldDecl = Previous.getFoundDecl();
8373       MergeTypeWithPrevious = false;
8374
8375       // ... except in the presence of __attribute__((overloadable)).
8376       if (OldDecl->hasAttr<OverloadableAttr>()) {
8377         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8378           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8379             << Redeclaration << NewFD;
8380           Diag(Previous.getFoundDecl()->getLocation(),
8381                diag::note_attribute_overloadable_prev_overload);
8382           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8383         }
8384         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8385           Redeclaration = false;
8386           OldDecl = nullptr;
8387         }
8388       }
8389     }
8390   }
8391
8392   // C++11 [dcl.constexpr]p8:
8393   //   A constexpr specifier for a non-static member function that is not
8394   //   a constructor declares that member function to be const.
8395   //
8396   // This needs to be delayed until we know whether this is an out-of-line
8397   // definition of a static member function.
8398   //
8399   // This rule is not present in C++1y, so we produce a backwards
8400   // compatibility warning whenever it happens in C++11.
8401   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8402   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8403       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8404       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8405     CXXMethodDecl *OldMD = nullptr;
8406     if (OldDecl)
8407       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8408     if (!OldMD || !OldMD->isStatic()) {
8409       const FunctionProtoType *FPT =
8410         MD->getType()->castAs<FunctionProtoType>();
8411       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8412       EPI.TypeQuals |= Qualifiers::Const;
8413       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8414                                           FPT->getParamTypes(), EPI));
8415
8416       // Warn that we did this, if we're not performing template instantiation.
8417       // In that case, we'll have warned already when the template was defined.
8418       if (ActiveTemplateInstantiations.empty()) {
8419         SourceLocation AddConstLoc;
8420         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8421                 .IgnoreParens().getAs<FunctionTypeLoc>())
8422           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8423
8424         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8425           << FixItHint::CreateInsertion(AddConstLoc, " const");
8426       }
8427     }
8428   }
8429
8430   if (Redeclaration) {
8431     // NewFD and OldDecl represent declarations that need to be
8432     // merged.
8433     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8434       NewFD->setInvalidDecl();
8435       return Redeclaration;
8436     }
8437
8438     Previous.clear();
8439     Previous.addDecl(OldDecl);
8440
8441     if (FunctionTemplateDecl *OldTemplateDecl
8442                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8443       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8444       FunctionTemplateDecl *NewTemplateDecl
8445         = NewFD->getDescribedFunctionTemplate();
8446       assert(NewTemplateDecl && "Template/non-template mismatch");
8447       if (CXXMethodDecl *Method 
8448             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8449         Method->setAccess(OldTemplateDecl->getAccess());
8450         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8451       }
8452       
8453       // If this is an explicit specialization of a member that is a function
8454       // template, mark it as a member specialization.
8455       if (IsExplicitSpecialization && 
8456           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8457         NewTemplateDecl->setMemberSpecialization();
8458         assert(OldTemplateDecl->isMemberSpecialization());
8459       }
8460       
8461     } else {
8462       // This needs to happen first so that 'inline' propagates.
8463       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8464
8465       if (isa<CXXMethodDecl>(NewFD))
8466         NewFD->setAccess(OldDecl->getAccess());
8467     }
8468   }
8469
8470   // Semantic checking for this function declaration (in isolation).
8471
8472   if (getLangOpts().CPlusPlus) {
8473     // C++-specific checks.
8474     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8475       CheckConstructor(Constructor);
8476     } else if (CXXDestructorDecl *Destructor = 
8477                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8478       CXXRecordDecl *Record = Destructor->getParent();
8479       QualType ClassType = Context.getTypeDeclType(Record);
8480       
8481       // FIXME: Shouldn't we be able to perform this check even when the class
8482       // type is dependent? Both gcc and edg can handle that.
8483       if (!ClassType->isDependentType()) {
8484         DeclarationName Name
8485           = Context.DeclarationNames.getCXXDestructorName(
8486                                         Context.getCanonicalType(ClassType));
8487         if (NewFD->getDeclName() != Name) {
8488           Diag(NewFD->getLocation(), diag::err_destructor_name);
8489           NewFD->setInvalidDecl();
8490           return Redeclaration;
8491         }
8492       }
8493     } else if (CXXConversionDecl *Conversion
8494                = dyn_cast<CXXConversionDecl>(NewFD)) {
8495       ActOnConversionDeclarator(Conversion);
8496     }
8497
8498     // Find any virtual functions that this function overrides.
8499     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8500       if (!Method->isFunctionTemplateSpecialization() && 
8501           !Method->getDescribedFunctionTemplate() &&
8502           Method->isCanonicalDecl()) {
8503         if (AddOverriddenMethods(Method->getParent(), Method)) {
8504           // If the function was marked as "static", we have a problem.
8505           if (NewFD->getStorageClass() == SC_Static) {
8506             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8507           }
8508         }
8509       }
8510       
8511       if (Method->isStatic())
8512         checkThisInStaticMemberFunctionType(Method);
8513     }
8514
8515     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8516     if (NewFD->isOverloadedOperator() &&
8517         CheckOverloadedOperatorDeclaration(NewFD)) {
8518       NewFD->setInvalidDecl();
8519       return Redeclaration;
8520     }
8521
8522     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8523     if (NewFD->getLiteralIdentifier() &&
8524         CheckLiteralOperatorDeclaration(NewFD)) {
8525       NewFD->setInvalidDecl();
8526       return Redeclaration;
8527     }
8528
8529     // In C++, check default arguments now that we have merged decls. Unless
8530     // the lexical context is the class, because in this case this is done
8531     // during delayed parsing anyway.
8532     if (!CurContext->isRecord())
8533       CheckCXXDefaultArguments(NewFD);
8534
8535     // If this function declares a builtin function, check the type of this
8536     // declaration against the expected type for the builtin. 
8537     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8538       ASTContext::GetBuiltinTypeError Error;
8539       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8540       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8541       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8542         // The type of this function differs from the type of the builtin,
8543         // so forget about the builtin entirely.
8544         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8545       }
8546     }
8547
8548     // If this function is declared as being extern "C", then check to see if 
8549     // the function returns a UDT (class, struct, or union type) that is not C
8550     // compatible, and if it does, warn the user.
8551     // But, issue any diagnostic on the first declaration only.
8552     if (Previous.empty() && NewFD->isExternC()) {
8553       QualType R = NewFD->getReturnType();
8554       if (R->isIncompleteType() && !R->isVoidType())
8555         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8556             << NewFD << R;
8557       else if (!R.isPODType(Context) && !R->isVoidType() &&
8558                !R->isObjCObjectPointerType())
8559         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8560     }
8561   }
8562   return Redeclaration;
8563 }
8564
8565 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8566   // C++11 [basic.start.main]p3:
8567   //   A program that [...] declares main to be inline, static or
8568   //   constexpr is ill-formed.
8569   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8570   //   appear in a declaration of main.
8571   // static main is not an error under C99, but we should warn about it.
8572   // We accept _Noreturn main as an extension.
8573   if (FD->getStorageClass() == SC_Static)
8574     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 
8575          ? diag::err_static_main : diag::warn_static_main) 
8576       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8577   if (FD->isInlineSpecified())
8578     Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 
8579       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8580   if (DS.isNoreturnSpecified()) {
8581     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8582     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8583     Diag(NoreturnLoc, diag::ext_noreturn_main);
8584     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8585       << FixItHint::CreateRemoval(NoreturnRange);
8586   }
8587   if (FD->isConstexpr()) {
8588     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8589       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8590     FD->setConstexpr(false);
8591   }
8592
8593   if (getLangOpts().OpenCL) {
8594     Diag(FD->getLocation(), diag::err_opencl_no_main)
8595         << FD->hasAttr<OpenCLKernelAttr>();
8596     FD->setInvalidDecl();
8597     return;
8598   }
8599
8600   QualType T = FD->getType();
8601   assert(T->isFunctionType() && "function decl is not of function type");
8602   const FunctionType* FT = T->castAs<FunctionType>();
8603
8604   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8605     // In C with GNU extensions we allow main() to have non-integer return
8606     // type, but we should warn about the extension, and we disable the
8607     // implicit-return-zero rule.
8608
8609     // GCC in C mode accepts qualified 'int'.
8610     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8611       FD->setHasImplicitReturnZero(true);
8612     else {
8613       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8614       SourceRange RTRange = FD->getReturnTypeSourceRange();
8615       if (RTRange.isValid())
8616         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8617             << FixItHint::CreateReplacement(RTRange, "int");
8618     }
8619   } else {
8620     // In C and C++, main magically returns 0 if you fall off the end;
8621     // set the flag which tells us that.
8622     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8623
8624     // All the standards say that main() should return 'int'.
8625     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8626       FD->setHasImplicitReturnZero(true);
8627     else {
8628       // Otherwise, this is just a flat-out error.
8629       SourceRange RTRange = FD->getReturnTypeSourceRange();
8630       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8631           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8632                                 : FixItHint());
8633       FD->setInvalidDecl(true);
8634     }
8635   }
8636
8637   // Treat protoless main() as nullary.
8638   if (isa<FunctionNoProtoType>(FT)) return;
8639
8640   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8641   unsigned nparams = FTP->getNumParams();
8642   assert(FD->getNumParams() == nparams);
8643
8644   bool HasExtraParameters = (nparams > 3);
8645
8646   if (FTP->isVariadic()) {
8647     Diag(FD->getLocation(), diag::ext_variadic_main);
8648     // FIXME: if we had information about the location of the ellipsis, we
8649     // could add a FixIt hint to remove it as a parameter.
8650   }
8651
8652   // Darwin passes an undocumented fourth argument of type char**.  If
8653   // other platforms start sprouting these, the logic below will start
8654   // getting shifty.
8655   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8656     HasExtraParameters = false;
8657
8658   if (HasExtraParameters) {
8659     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8660     FD->setInvalidDecl(true);
8661     nparams = 3;
8662   }
8663
8664   // FIXME: a lot of the following diagnostics would be improved
8665   // if we had some location information about types.
8666
8667   QualType CharPP =
8668     Context.getPointerType(Context.getPointerType(Context.CharTy));
8669   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8670
8671   for (unsigned i = 0; i < nparams; ++i) {
8672     QualType AT = FTP->getParamType(i);
8673
8674     bool mismatch = true;
8675
8676     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8677       mismatch = false;
8678     else if (Expected[i] == CharPP) {
8679       // As an extension, the following forms are okay:
8680       //   char const **
8681       //   char const * const *
8682       //   char * const *
8683
8684       QualifierCollector qs;
8685       const PointerType* PT;
8686       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8687           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8688           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8689                               Context.CharTy)) {
8690         qs.removeConst();
8691         mismatch = !qs.empty();
8692       }
8693     }
8694
8695     if (mismatch) {
8696       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8697       // TODO: suggest replacing given type with expected type
8698       FD->setInvalidDecl(true);
8699     }
8700   }
8701
8702   if (nparams == 1 && !FD->isInvalidDecl()) {
8703     Diag(FD->getLocation(), diag::warn_main_one_arg);
8704   }
8705   
8706   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8707     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8708     FD->setInvalidDecl();
8709   }
8710 }
8711
8712 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8713   QualType T = FD->getType();
8714   assert(T->isFunctionType() && "function decl is not of function type");
8715   const FunctionType *FT = T->castAs<FunctionType>();
8716
8717   // Set an implicit return of 'zero' if the function can return some integral,
8718   // enumeration, pointer or nullptr type.
8719   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8720       FT->getReturnType()->isAnyPointerType() ||
8721       FT->getReturnType()->isNullPtrType())
8722     // DllMain is exempt because a return value of zero means it failed.
8723     if (FD->getName() != "DllMain")
8724       FD->setHasImplicitReturnZero(true);
8725
8726   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8727     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8728     FD->setInvalidDecl();
8729   }
8730 }
8731
8732 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8733   // FIXME: Need strict checking.  In C89, we need to check for
8734   // any assignment, increment, decrement, function-calls, or
8735   // commas outside of a sizeof.  In C99, it's the same list,
8736   // except that the aforementioned are allowed in unevaluated
8737   // expressions.  Everything else falls under the
8738   // "may accept other forms of constant expressions" exception.
8739   // (We never end up here for C++, so the constant expression
8740   // rules there don't matter.)
8741   const Expr *Culprit;
8742   if (Init->isConstantInitializer(Context, false, &Culprit))
8743     return false;
8744   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8745     << Culprit->getSourceRange();
8746   return true;
8747 }
8748
8749 namespace {
8750   // Visits an initialization expression to see if OrigDecl is evaluated in
8751   // its own initialization and throws a warning if it does.
8752   class SelfReferenceChecker
8753       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8754     Sema &S;
8755     Decl *OrigDecl;
8756     bool isRecordType;
8757     bool isPODType;
8758     bool isReferenceType;
8759
8760     bool isInitList;
8761     llvm::SmallVector<unsigned, 4> InitFieldIndex;
8762   public:
8763     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8764
8765     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8766                                                     S(S), OrigDecl(OrigDecl) {
8767       isPODType = false;
8768       isRecordType = false;
8769       isReferenceType = false;
8770       isInitList = false;
8771       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8772         isPODType = VD->getType().isPODType(S.Context);
8773         isRecordType = VD->getType()->isRecordType();
8774         isReferenceType = VD->getType()->isReferenceType();
8775       }
8776     }
8777
8778     // For most expressions, just call the visitor.  For initializer lists,
8779     // track the index of the field being initialized since fields are
8780     // initialized in order allowing use of previously initialized fields.
8781     void CheckExpr(Expr *E) {
8782       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8783       if (!InitList) {
8784         Visit(E);
8785         return;
8786       }
8787
8788       // Track and increment the index here.
8789       isInitList = true;
8790       InitFieldIndex.push_back(0);
8791       for (auto Child : InitList->children()) {
8792         CheckExpr(cast<Expr>(Child));
8793         ++InitFieldIndex.back();
8794       }
8795       InitFieldIndex.pop_back();
8796     }
8797
8798     // Returns true if MemberExpr is checked and no futher checking is needed.
8799     // Returns false if additional checking is required.
8800     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8801       llvm::SmallVector<FieldDecl*, 4> Fields;
8802       Expr *Base = E;
8803       bool ReferenceField = false;
8804
8805       // Get the field memebers used.
8806       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8807         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8808         if (!FD)
8809           return false;
8810         Fields.push_back(FD);
8811         if (FD->getType()->isReferenceType())
8812           ReferenceField = true;
8813         Base = ME->getBase()->IgnoreParenImpCasts();
8814       }
8815
8816       // Keep checking only if the base Decl is the same.
8817       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8818       if (!DRE || DRE->getDecl() != OrigDecl)
8819         return false;
8820
8821       // A reference field can be bound to an unininitialized field.
8822       if (CheckReference && !ReferenceField)
8823         return true;
8824
8825       // Convert FieldDecls to their index number.
8826       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8827       for (const FieldDecl *I : llvm::reverse(Fields))
8828         UsedFieldIndex.push_back(I->getFieldIndex());
8829
8830       // See if a warning is needed by checking the first difference in index
8831       // numbers.  If field being used has index less than the field being
8832       // initialized, then the use is safe.
8833       for (auto UsedIter = UsedFieldIndex.begin(),
8834                 UsedEnd = UsedFieldIndex.end(),
8835                 OrigIter = InitFieldIndex.begin(),
8836                 OrigEnd = InitFieldIndex.end();
8837            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8838         if (*UsedIter < *OrigIter)
8839           return true;
8840         if (*UsedIter > *OrigIter)
8841           break;
8842       }
8843
8844       // TODO: Add a different warning which will print the field names.
8845       HandleDeclRefExpr(DRE);
8846       return true;
8847     }
8848
8849     // For most expressions, the cast is directly above the DeclRefExpr.
8850     // For conditional operators, the cast can be outside the conditional
8851     // operator if both expressions are DeclRefExpr's.
8852     void HandleValue(Expr *E) {
8853       E = E->IgnoreParens();
8854       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8855         HandleDeclRefExpr(DRE);
8856         return;
8857       }
8858
8859       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8860         Visit(CO->getCond());
8861         HandleValue(CO->getTrueExpr());
8862         HandleValue(CO->getFalseExpr());
8863         return;
8864       }
8865
8866       if (BinaryConditionalOperator *BCO =
8867               dyn_cast<BinaryConditionalOperator>(E)) {
8868         Visit(BCO->getCond());
8869         HandleValue(BCO->getFalseExpr());
8870         return;
8871       }
8872
8873       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8874         HandleValue(OVE->getSourceExpr());
8875         return;
8876       }
8877
8878       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8879         if (BO->getOpcode() == BO_Comma) {
8880           Visit(BO->getLHS());
8881           HandleValue(BO->getRHS());
8882           return;
8883         }
8884       }
8885
8886       if (isa<MemberExpr>(E)) {
8887         if (isInitList) {
8888           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
8889                                       false /*CheckReference*/))
8890             return;
8891         }
8892
8893         Expr *Base = E->IgnoreParenImpCasts();
8894         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8895           // Check for static member variables and don't warn on them.
8896           if (!isa<FieldDecl>(ME->getMemberDecl()))
8897             return;
8898           Base = ME->getBase()->IgnoreParenImpCasts();
8899         }
8900         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8901           HandleDeclRefExpr(DRE);
8902         return;
8903       }
8904
8905       Visit(E);
8906     }
8907
8908     // Reference types not handled in HandleValue are handled here since all
8909     // uses of references are bad, not just r-value uses.
8910     void VisitDeclRefExpr(DeclRefExpr *E) {
8911       if (isReferenceType)
8912         HandleDeclRefExpr(E);
8913     }
8914
8915     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8916       if (E->getCastKind() == CK_LValueToRValue) {
8917         HandleValue(E->getSubExpr());
8918         return;
8919       }
8920
8921       Inherited::VisitImplicitCastExpr(E);
8922     }
8923
8924     void VisitMemberExpr(MemberExpr *E) {
8925       if (isInitList) {
8926         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
8927           return;
8928       }
8929
8930       // Don't warn on arrays since they can be treated as pointers.
8931       if (E->getType()->canDecayToPointerType()) return;
8932
8933       // Warn when a non-static method call is followed by non-static member
8934       // field accesses, which is followed by a DeclRefExpr.
8935       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8936       bool Warn = (MD && !MD->isStatic());
8937       Expr *Base = E->getBase()->IgnoreParenImpCasts();
8938       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8939         if (!isa<FieldDecl>(ME->getMemberDecl()))
8940           Warn = false;
8941         Base = ME->getBase()->IgnoreParenImpCasts();
8942       }
8943
8944       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8945         if (Warn)
8946           HandleDeclRefExpr(DRE);
8947         return;
8948       }
8949
8950       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8951       // Visit that expression.
8952       Visit(Base);
8953     }
8954
8955     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8956       Expr *Callee = E->getCallee();
8957
8958       if (isa<UnresolvedLookupExpr>(Callee))
8959         return Inherited::VisitCXXOperatorCallExpr(E);
8960
8961       Visit(Callee);
8962       for (auto Arg: E->arguments())
8963         HandleValue(Arg->IgnoreParenImpCasts());
8964     }
8965
8966     void VisitUnaryOperator(UnaryOperator *E) {
8967       // For POD record types, addresses of its own members are well-defined.
8968       if (E->getOpcode() == UO_AddrOf && isRecordType &&
8969           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8970         if (!isPODType)
8971           HandleValue(E->getSubExpr());
8972         return;
8973       }
8974
8975       if (E->isIncrementDecrementOp()) {
8976         HandleValue(E->getSubExpr());
8977         return;
8978       }
8979
8980       Inherited::VisitUnaryOperator(E);
8981     }
8982
8983     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8984
8985     void VisitCXXConstructExpr(CXXConstructExpr *E) {
8986       if (E->getConstructor()->isCopyConstructor()) {
8987         Expr *ArgExpr = E->getArg(0);
8988         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
8989           if (ILE->getNumInits() == 1)
8990             ArgExpr = ILE->getInit(0);
8991         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8992           if (ICE->getCastKind() == CK_NoOp)
8993             ArgExpr = ICE->getSubExpr();
8994         HandleValue(ArgExpr);
8995         return;
8996       }
8997       Inherited::VisitCXXConstructExpr(E);
8998     }
8999
9000     void VisitCallExpr(CallExpr *E) {
9001       // Treat std::move as a use.
9002       if (E->getNumArgs() == 1) {
9003         if (FunctionDecl *FD = E->getDirectCallee()) {
9004           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9005               FD->getIdentifier()->isStr("move")) {
9006             HandleValue(E->getArg(0));
9007             return;
9008           }
9009         }
9010       }
9011
9012       Inherited::VisitCallExpr(E);
9013     }
9014
9015     void VisitBinaryOperator(BinaryOperator *E) {
9016       if (E->isCompoundAssignmentOp()) {
9017         HandleValue(E->getLHS());
9018         Visit(E->getRHS());
9019         return;
9020       }
9021
9022       Inherited::VisitBinaryOperator(E);
9023     }
9024
9025     // A custom visitor for BinaryConditionalOperator is needed because the
9026     // regular visitor would check the condition and true expression separately
9027     // but both point to the same place giving duplicate diagnostics.
9028     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9029       Visit(E->getCond());
9030       Visit(E->getFalseExpr());
9031     }
9032
9033     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9034       Decl* ReferenceDecl = DRE->getDecl();
9035       if (OrigDecl != ReferenceDecl) return;
9036       unsigned diag;
9037       if (isReferenceType) {
9038         diag = diag::warn_uninit_self_reference_in_reference_init;
9039       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9040         diag = diag::warn_static_self_reference_in_init;
9041       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9042                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9043                  DRE->getDecl()->getType()->isRecordType()) {
9044         diag = diag::warn_uninit_self_reference_in_init;
9045       } else {
9046         // Local variables will be handled by the CFG analysis.
9047         return;
9048       }
9049
9050       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9051                             S.PDiag(diag)
9052                               << DRE->getNameInfo().getName()
9053                               << OrigDecl->getLocation()
9054                               << DRE->getSourceRange());
9055     }
9056   };
9057
9058   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9059   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9060                                  bool DirectInit) {
9061     // Parameters arguments are occassionially constructed with itself,
9062     // for instance, in recursive functions.  Skip them.
9063     if (isa<ParmVarDecl>(OrigDecl))
9064       return;
9065
9066     E = E->IgnoreParens();
9067
9068     // Skip checking T a = a where T is not a record or reference type.
9069     // Doing so is a way to silence uninitialized warnings.
9070     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9071       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9072         if (ICE->getCastKind() == CK_LValueToRValue)
9073           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9074             if (DRE->getDecl() == OrigDecl)
9075               return;
9076
9077     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9078   }
9079 }
9080
9081 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9082                                             DeclarationName Name, QualType Type,
9083                                             TypeSourceInfo *TSI,
9084                                             SourceRange Range, bool DirectInit,
9085                                             Expr *Init) {
9086   bool IsInitCapture = !VDecl;
9087   assert((!VDecl || !VDecl->isInitCapture()) &&
9088          "init captures are expected to be deduced prior to initialization");
9089
9090   ArrayRef<Expr *> DeduceInits = Init;
9091   if (DirectInit) {
9092     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9093       DeduceInits = PL->exprs();
9094     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9095       DeduceInits = IL->inits();
9096   }
9097
9098   // Deduction only works if we have exactly one source expression.
9099   if (DeduceInits.empty()) {
9100     // It isn't possible to write this directly, but it is possible to
9101     // end up in this situation with "auto x(some_pack...);"
9102     Diag(Init->getLocStart(), IsInitCapture
9103                                   ? diag::err_init_capture_no_expression
9104                                   : diag::err_auto_var_init_no_expression)
9105         << Name << Type << Range;
9106     return QualType();
9107   }
9108
9109   if (DeduceInits.size() > 1) {
9110     Diag(DeduceInits[1]->getLocStart(),
9111          IsInitCapture ? diag::err_init_capture_multiple_expressions
9112                        : diag::err_auto_var_init_multiple_expressions)
9113         << Name << Type << Range;
9114     return QualType();
9115   }
9116
9117   Expr *DeduceInit = DeduceInits[0];
9118   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9119     Diag(Init->getLocStart(), IsInitCapture
9120                                   ? diag::err_init_capture_paren_braces
9121                                   : diag::err_auto_var_init_paren_braces)
9122         << isa<InitListExpr>(Init) << Name << Type << Range;
9123     return QualType();
9124   }
9125
9126   // Expressions default to 'id' when we're in a debugger.
9127   bool DefaultedAnyToId = false;
9128   if (getLangOpts().DebuggerCastResultToId &&
9129       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9130     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9131     if (Result.isInvalid()) {
9132       return QualType();
9133     }
9134     Init = Result.get();
9135     DefaultedAnyToId = true;
9136   }
9137
9138   QualType DeducedType;
9139   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9140     if (!IsInitCapture)
9141       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9142     else if (isa<InitListExpr>(Init))
9143       Diag(Range.getBegin(),
9144            diag::err_init_capture_deduction_failure_from_init_list)
9145           << Name
9146           << (DeduceInit->getType().isNull() ? TSI->getType()
9147                                              : DeduceInit->getType())
9148           << DeduceInit->getSourceRange();
9149     else
9150       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9151           << Name << TSI->getType()
9152           << (DeduceInit->getType().isNull() ? TSI->getType()
9153                                              : DeduceInit->getType())
9154           << DeduceInit->getSourceRange();
9155   }
9156
9157   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9158   // 'id' instead of a specific object type prevents most of our usual
9159   // checks.
9160   // We only want to warn outside of template instantiations, though:
9161   // inside a template, the 'id' could have come from a parameter.
9162   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9163       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9164     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9165     Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9166   }
9167
9168   return DeducedType;
9169 }
9170
9171 /// AddInitializerToDecl - Adds the initializer Init to the
9172 /// declaration dcl. If DirectInit is true, this is C++ direct
9173 /// initialization rather than copy initialization.
9174 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9175                                 bool DirectInit, bool TypeMayContainAuto) {
9176   // If there is no declaration, there was an error parsing it.  Just ignore
9177   // the initializer.
9178   if (!RealDecl || RealDecl->isInvalidDecl()) {
9179     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9180     return;
9181   }
9182
9183   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9184     // Pure-specifiers are handled in ActOnPureSpecifier.
9185     Diag(Method->getLocation(), diag::err_member_function_initialization)
9186       << Method->getDeclName() << Init->getSourceRange();
9187     Method->setInvalidDecl();
9188     return;
9189   }
9190
9191   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9192   if (!VDecl) {
9193     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9194     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9195     RealDecl->setInvalidDecl();
9196     return;
9197   }
9198
9199   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9200   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9201     // Attempt typo correction early so that the type of the init expression can
9202     // be deduced based on the chosen correction if the original init contains a
9203     // TypoExpr.
9204     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9205     if (!Res.isUsable()) {
9206       RealDecl->setInvalidDecl();
9207       return;
9208     }
9209     Init = Res.get();
9210
9211     QualType DeducedType = deduceVarTypeFromInitializer(
9212         VDecl, VDecl->getDeclName(), VDecl->getType(),
9213         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9214     if (DeducedType.isNull()) {
9215       RealDecl->setInvalidDecl();
9216       return;
9217     }
9218
9219     VDecl->setType(DeducedType);
9220     assert(VDecl->isLinkageValid());
9221
9222     // In ARC, infer lifetime.
9223     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9224       VDecl->setInvalidDecl();
9225
9226     // If this is a redeclaration, check that the type we just deduced matches
9227     // the previously declared type.
9228     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9229       // We never need to merge the type, because we cannot form an incomplete
9230       // array of auto, nor deduce such a type.
9231       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9232     }
9233
9234     // Check the deduced type is valid for a variable declaration.
9235     CheckVariableDeclarationType(VDecl);
9236     if (VDecl->isInvalidDecl())
9237       return;
9238   }
9239
9240   // dllimport cannot be used on variable definitions.
9241   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9242     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9243     VDecl->setInvalidDecl();
9244     return;
9245   }
9246
9247   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9248     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9249     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9250     VDecl->setInvalidDecl();
9251     return;
9252   }
9253
9254   if (!VDecl->getType()->isDependentType()) {
9255     // A definition must end up with a complete type, which means it must be
9256     // complete with the restriction that an array type might be completed by
9257     // the initializer; note that later code assumes this restriction.
9258     QualType BaseDeclType = VDecl->getType();
9259     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9260       BaseDeclType = Array->getElementType();
9261     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9262                             diag::err_typecheck_decl_incomplete_type)) {
9263       RealDecl->setInvalidDecl();
9264       return;
9265     }
9266
9267     // The variable can not have an abstract class type.
9268     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9269                                diag::err_abstract_type_in_decl,
9270                                AbstractVariableType))
9271       VDecl->setInvalidDecl();
9272   }
9273
9274   VarDecl *Def;
9275   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9276     NamedDecl *Hidden = nullptr;
9277     if (!hasVisibleDefinition(Def, &Hidden) && 
9278         (VDecl->getFormalLinkage() == InternalLinkage ||
9279          VDecl->getDescribedVarTemplate() ||
9280          VDecl->getNumTemplateParameterLists() ||
9281          VDecl->getDeclContext()->isDependentContext())) {
9282       // The previous definition is hidden, and multiple definitions are
9283       // permitted (in separate TUs). Form another definition of it.
9284     } else {
9285       Diag(VDecl->getLocation(), diag::err_redefinition)
9286         << VDecl->getDeclName();
9287       Diag(Def->getLocation(), diag::note_previous_definition);
9288       VDecl->setInvalidDecl();
9289       return;
9290     }
9291   }
9292
9293   if (getLangOpts().CPlusPlus) {
9294     // C++ [class.static.data]p4
9295     //   If a static data member is of const integral or const
9296     //   enumeration type, its declaration in the class definition can
9297     //   specify a constant-initializer which shall be an integral
9298     //   constant expression (5.19). In that case, the member can appear
9299     //   in integral constant expressions. The member shall still be
9300     //   defined in a namespace scope if it is used in the program and the
9301     //   namespace scope definition shall not contain an initializer.
9302     //
9303     // We already performed a redefinition check above, but for static
9304     // data members we also need to check whether there was an in-class
9305     // declaration with an initializer.
9306     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9307       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9308           << VDecl->getDeclName();
9309       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9310            diag::note_previous_initializer)
9311           << 0;
9312       return;
9313     }  
9314
9315     if (VDecl->hasLocalStorage())
9316       getCurFunction()->setHasBranchProtectedScope();
9317
9318     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9319       VDecl->setInvalidDecl();
9320       return;
9321     }
9322   }
9323
9324   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9325   // a kernel function cannot be initialized."
9326   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9327     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9328     VDecl->setInvalidDecl();
9329     return;
9330   }
9331
9332   // Get the decls type and save a reference for later, since
9333   // CheckInitializerTypes may change it.
9334   QualType DclT = VDecl->getType(), SavT = DclT;
9335   
9336   // Expressions default to 'id' when we're in a debugger
9337   // and we are assigning it to a variable of Objective-C pointer type.
9338   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9339       Init->getType() == Context.UnknownAnyTy) {
9340     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9341     if (Result.isInvalid()) {
9342       VDecl->setInvalidDecl();
9343       return;
9344     }
9345     Init = Result.get();
9346   }
9347
9348   // Perform the initialization.
9349   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9350   if (!VDecl->isInvalidDecl()) {
9351     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9352     InitializationKind Kind =
9353         DirectInit
9354             ? CXXDirectInit
9355                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9356                                                      Init->getLocStart(),
9357                                                      Init->getLocEnd())
9358                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9359             : InitializationKind::CreateCopy(VDecl->getLocation(),
9360                                              Init->getLocStart());
9361
9362     MultiExprArg Args = Init;
9363     if (CXXDirectInit)
9364       Args = MultiExprArg(CXXDirectInit->getExprs(),
9365                           CXXDirectInit->getNumExprs());
9366
9367     // Try to correct any TypoExprs in the initialization arguments.
9368     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9369       ExprResult Res = CorrectDelayedTyposInExpr(
9370           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9371             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9372             return Init.Failed() ? ExprError() : E;
9373           });
9374       if (Res.isInvalid()) {
9375         VDecl->setInvalidDecl();
9376       } else if (Res.get() != Args[Idx]) {
9377         Args[Idx] = Res.get();
9378       }
9379     }
9380     if (VDecl->isInvalidDecl())
9381       return;
9382
9383     InitializationSequence InitSeq(*this, Entity, Kind, Args);
9384     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9385     if (Result.isInvalid()) {
9386       VDecl->setInvalidDecl();
9387       return;
9388     }
9389
9390     Init = Result.getAs<Expr>();
9391   }
9392
9393   // Check for self-references within variable initializers.
9394   // Variables declared within a function/method body (except for references)
9395   // are handled by a dataflow analysis.
9396   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9397       VDecl->getType()->isReferenceType()) {
9398     CheckSelfReference(*this, RealDecl, Init, DirectInit);
9399   }
9400
9401   // If the type changed, it means we had an incomplete type that was
9402   // completed by the initializer. For example:
9403   //   int ary[] = { 1, 3, 5 };
9404   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9405   if (!VDecl->isInvalidDecl() && (DclT != SavT))
9406     VDecl->setType(DclT);
9407
9408   if (!VDecl->isInvalidDecl()) {
9409     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9410
9411     if (VDecl->hasAttr<BlocksAttr>())
9412       checkRetainCycles(VDecl, Init);
9413
9414     // It is safe to assign a weak reference into a strong variable.
9415     // Although this code can still have problems:
9416     //   id x = self.weakProp;
9417     //   id y = self.weakProp;
9418     // we do not warn to warn spuriously when 'x' and 'y' are on separate
9419     // paths through the function. This should be revisited if
9420     // -Wrepeated-use-of-weak is made flow-sensitive.
9421     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9422         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9423                          Init->getLocStart()))
9424       getCurFunction()->markSafeWeakUse(Init);
9425   }
9426
9427   // The initialization is usually a full-expression.
9428   //
9429   // FIXME: If this is a braced initialization of an aggregate, it is not
9430   // an expression, and each individual field initializer is a separate
9431   // full-expression. For instance, in:
9432   //
9433   //   struct Temp { ~Temp(); };
9434   //   struct S { S(Temp); };
9435   //   struct T { S a, b; } t = { Temp(), Temp() }
9436   //
9437   // we should destroy the first Temp before constructing the second.
9438   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9439                                           false,
9440                                           VDecl->isConstexpr());
9441   if (Result.isInvalid()) {
9442     VDecl->setInvalidDecl();
9443     return;
9444   }
9445   Init = Result.get();
9446
9447   // Attach the initializer to the decl.
9448   VDecl->setInit(Init);
9449
9450   if (VDecl->isLocalVarDecl()) {
9451     // C99 6.7.8p4: All the expressions in an initializer for an object that has
9452     // static storage duration shall be constant expressions or string literals.
9453     // C++ does not have this restriction.
9454     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9455       const Expr *Culprit;
9456       if (VDecl->getStorageClass() == SC_Static)
9457         CheckForConstantInitializer(Init, DclT);
9458       // C89 is stricter than C99 for non-static aggregate types.
9459       // C89 6.5.7p3: All the expressions [...] in an initializer list
9460       // for an object that has aggregate or union type shall be
9461       // constant expressions.
9462       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9463                isa<InitListExpr>(Init) &&
9464                !Init->isConstantInitializer(Context, false, &Culprit))
9465         Diag(Culprit->getExprLoc(),
9466              diag::ext_aggregate_init_not_constant)
9467           << Culprit->getSourceRange();
9468     }
9469   } else if (VDecl->isStaticDataMember() &&
9470              VDecl->getLexicalDeclContext()->isRecord()) {
9471     // This is an in-class initialization for a static data member, e.g.,
9472     //
9473     // struct S {
9474     //   static const int value = 17;
9475     // };
9476
9477     // C++ [class.mem]p4:
9478     //   A member-declarator can contain a constant-initializer only
9479     //   if it declares a static member (9.4) of const integral or
9480     //   const enumeration type, see 9.4.2.
9481     //
9482     // C++11 [class.static.data]p3:
9483     //   If a non-volatile const static data member is of integral or
9484     //   enumeration type, its declaration in the class definition can
9485     //   specify a brace-or-equal-initializer in which every initalizer-clause
9486     //   that is an assignment-expression is a constant expression. A static
9487     //   data member of literal type can be declared in the class definition
9488     //   with the constexpr specifier; if so, its declaration shall specify a
9489     //   brace-or-equal-initializer in which every initializer-clause that is
9490     //   an assignment-expression is a constant expression.
9491
9492     // Do nothing on dependent types.
9493     if (DclT->isDependentType()) {
9494
9495     // Allow any 'static constexpr' members, whether or not they are of literal
9496     // type. We separately check that every constexpr variable is of literal
9497     // type.
9498     } else if (VDecl->isConstexpr()) {
9499
9500     // Require constness.
9501     } else if (!DclT.isConstQualified()) {
9502       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9503         << Init->getSourceRange();
9504       VDecl->setInvalidDecl();
9505
9506     // We allow integer constant expressions in all cases.
9507     } else if (DclT->isIntegralOrEnumerationType()) {
9508       // Check whether the expression is a constant expression.
9509       SourceLocation Loc;
9510       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9511         // In C++11, a non-constexpr const static data member with an
9512         // in-class initializer cannot be volatile.
9513         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9514       else if (Init->isValueDependent())
9515         ; // Nothing to check.
9516       else if (Init->isIntegerConstantExpr(Context, &Loc))
9517         ; // Ok, it's an ICE!
9518       else if (Init->isEvaluatable(Context)) {
9519         // If we can constant fold the initializer through heroics, accept it,
9520         // but report this as a use of an extension for -pedantic.
9521         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9522           << Init->getSourceRange();
9523       } else {
9524         // Otherwise, this is some crazy unknown case.  Report the issue at the
9525         // location provided by the isIntegerConstantExpr failed check.
9526         Diag(Loc, diag::err_in_class_initializer_non_constant)
9527           << Init->getSourceRange();
9528         VDecl->setInvalidDecl();
9529       }
9530
9531     // We allow foldable floating-point constants as an extension.
9532     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9533       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9534       // it anyway and provide a fixit to add the 'constexpr'.
9535       if (getLangOpts().CPlusPlus11) {
9536         Diag(VDecl->getLocation(),
9537              diag::ext_in_class_initializer_float_type_cxx11)
9538             << DclT << Init->getSourceRange();
9539         Diag(VDecl->getLocStart(),
9540              diag::note_in_class_initializer_float_type_cxx11)
9541             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9542       } else {
9543         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9544           << DclT << Init->getSourceRange();
9545
9546         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9547           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9548             << Init->getSourceRange();
9549           VDecl->setInvalidDecl();
9550         }
9551       }
9552
9553     // Suggest adding 'constexpr' in C++11 for literal types.
9554     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9555       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9556         << DclT << Init->getSourceRange()
9557         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9558       VDecl->setConstexpr(true);
9559
9560     } else {
9561       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9562         << DclT << Init->getSourceRange();
9563       VDecl->setInvalidDecl();
9564     }
9565   } else if (VDecl->isFileVarDecl()) {
9566     if (VDecl->getStorageClass() == SC_Extern &&
9567         (!getLangOpts().CPlusPlus ||
9568          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9569            VDecl->isExternC())) &&
9570         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9571       Diag(VDecl->getLocation(), diag::warn_extern_init);
9572
9573     // C99 6.7.8p4. All file scoped initializers need to be constant.
9574     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9575       CheckForConstantInitializer(Init, DclT);
9576   }
9577
9578   // We will represent direct-initialization similarly to copy-initialization:
9579   //    int x(1);  -as-> int x = 1;
9580   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9581   //
9582   // Clients that want to distinguish between the two forms, can check for
9583   // direct initializer using VarDecl::getInitStyle().
9584   // A major benefit is that clients that don't particularly care about which
9585   // exactly form was it (like the CodeGen) can handle both cases without
9586   // special case code.
9587
9588   // C++ 8.5p11:
9589   // The form of initialization (using parentheses or '=') is generally
9590   // insignificant, but does matter when the entity being initialized has a
9591   // class type.
9592   if (CXXDirectInit) {
9593     assert(DirectInit && "Call-style initializer must be direct init.");
9594     VDecl->setInitStyle(VarDecl::CallInit);
9595   } else if (DirectInit) {
9596     // This must be list-initialization. No other way is direct-initialization.
9597     VDecl->setInitStyle(VarDecl::ListInit);
9598   }
9599
9600   CheckCompleteVariableDeclaration(VDecl);
9601 }
9602
9603 /// ActOnInitializerError - Given that there was an error parsing an
9604 /// initializer for the given declaration, try to return to some form
9605 /// of sanity.
9606 void Sema::ActOnInitializerError(Decl *D) {
9607   // Our main concern here is re-establishing invariants like "a
9608   // variable's type is either dependent or complete".
9609   if (!D || D->isInvalidDecl()) return;
9610
9611   VarDecl *VD = dyn_cast<VarDecl>(D);
9612   if (!VD) return;
9613
9614   // Auto types are meaningless if we can't make sense of the initializer.
9615   if (ParsingInitForAutoVars.count(D)) {
9616     D->setInvalidDecl();
9617     return;
9618   }
9619
9620   QualType Ty = VD->getType();
9621   if (Ty->isDependentType()) return;
9622
9623   // Require a complete type.
9624   if (RequireCompleteType(VD->getLocation(), 
9625                           Context.getBaseElementType(Ty),
9626                           diag::err_typecheck_decl_incomplete_type)) {
9627     VD->setInvalidDecl();
9628     return;
9629   }
9630
9631   // Require a non-abstract type.
9632   if (RequireNonAbstractType(VD->getLocation(), Ty,
9633                              diag::err_abstract_type_in_decl,
9634                              AbstractVariableType)) {
9635     VD->setInvalidDecl();
9636     return;
9637   }
9638
9639   // Don't bother complaining about constructors or destructors,
9640   // though.
9641 }
9642
9643 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9644                                   bool TypeMayContainAuto) {
9645   // If there is no declaration, there was an error parsing it. Just ignore it.
9646   if (!RealDecl)
9647     return;
9648
9649   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9650     QualType Type = Var->getType();
9651
9652     // C++11 [dcl.spec.auto]p3
9653     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9654       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9655         << Var->getDeclName() << Type;
9656       Var->setInvalidDecl();
9657       return;
9658     }
9659
9660     // C++11 [class.static.data]p3: A static data member can be declared with
9661     // the constexpr specifier; if so, its declaration shall specify
9662     // a brace-or-equal-initializer.
9663     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9664     // the definition of a variable [...] or the declaration of a static data
9665     // member.
9666     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9667       if (Var->isStaticDataMember())
9668         Diag(Var->getLocation(),
9669              diag::err_constexpr_static_mem_var_requires_init)
9670           << Var->getDeclName();
9671       else
9672         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9673       Var->setInvalidDecl();
9674       return;
9675     }
9676
9677     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
9678     // definition having the concept specifier is called a variable concept. A
9679     // concept definition refers to [...] a variable concept and its initializer.
9680     if (Var->isConcept()) {
9681       Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
9682       Var->setInvalidDecl();
9683       return;
9684     }
9685
9686     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9687     // be initialized.
9688     if (!Var->isInvalidDecl() &&
9689         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9690         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9691       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9692       Var->setInvalidDecl();
9693       return;
9694     }
9695
9696     switch (Var->isThisDeclarationADefinition()) {
9697     case VarDecl::Definition:
9698       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9699         break;
9700
9701       // We have an out-of-line definition of a static data member
9702       // that has an in-class initializer, so we type-check this like
9703       // a declaration. 
9704       //
9705       // Fall through
9706       
9707     case VarDecl::DeclarationOnly:
9708       // It's only a declaration. 
9709
9710       // Block scope. C99 6.7p7: If an identifier for an object is
9711       // declared with no linkage (C99 6.2.2p6), the type for the
9712       // object shall be complete.
9713       if (!Type->isDependentType() && Var->isLocalVarDecl() && 
9714           !Var->hasLinkage() && !Var->isInvalidDecl() &&
9715           RequireCompleteType(Var->getLocation(), Type,
9716                               diag::err_typecheck_decl_incomplete_type))
9717         Var->setInvalidDecl();
9718
9719       // Make sure that the type is not abstract.
9720       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9721           RequireNonAbstractType(Var->getLocation(), Type,
9722                                  diag::err_abstract_type_in_decl,
9723                                  AbstractVariableType))
9724         Var->setInvalidDecl();
9725       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9726           Var->getStorageClass() == SC_PrivateExtern) {
9727         Diag(Var->getLocation(), diag::warn_private_extern);
9728         Diag(Var->getLocation(), diag::note_private_extern);
9729       }
9730         
9731       return;
9732
9733     case VarDecl::TentativeDefinition:
9734       // File scope. C99 6.9.2p2: A declaration of an identifier for an
9735       // object that has file scope without an initializer, and without a
9736       // storage-class specifier or with the storage-class specifier "static",
9737       // constitutes a tentative definition. Note: A tentative definition with
9738       // external linkage is valid (C99 6.2.2p5).
9739       if (!Var->isInvalidDecl()) {
9740         if (const IncompleteArrayType *ArrayT
9741                                     = Context.getAsIncompleteArrayType(Type)) {
9742           if (RequireCompleteType(Var->getLocation(),
9743                                   ArrayT->getElementType(),
9744                                   diag::err_illegal_decl_array_incomplete_type))
9745             Var->setInvalidDecl();
9746         } else if (Var->getStorageClass() == SC_Static) {
9747           // C99 6.9.2p3: If the declaration of an identifier for an object is
9748           // a tentative definition and has internal linkage (C99 6.2.2p3), the
9749           // declared type shall not be an incomplete type.
9750           // NOTE: code such as the following
9751           //     static struct s;
9752           //     struct s { int a; };
9753           // is accepted by gcc. Hence here we issue a warning instead of
9754           // an error and we do not invalidate the static declaration.
9755           // NOTE: to avoid multiple warnings, only check the first declaration.
9756           if (Var->isFirstDecl())
9757             RequireCompleteType(Var->getLocation(), Type,
9758                                 diag::ext_typecheck_decl_incomplete_type);
9759         }
9760       }
9761
9762       // Record the tentative definition; we're done.
9763       if (!Var->isInvalidDecl())
9764         TentativeDefinitions.push_back(Var);
9765       return;
9766     }
9767
9768     // Provide a specific diagnostic for uninitialized variable
9769     // definitions with incomplete array type.
9770     if (Type->isIncompleteArrayType()) {
9771       Diag(Var->getLocation(),
9772            diag::err_typecheck_incomplete_array_needs_initializer);
9773       Var->setInvalidDecl();
9774       return;
9775     }
9776
9777     // Provide a specific diagnostic for uninitialized variable
9778     // definitions with reference type.
9779     if (Type->isReferenceType()) {
9780       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9781         << Var->getDeclName()
9782         << SourceRange(Var->getLocation(), Var->getLocation());
9783       Var->setInvalidDecl();
9784       return;
9785     }
9786
9787     // Do not attempt to type-check the default initializer for a
9788     // variable with dependent type.
9789     if (Type->isDependentType())
9790       return;
9791
9792     if (Var->isInvalidDecl())
9793       return;
9794
9795     if (!Var->hasAttr<AliasAttr>()) {
9796       if (RequireCompleteType(Var->getLocation(),
9797                               Context.getBaseElementType(Type),
9798                               diag::err_typecheck_decl_incomplete_type)) {
9799         Var->setInvalidDecl();
9800         return;
9801       }
9802     } else {
9803       return;
9804     }
9805
9806     // The variable can not have an abstract class type.
9807     if (RequireNonAbstractType(Var->getLocation(), Type,
9808                                diag::err_abstract_type_in_decl,
9809                                AbstractVariableType)) {
9810       Var->setInvalidDecl();
9811       return;
9812     }
9813
9814     // Check for jumps past the implicit initializer.  C++0x
9815     // clarifies that this applies to a "variable with automatic
9816     // storage duration", not a "local variable".
9817     // C++11 [stmt.dcl]p3
9818     //   A program that jumps from a point where a variable with automatic
9819     //   storage duration is not in scope to a point where it is in scope is
9820     //   ill-formed unless the variable has scalar type, class type with a
9821     //   trivial default constructor and a trivial destructor, a cv-qualified
9822     //   version of one of these types, or an array of one of the preceding
9823     //   types and is declared without an initializer.
9824     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9825       if (const RecordType *Record
9826             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
9827         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9828         // Mark the function for further checking even if the looser rules of
9829         // C++11 do not require such checks, so that we can diagnose
9830         // incompatibilities with C++98.
9831         if (!CXXRecord->isPOD())
9832           getCurFunction()->setHasBranchProtectedScope();
9833       }
9834     }
9835     
9836     // C++03 [dcl.init]p9:
9837     //   If no initializer is specified for an object, and the
9838     //   object is of (possibly cv-qualified) non-POD class type (or
9839     //   array thereof), the object shall be default-initialized; if
9840     //   the object is of const-qualified type, the underlying class
9841     //   type shall have a user-declared default
9842     //   constructor. Otherwise, if no initializer is specified for
9843     //   a non- static object, the object and its subobjects, if
9844     //   any, have an indeterminate initial value); if the object
9845     //   or any of its subobjects are of const-qualified type, the
9846     //   program is ill-formed.
9847     // C++0x [dcl.init]p11:
9848     //   If no initializer is specified for an object, the object is
9849     //   default-initialized; [...].
9850     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
9851     InitializationKind Kind
9852       = InitializationKind::CreateDefault(Var->getLocation());
9853
9854     InitializationSequence InitSeq(*this, Entity, Kind, None);
9855     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
9856     if (Init.isInvalid())
9857       Var->setInvalidDecl();
9858     else if (Init.get()) {
9859       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
9860       // This is important for template substitution.
9861       Var->setInitStyle(VarDecl::CallInit);
9862     }
9863
9864     CheckCompleteVariableDeclaration(Var);
9865   }
9866 }
9867
9868 void Sema::ActOnCXXForRangeDecl(Decl *D) {
9869   VarDecl *VD = dyn_cast<VarDecl>(D);
9870   if (!VD) {
9871     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9872     D->setInvalidDecl();
9873     return;
9874   }
9875
9876   VD->setCXXForRangeDecl(true);
9877
9878   // for-range-declaration cannot be given a storage class specifier.
9879   int Error = -1;
9880   switch (VD->getStorageClass()) {
9881   case SC_None:
9882     break;
9883   case SC_Extern:
9884     Error = 0;
9885     break;
9886   case SC_Static:
9887     Error = 1;
9888     break;
9889   case SC_PrivateExtern:
9890     Error = 2;
9891     break;
9892   case SC_Auto:
9893     Error = 3;
9894     break;
9895   case SC_Register:
9896     Error = 4;
9897     break;
9898   }
9899   if (Error != -1) {
9900     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
9901       << VD->getDeclName() << Error;
9902     D->setInvalidDecl();
9903   }
9904 }
9905
9906 StmtResult
9907 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
9908                                  IdentifierInfo *Ident,
9909                                  ParsedAttributes &Attrs,
9910                                  SourceLocation AttrEnd) {
9911   // C++1y [stmt.iter]p1:
9912   //   A range-based for statement of the form
9913   //      for ( for-range-identifier : for-range-initializer ) statement
9914   //   is equivalent to
9915   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
9916   DeclSpec DS(Attrs.getPool().getFactory());
9917
9918   const char *PrevSpec;
9919   unsigned DiagID;
9920   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
9921                      getPrintingPolicy());
9922
9923   Declarator D(DS, Declarator::ForContext);
9924   D.SetIdentifier(Ident, IdentLoc);
9925   D.takeAttributes(Attrs, AttrEnd);
9926
9927   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
9928   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
9929                 EmptyAttrs, IdentLoc);
9930   Decl *Var = ActOnDeclarator(S, D);
9931   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
9932   FinalizeDeclaration(Var);
9933   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
9934                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
9935 }
9936
9937 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
9938   if (var->isInvalidDecl()) return;
9939
9940   // In Objective-C, don't allow jumps past the implicit initialization of a
9941   // local retaining variable.
9942   if (getLangOpts().ObjC1 &&
9943       var->hasLocalStorage()) {
9944     switch (var->getType().getObjCLifetime()) {
9945     case Qualifiers::OCL_None:
9946     case Qualifiers::OCL_ExplicitNone:
9947     case Qualifiers::OCL_Autoreleasing:
9948       break;
9949
9950     case Qualifiers::OCL_Weak:
9951     case Qualifiers::OCL_Strong:
9952       getCurFunction()->setHasBranchProtectedScope();
9953       break;
9954     }
9955   }
9956
9957   // Warn about externally-visible variables being defined without a
9958   // prior declaration.  We only want to do this for global
9959   // declarations, but we also specifically need to avoid doing it for
9960   // class members because the linkage of an anonymous class can
9961   // change if it's later given a typedef name.
9962   if (var->isThisDeclarationADefinition() &&
9963       var->getDeclContext()->getRedeclContext()->isFileContext() &&
9964       var->isExternallyVisible() && var->hasLinkage() &&
9965       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
9966                                   var->getLocation())) {
9967     // Find a previous declaration that's not a definition.
9968     VarDecl *prev = var->getPreviousDecl();
9969     while (prev && prev->isThisDeclarationADefinition())
9970       prev = prev->getPreviousDecl();
9971
9972     if (!prev)
9973       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
9974   }
9975
9976   if (var->getTLSKind() == VarDecl::TLS_Static) {
9977     const Expr *Culprit;
9978     if (var->getType().isDestructedType()) {
9979       // GNU C++98 edits for __thread, [basic.start.term]p3:
9980       //   The type of an object with thread storage duration shall not
9981       //   have a non-trivial destructor.
9982       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
9983       if (getLangOpts().CPlusPlus11)
9984         Diag(var->getLocation(), diag::note_use_thread_local);
9985     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
9986                !var->getInit()->isConstantInitializer(
9987                    Context, var->getType()->isReferenceType(), &Culprit)) {
9988       // GNU C++98 edits for __thread, [basic.start.init]p4:
9989       //   An object of thread storage duration shall not require dynamic
9990       //   initialization.
9991       // FIXME: Need strict checking here.
9992       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
9993         << Culprit->getSourceRange();
9994       if (getLangOpts().CPlusPlus11)
9995         Diag(var->getLocation(), diag::note_use_thread_local);
9996     }
9997
9998   }
9999
10000   // Apply section attributes and pragmas to global variables.
10001   bool GlobalStorage = var->hasGlobalStorage();
10002   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10003       ActiveTemplateInstantiations.empty()) {
10004     PragmaStack<StringLiteral *> *Stack = nullptr;
10005     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10006     if (var->getType().isConstQualified())
10007       Stack = &ConstSegStack;
10008     else if (!var->getInit()) {
10009       Stack = &BSSSegStack;
10010       SectionFlags |= ASTContext::PSF_Write;
10011     } else {
10012       Stack = &DataSegStack;
10013       SectionFlags |= ASTContext::PSF_Write;
10014     }
10015     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10016       var->addAttr(SectionAttr::CreateImplicit(
10017           Context, SectionAttr::Declspec_allocate,
10018           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10019     }
10020     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10021       if (UnifySection(SA->getName(), SectionFlags, var))
10022         var->dropAttr<SectionAttr>();
10023
10024     // Apply the init_seg attribute if this has an initializer.  If the
10025     // initializer turns out to not be dynamic, we'll end up ignoring this
10026     // attribute.
10027     if (CurInitSeg && var->getInit())
10028       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10029                                                CurInitSegLoc));
10030   }
10031
10032   // All the following checks are C++ only.
10033   if (!getLangOpts().CPlusPlus) return;
10034
10035   QualType type = var->getType();
10036   if (type->isDependentType()) return;
10037
10038   // __block variables might require us to capture a copy-initializer.
10039   if (var->hasAttr<BlocksAttr>()) {
10040     // It's currently invalid to ever have a __block variable with an
10041     // array type; should we diagnose that here?
10042
10043     // Regardless, we don't want to ignore array nesting when
10044     // constructing this copy.
10045     if (type->isStructureOrClassType()) {
10046       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10047       SourceLocation poi = var->getLocation();
10048       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10049       ExprResult result
10050         = PerformMoveOrCopyInitialization(
10051             InitializedEntity::InitializeBlock(poi, type, false),
10052             var, var->getType(), varRef, /*AllowNRVO=*/true);
10053       if (!result.isInvalid()) {
10054         result = MaybeCreateExprWithCleanups(result);
10055         Expr *init = result.getAs<Expr>();
10056         Context.setBlockVarCopyInits(var, init);
10057       }
10058     }
10059   }
10060
10061   Expr *Init = var->getInit();
10062   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10063   QualType baseType = Context.getBaseElementType(type);
10064
10065   if (!var->getDeclContext()->isDependentContext() &&
10066       Init && !Init->isValueDependent()) {
10067     if (IsGlobal && !var->isConstexpr() &&
10068         !getDiagnostics().isIgnored(diag::warn_global_constructor,
10069                                     var->getLocation())) {
10070       // Warn about globals which don't have a constant initializer.  Don't
10071       // warn about globals with a non-trivial destructor because we already
10072       // warned about them.
10073       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10074       if (!(RD && !RD->hasTrivialDestructor()) &&
10075           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10076         Diag(var->getLocation(), diag::warn_global_constructor)
10077           << Init->getSourceRange();
10078     }
10079
10080     if (var->isConstexpr()) {
10081       SmallVector<PartialDiagnosticAt, 8> Notes;
10082       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10083         SourceLocation DiagLoc = var->getLocation();
10084         // If the note doesn't add any useful information other than a source
10085         // location, fold it into the primary diagnostic.
10086         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10087               diag::note_invalid_subexpr_in_const_expr) {
10088           DiagLoc = Notes[0].first;
10089           Notes.clear();
10090         }
10091         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10092           << var << Init->getSourceRange();
10093         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10094           Diag(Notes[I].first, Notes[I].second);
10095       }
10096     } else if (var->isUsableInConstantExpressions(Context)) {
10097       // Check whether the initializer of a const variable of integral or
10098       // enumeration type is an ICE now, since we can't tell whether it was
10099       // initialized by a constant expression if we check later.
10100       var->checkInitIsICE();
10101     }
10102   }
10103
10104   // Require the destructor.
10105   if (const RecordType *recordType = baseType->getAs<RecordType>())
10106     FinalizeVarWithDestructor(var, recordType);
10107 }
10108
10109 /// \brief Determines if a variable's alignment is dependent.
10110 static bool hasDependentAlignment(VarDecl *VD) {
10111   if (VD->getType()->isDependentType())
10112     return true;
10113   for (auto *I : VD->specific_attrs<AlignedAttr>())
10114     if (I->isAlignmentDependent())
10115       return true;
10116   return false;
10117 }
10118
10119 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10120 /// any semantic actions necessary after any initializer has been attached.
10121 void
10122 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10123   // Note that we are no longer parsing the initializer for this declaration.
10124   ParsingInitForAutoVars.erase(ThisDecl);
10125
10126   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10127   if (!VD)
10128     return;
10129
10130   checkAttributesAfterMerging(*this, *VD);
10131
10132   // Perform TLS alignment check here after attributes attached to the variable
10133   // which may affect the alignment have been processed. Only perform the check
10134   // if the target has a maximum TLS alignment (zero means no constraints).
10135   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10136     // Protect the check so that it's not performed on dependent types and
10137     // dependent alignments (we can't determine the alignment in that case).
10138     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10139       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10140       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10141         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10142           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10143           << (unsigned)MaxAlignChars.getQuantity();
10144       }
10145     }
10146   }
10147
10148   // Static locals inherit dll attributes from their function.
10149   if (VD->isStaticLocal()) {
10150     if (FunctionDecl *FD =
10151             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10152       if (Attr *A = getDLLAttr(FD)) {
10153         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10154         NewAttr->setInherited(true);
10155         VD->addAttr(NewAttr);
10156       }
10157     }
10158   }
10159
10160   // Grab the dllimport or dllexport attribute off of the VarDecl.
10161   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10162
10163   // Imported static data members cannot be defined out-of-line.
10164   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10165     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10166         VD->isThisDeclarationADefinition()) {
10167       // We allow definitions of dllimport class template static data members
10168       // with a warning.
10169       CXXRecordDecl *Context =
10170         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10171       bool IsClassTemplateMember =
10172           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10173           Context->getDescribedClassTemplate();
10174
10175       Diag(VD->getLocation(),
10176            IsClassTemplateMember
10177                ? diag::warn_attribute_dllimport_static_field_definition
10178                : diag::err_attribute_dllimport_static_field_definition);
10179       Diag(IA->getLocation(), diag::note_attribute);
10180       if (!IsClassTemplateMember)
10181         VD->setInvalidDecl();
10182     }
10183   }
10184
10185   // dllimport/dllexport variables cannot be thread local, their TLS index
10186   // isn't exported with the variable.
10187   if (DLLAttr && VD->getTLSKind()) {
10188     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10189     if (F && getDLLAttr(F)) {
10190       assert(VD->isStaticLocal());
10191       // But if this is a static local in a dlimport/dllexport function, the
10192       // function will never be inlined, which means the var would never be
10193       // imported, so having it marked import/export is safe.
10194     } else {
10195       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10196                                                                     << DLLAttr;
10197       VD->setInvalidDecl();
10198     }
10199   }
10200
10201   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10202     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10203       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10204       VD->dropAttr<UsedAttr>();
10205     }
10206   }
10207
10208   const DeclContext *DC = VD->getDeclContext();
10209   // If there's a #pragma GCC visibility in scope, and this isn't a class
10210   // member, set the visibility of this variable.
10211   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10212     AddPushedVisibilityAttribute(VD);
10213
10214   // FIXME: Warn on unused templates.
10215   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10216       !isa<VarTemplatePartialSpecializationDecl>(VD))
10217     MarkUnusedFileScopedDecl(VD);
10218
10219   // Now we have parsed the initializer and can update the table of magic
10220   // tag values.
10221   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10222       !VD->getType()->isIntegralOrEnumerationType())
10223     return;
10224
10225   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10226     const Expr *MagicValueExpr = VD->getInit();
10227     if (!MagicValueExpr) {
10228       continue;
10229     }
10230     llvm::APSInt MagicValueInt;
10231     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10232       Diag(I->getRange().getBegin(),
10233            diag::err_type_tag_for_datatype_not_ice)
10234         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10235       continue;
10236     }
10237     if (MagicValueInt.getActiveBits() > 64) {
10238       Diag(I->getRange().getBegin(),
10239            diag::err_type_tag_for_datatype_too_large)
10240         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10241       continue;
10242     }
10243     uint64_t MagicValue = MagicValueInt.getZExtValue();
10244     RegisterTypeTagForDatatype(I->getArgumentKind(),
10245                                MagicValue,
10246                                I->getMatchingCType(),
10247                                I->getLayoutCompatible(),
10248                                I->getMustBeNull());
10249   }
10250 }
10251
10252 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10253                                                    ArrayRef<Decl *> Group) {
10254   SmallVector<Decl*, 8> Decls;
10255
10256   if (DS.isTypeSpecOwned())
10257     Decls.push_back(DS.getRepAsDecl());
10258
10259   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10260   for (unsigned i = 0, e = Group.size(); i != e; ++i)
10261     if (Decl *D = Group[i]) {
10262       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10263         if (!FirstDeclaratorInGroup)
10264           FirstDeclaratorInGroup = DD;
10265       Decls.push_back(D);
10266     }
10267
10268   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10269     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10270       handleTagNumbering(Tag, S);
10271       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10272           getLangOpts().CPlusPlus)
10273         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10274     }
10275   }
10276
10277   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10278 }
10279
10280 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10281 /// group, performing any necessary semantic checking.
10282 Sema::DeclGroupPtrTy
10283 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10284                            bool TypeMayContainAuto) {
10285   // C++0x [dcl.spec.auto]p7:
10286   //   If the type deduced for the template parameter U is not the same in each
10287   //   deduction, the program is ill-formed.
10288   // FIXME: When initializer-list support is added, a distinction is needed
10289   // between the deduced type U and the deduced type which 'auto' stands for.
10290   //   auto a = 0, b = { 1, 2, 3 };
10291   // is legal because the deduced type U is 'int' in both cases.
10292   if (TypeMayContainAuto && Group.size() > 1) {
10293     QualType Deduced;
10294     CanQualType DeducedCanon;
10295     VarDecl *DeducedDecl = nullptr;
10296     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10297       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10298         AutoType *AT = D->getType()->getContainedAutoType();
10299         // Don't reissue diagnostics when instantiating a template.
10300         if (AT && D->isInvalidDecl())
10301           break;
10302         QualType U = AT ? AT->getDeducedType() : QualType();
10303         if (!U.isNull()) {
10304           CanQualType UCanon = Context.getCanonicalType(U);
10305           if (Deduced.isNull()) {
10306             Deduced = U;
10307             DeducedCanon = UCanon;
10308             DeducedDecl = D;
10309           } else if (DeducedCanon != UCanon) {
10310             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10311                  diag::err_auto_different_deductions)
10312               << (unsigned)AT->getKeyword()
10313               << Deduced << DeducedDecl->getDeclName()
10314               << U << D->getDeclName()
10315               << DeducedDecl->getInit()->getSourceRange()
10316               << D->getInit()->getSourceRange();
10317             D->setInvalidDecl();
10318             break;
10319           }
10320         }
10321       }
10322     }
10323   }
10324
10325   ActOnDocumentableDecls(Group);
10326
10327   return DeclGroupPtrTy::make(
10328       DeclGroupRef::Create(Context, Group.data(), Group.size()));
10329 }
10330
10331 void Sema::ActOnDocumentableDecl(Decl *D) {
10332   ActOnDocumentableDecls(D);
10333 }
10334
10335 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10336   // Don't parse the comment if Doxygen diagnostics are ignored.
10337   if (Group.empty() || !Group[0])
10338     return;
10339
10340   if (Diags.isIgnored(diag::warn_doc_param_not_found,
10341                       Group[0]->getLocation()) &&
10342       Diags.isIgnored(diag::warn_unknown_comment_command_name,
10343                       Group[0]->getLocation()))
10344     return;
10345
10346   if (Group.size() >= 2) {
10347     // This is a decl group.  Normally it will contain only declarations
10348     // produced from declarator list.  But in case we have any definitions or
10349     // additional declaration references:
10350     //   'typedef struct S {} S;'
10351     //   'typedef struct S *S;'
10352     //   'struct S *pS;'
10353     // FinalizeDeclaratorGroup adds these as separate declarations.
10354     Decl *MaybeTagDecl = Group[0];
10355     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10356       Group = Group.slice(1);
10357     }
10358   }
10359
10360   // See if there are any new comments that are not attached to a decl.
10361   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10362   if (!Comments.empty() &&
10363       !Comments.back()->isAttached()) {
10364     // There is at least one comment that not attached to a decl.
10365     // Maybe it should be attached to one of these decls?
10366     //
10367     // Note that this way we pick up not only comments that precede the
10368     // declaration, but also comments that *follow* the declaration -- thanks to
10369     // the lookahead in the lexer: we've consumed the semicolon and looked
10370     // ahead through comments.
10371     for (unsigned i = 0, e = Group.size(); i != e; ++i)
10372       Context.getCommentForDecl(Group[i], &PP);
10373   }
10374 }
10375
10376 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10377 /// to introduce parameters into function prototype scope.
10378 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10379   const DeclSpec &DS = D.getDeclSpec();
10380
10381   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10382
10383   // C++03 [dcl.stc]p2 also permits 'auto'.
10384   StorageClass SC = SC_None;
10385   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10386     SC = SC_Register;
10387   } else if (getLangOpts().CPlusPlus &&
10388              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10389     SC = SC_Auto;
10390   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10391     Diag(DS.getStorageClassSpecLoc(),
10392          diag::err_invalid_storage_class_in_func_decl);
10393     D.getMutableDeclSpec().ClearStorageClassSpecs();
10394   }
10395
10396   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10397     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10398       << DeclSpec::getSpecifierName(TSCS);
10399   if (DS.isConstexprSpecified())
10400     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10401       << 0;
10402   if (DS.isConceptSpecified())
10403     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10404
10405   DiagnoseFunctionSpecifiers(DS);
10406
10407   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10408   QualType parmDeclType = TInfo->getType();
10409
10410   if (getLangOpts().CPlusPlus) {
10411     // Check that there are no default arguments inside the type of this
10412     // parameter.
10413     CheckExtraCXXDefaultArguments(D);
10414     
10415     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10416     if (D.getCXXScopeSpec().isSet()) {
10417       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10418         << D.getCXXScopeSpec().getRange();
10419       D.getCXXScopeSpec().clear();
10420     }
10421   }
10422
10423   // Ensure we have a valid name
10424   IdentifierInfo *II = nullptr;
10425   if (D.hasName()) {
10426     II = D.getIdentifier();
10427     if (!II) {
10428       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10429         << GetNameForDeclarator(D).getName();
10430       D.setInvalidType(true);
10431     }
10432   }
10433
10434   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10435   if (II) {
10436     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10437                    ForRedeclaration);
10438     LookupName(R, S);
10439     if (R.isSingleResult()) {
10440       NamedDecl *PrevDecl = R.getFoundDecl();
10441       if (PrevDecl->isTemplateParameter()) {
10442         // Maybe we will complain about the shadowed template parameter.
10443         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10444         // Just pretend that we didn't see the previous declaration.
10445         PrevDecl = nullptr;
10446       } else if (S->isDeclScope(PrevDecl)) {
10447         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10448         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10449
10450         // Recover by removing the name
10451         II = nullptr;
10452         D.SetIdentifier(nullptr, D.getIdentifierLoc());
10453         D.setInvalidType(true);
10454       }
10455     }
10456   }
10457
10458   // Temporarily put parameter variables in the translation unit, not
10459   // the enclosing context.  This prevents them from accidentally
10460   // looking like class members in C++.
10461   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10462                                     D.getLocStart(),
10463                                     D.getIdentifierLoc(), II,
10464                                     parmDeclType, TInfo,
10465                                     SC);
10466
10467   if (D.isInvalidType())
10468     New->setInvalidDecl();
10469
10470   assert(S->isFunctionPrototypeScope());
10471   assert(S->getFunctionPrototypeDepth() >= 1);
10472   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10473                     S->getNextFunctionPrototypeIndex());
10474   
10475   // Add the parameter declaration into this scope.
10476   S->AddDecl(New);
10477   if (II)
10478     IdResolver.AddDecl(New);
10479
10480   ProcessDeclAttributes(S, New, D);
10481
10482   if (D.getDeclSpec().isModulePrivateSpecified())
10483     Diag(New->getLocation(), diag::err_module_private_local)
10484       << 1 << New->getDeclName()
10485       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10486       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10487
10488   if (New->hasAttr<BlocksAttr>()) {
10489     Diag(New->getLocation(), diag::err_block_on_nonlocal);
10490   }
10491   return New;
10492 }
10493
10494 /// \brief Synthesizes a variable for a parameter arising from a
10495 /// typedef.
10496 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10497                                               SourceLocation Loc,
10498                                               QualType T) {
10499   /* FIXME: setting StartLoc == Loc.
10500      Would it be worth to modify callers so as to provide proper source
10501      location for the unnamed parameters, embedding the parameter's type? */
10502   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10503                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
10504                                            SC_None, nullptr);
10505   Param->setImplicit();
10506   return Param;
10507 }
10508
10509 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
10510                                     ParmVarDecl * const *ParamEnd) {
10511   // Don't diagnose unused-parameter errors in template instantiations; we
10512   // will already have done so in the template itself.
10513   if (!ActiveTemplateInstantiations.empty())
10514     return;
10515
10516   for (; Param != ParamEnd; ++Param) {
10517     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10518         !(*Param)->hasAttr<UnusedAttr>()) {
10519       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10520         << (*Param)->getDeclName();
10521     }
10522   }
10523 }
10524
10525 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
10526                                                   ParmVarDecl * const *ParamEnd,
10527                                                   QualType ReturnTy,
10528                                                   NamedDecl *D) {
10529   if (LangOpts.NumLargeByValueCopy == 0) // No check.
10530     return;
10531
10532   // Warn if the return value is pass-by-value and larger than the specified
10533   // threshold.
10534   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10535     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10536     if (Size > LangOpts.NumLargeByValueCopy)
10537       Diag(D->getLocation(), diag::warn_return_value_size)
10538           << D->getDeclName() << Size;
10539   }
10540
10541   // Warn if any parameter is pass-by-value and larger than the specified
10542   // threshold.
10543   for (; Param != ParamEnd; ++Param) {
10544     QualType T = (*Param)->getType();
10545     if (T->isDependentType() || !T.isPODType(Context))
10546       continue;
10547     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10548     if (Size > LangOpts.NumLargeByValueCopy)
10549       Diag((*Param)->getLocation(), diag::warn_parameter_size)
10550           << (*Param)->getDeclName() << Size;
10551   }
10552 }
10553
10554 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10555                                   SourceLocation NameLoc, IdentifierInfo *Name,
10556                                   QualType T, TypeSourceInfo *TSInfo,
10557                                   StorageClass SC) {
10558   // In ARC, infer a lifetime qualifier for appropriate parameter types.
10559   if (getLangOpts().ObjCAutoRefCount &&
10560       T.getObjCLifetime() == Qualifiers::OCL_None &&
10561       T->isObjCLifetimeType()) {
10562
10563     Qualifiers::ObjCLifetime lifetime;
10564
10565     // Special cases for arrays:
10566     //   - if it's const, use __unsafe_unretained
10567     //   - otherwise, it's an error
10568     if (T->isArrayType()) {
10569       if (!T.isConstQualified()) {
10570         DelayedDiagnostics.add(
10571             sema::DelayedDiagnostic::makeForbiddenType(
10572             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10573       }
10574       lifetime = Qualifiers::OCL_ExplicitNone;
10575     } else {
10576       lifetime = T->getObjCARCImplicitLifetime();
10577     }
10578     T = Context.getLifetimeQualifiedType(T, lifetime);
10579   }
10580
10581   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10582                                          Context.getAdjustedParameterType(T), 
10583                                          TSInfo, SC, nullptr);
10584
10585   // Parameters can not be abstract class types.
10586   // For record types, this is done by the AbstractClassUsageDiagnoser once
10587   // the class has been completely parsed.
10588   if (!CurContext->isRecord() &&
10589       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10590                              AbstractParamType))
10591     New->setInvalidDecl();
10592
10593   // Parameter declarators cannot be interface types. All ObjC objects are
10594   // passed by reference.
10595   if (T->isObjCObjectType()) {
10596     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10597     Diag(NameLoc,
10598          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10599       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10600     T = Context.getObjCObjectPointerType(T);
10601     New->setType(T);
10602   }
10603
10604   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 
10605   // duration shall not be qualified by an address-space qualifier."
10606   // Since all parameters have automatic store duration, they can not have
10607   // an address space.
10608   if (T.getAddressSpace() != 0) {
10609     // OpenCL allows function arguments declared to be an array of a type
10610     // to be qualified with an address space.
10611     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10612       Diag(NameLoc, diag::err_arg_with_address_space);
10613       New->setInvalidDecl();
10614     }
10615   }   
10616
10617   return New;
10618 }
10619
10620 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10621                                            SourceLocation LocAfterDecls) {
10622   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10623
10624   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10625   // for a K&R function.
10626   if (!FTI.hasPrototype) {
10627     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10628       --i;
10629       if (FTI.Params[i].Param == nullptr) {
10630         SmallString<256> Code;
10631         llvm::raw_svector_ostream(Code)
10632             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10633         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10634             << FTI.Params[i].Ident
10635             << FixItHint::CreateInsertion(LocAfterDecls, Code);
10636
10637         // Implicitly declare the argument as type 'int' for lack of a better
10638         // type.
10639         AttributeFactory attrs;
10640         DeclSpec DS(attrs);
10641         const char* PrevSpec; // unused
10642         unsigned DiagID; // unused
10643         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10644                            DiagID, Context.getPrintingPolicy());
10645         // Use the identifier location for the type source range.
10646         DS.SetRangeStart(FTI.Params[i].IdentLoc);
10647         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10648         Declarator ParamD(DS, Declarator::KNRTypeListContext);
10649         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10650         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10651       }
10652     }
10653   }
10654 }
10655
10656 Decl *
10657 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
10658                               MultiTemplateParamsArg TemplateParameterLists,
10659                               SkipBodyInfo *SkipBody) {
10660   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10661   assert(D.isFunctionDeclarator() && "Not a function declarator!");
10662   Scope *ParentScope = FnBodyScope->getParent();
10663
10664   D.setFunctionDefinitionKind(FDK_Definition);
10665   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
10666   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
10667 }
10668
10669 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10670   Consumer.HandleInlineMethodDefinition(D);
10671 }
10672
10673 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 
10674                              const FunctionDecl*& PossibleZeroParamPrototype) {
10675   // Don't warn about invalid declarations.
10676   if (FD->isInvalidDecl())
10677     return false;
10678
10679   // Or declarations that aren't global.
10680   if (!FD->isGlobal())
10681     return false;
10682
10683   // Don't warn about C++ member functions.
10684   if (isa<CXXMethodDecl>(FD))
10685     return false;
10686
10687   // Don't warn about 'main'.
10688   if (FD->isMain())
10689     return false;
10690
10691   // Don't warn about inline functions.
10692   if (FD->isInlined())
10693     return false;
10694
10695   // Don't warn about function templates.
10696   if (FD->getDescribedFunctionTemplate())
10697     return false;
10698
10699   // Don't warn about function template specializations.
10700   if (FD->isFunctionTemplateSpecialization())
10701     return false;
10702
10703   // Don't warn for OpenCL kernels.
10704   if (FD->hasAttr<OpenCLKernelAttr>())
10705     return false;
10706
10707   // Don't warn on explicitly deleted functions.
10708   if (FD->isDeleted())
10709     return false;
10710
10711   bool MissingPrototype = true;
10712   for (const FunctionDecl *Prev = FD->getPreviousDecl();
10713        Prev; Prev = Prev->getPreviousDecl()) {
10714     // Ignore any declarations that occur in function or method
10715     // scope, because they aren't visible from the header.
10716     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10717       continue;
10718
10719     MissingPrototype = !Prev->getType()->isFunctionProtoType();
10720     if (FD->getNumParams() == 0)
10721       PossibleZeroParamPrototype = Prev;
10722     break;
10723   }
10724
10725   return MissingPrototype;
10726 }
10727
10728 void
10729 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10730                                    const FunctionDecl *EffectiveDefinition,
10731                                    SkipBodyInfo *SkipBody) {
10732   // Don't complain if we're in GNU89 mode and the previous definition
10733   // was an extern inline function.
10734   const FunctionDecl *Definition = EffectiveDefinition;
10735   if (!Definition)
10736     if (!FD->isDefined(Definition))
10737       return;
10738
10739   if (canRedefineFunction(Definition, getLangOpts()))
10740     return;
10741
10742   // If we don't have a visible definition of the function, and it's inline or
10743   // a template, skip the new definition.
10744   if (SkipBody && !hasVisibleDefinition(Definition) &&
10745       (Definition->getFormalLinkage() == InternalLinkage ||
10746        Definition->isInlined() ||
10747        Definition->getDescribedFunctionTemplate() ||
10748        Definition->getNumTemplateParameterLists())) {
10749     SkipBody->ShouldSkip = true;
10750     if (auto *TD = Definition->getDescribedFunctionTemplate())
10751       makeMergedDefinitionVisible(TD, FD->getLocation());
10752     else
10753       makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
10754                                   FD->getLocation());
10755     return;
10756   }
10757
10758   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10759       Definition->getStorageClass() == SC_Extern)
10760     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10761         << FD->getDeclName() << getLangOpts().CPlusPlus;
10762   else
10763     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10764
10765   Diag(Definition->getLocation(), diag::note_previous_definition);
10766   FD->setInvalidDecl();
10767 }
10768
10769
10770 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 
10771                                    Sema &S) {
10772   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10773   
10774   LambdaScopeInfo *LSI = S.PushLambdaScope();
10775   LSI->CallOperator = CallOperator;
10776   LSI->Lambda = LambdaClass;
10777   LSI->ReturnType = CallOperator->getReturnType();
10778   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10779
10780   if (LCD == LCD_None)
10781     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10782   else if (LCD == LCD_ByCopy)
10783     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10784   else if (LCD == LCD_ByRef)
10785     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10786   DeclarationNameInfo DNI = CallOperator->getNameInfo();
10787     
10788   LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 
10789   LSI->Mutable = !CallOperator->isConst();
10790
10791   // Add the captures to the LSI so they can be noted as already
10792   // captured within tryCaptureVar. 
10793   auto I = LambdaClass->field_begin();
10794   for (const auto &C : LambdaClass->captures()) {
10795     if (C.capturesVariable()) {
10796       VarDecl *VD = C.getCapturedVar();
10797       if (VD->isInitCapture())
10798         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10799       QualType CaptureType = VD->getType();
10800       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10801       LSI->addCapture(VD, /*IsBlock*/false, ByRef, 
10802           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
10803           /*EllipsisLoc*/C.isPackExpansion() 
10804                          ? C.getEllipsisLoc() : SourceLocation(),
10805           CaptureType, /*Expr*/ nullptr);
10806
10807     } else if (C.capturesThis()) {
10808       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 
10809                               S.getCurrentThisType(), /*Expr*/ nullptr);
10810     } else {
10811       LSI->addVLATypeCapture(C.getLocation(), I->getType());
10812     }
10813     ++I;
10814   }
10815 }
10816
10817 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
10818                                     SkipBodyInfo *SkipBody) {
10819   // Clear the last template instantiation error context.
10820   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10821   
10822   if (!D)
10823     return D;
10824   FunctionDecl *FD = nullptr;
10825
10826   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10827     FD = FunTmpl->getTemplatedDecl();
10828   else
10829     FD = cast<FunctionDecl>(D);
10830
10831   // See if this is a redefinition.
10832   if (!FD->isLateTemplateParsed()) {
10833     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
10834
10835     // If we're skipping the body, we're done. Don't enter the scope.
10836     if (SkipBody && SkipBody->ShouldSkip)
10837       return D;
10838   }
10839
10840   // If we are instantiating a generic lambda call operator, push
10841   // a LambdaScopeInfo onto the function stack.  But use the information
10842   // that's already been calculated (ActOnLambdaExpr) to prime the current 
10843   // LambdaScopeInfo.  
10844   // When the template operator is being specialized, the LambdaScopeInfo,
10845   // has to be properly restored so that tryCaptureVariable doesn't try
10846   // and capture any new variables. In addition when calculating potential
10847   // captures during transformation of nested lambdas, it is necessary to 
10848   // have the LSI properly restored. 
10849   if (isGenericLambdaCallOperatorSpecialization(FD)) {
10850     assert(ActiveTemplateInstantiations.size() &&
10851       "There should be an active template instantiation on the stack " 
10852       "when instantiating a generic lambda!");
10853     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
10854   }
10855   else
10856     // Enter a new function scope
10857     PushFunctionScope();
10858
10859   // Builtin functions cannot be defined.
10860   if (unsigned BuiltinID = FD->getBuiltinID()) {
10861     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10862         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
10863       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
10864       FD->setInvalidDecl();
10865     }
10866   }
10867
10868   // The return type of a function definition must be complete
10869   // (C99 6.9.1p3, C++ [dcl.fct]p6).
10870   QualType ResultType = FD->getReturnType();
10871   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
10872       !FD->isInvalidDecl() &&
10873       RequireCompleteType(FD->getLocation(), ResultType,
10874                           diag::err_func_def_incomplete_result))
10875     FD->setInvalidDecl();
10876
10877   if (FnBodyScope)
10878     PushDeclContext(FnBodyScope, FD);
10879
10880   // Check the validity of our function parameters
10881   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10882                            /*CheckParameterNames=*/true);
10883
10884   // Introduce our parameters into the function scope
10885   for (auto Param : FD->params()) {
10886     Param->setOwningFunction(FD);
10887
10888     // If this has an identifier, add it to the scope stack.
10889     if (Param->getIdentifier() && FnBodyScope) {
10890       CheckShadow(FnBodyScope, Param);
10891
10892       PushOnScopeChains(Param, FnBodyScope);
10893     }
10894   }
10895
10896   // If we had any tags defined in the function prototype,
10897   // introduce them into the function scope.
10898   if (FnBodyScope) {
10899     for (ArrayRef<NamedDecl *>::iterator
10900              I = FD->getDeclsInPrototypeScope().begin(),
10901              E = FD->getDeclsInPrototypeScope().end();
10902          I != E; ++I) {
10903       NamedDecl *D = *I;
10904
10905       // Some of these decls (like enums) may have been pinned to the
10906       // translation unit for lack of a real context earlier. If so, remove
10907       // from the translation unit and reattach to the current context.
10908       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
10909         // Is the decl actually in the context?
10910         for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
10911           if (DI == D) {  
10912             Context.getTranslationUnitDecl()->removeDecl(D);
10913             break;
10914           }
10915         }
10916         // Either way, reassign the lexical decl context to our FunctionDecl.
10917         D->setLexicalDeclContext(CurContext);
10918       }
10919
10920       // If the decl has a non-null name, make accessible in the current scope.
10921       if (!D->getName().empty())
10922         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10923
10924       // Similarly, dive into enums and fish their constants out, making them
10925       // accessible in this scope.
10926       if (auto *ED = dyn_cast<EnumDecl>(D)) {
10927         for (auto *EI : ED->enumerators())
10928           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
10929       }
10930     }
10931   }
10932
10933   // Ensure that the function's exception specification is instantiated.
10934   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10935     ResolveExceptionSpec(D->getLocation(), FPT);
10936
10937   // dllimport cannot be applied to non-inline function definitions.
10938   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10939       !FD->isTemplateInstantiation()) {
10940     assert(!FD->hasAttr<DLLExportAttr>());
10941     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10942     FD->setInvalidDecl();
10943     return D;
10944   }
10945   // We want to attach documentation to original Decl (which might be
10946   // a function template).
10947   ActOnDocumentableDecl(D);
10948   if (getCurLexicalContext()->isObjCContainer() &&
10949       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10950       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10951     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10952     
10953   return D;
10954 }
10955
10956 /// \brief Given the set of return statements within a function body,
10957 /// compute the variables that are subject to the named return value 
10958 /// optimization.
10959 ///
10960 /// Each of the variables that is subject to the named return value 
10961 /// optimization will be marked as NRVO variables in the AST, and any
10962 /// return statement that has a marked NRVO variable as its NRVO candidate can
10963 /// use the named return value optimization.
10964 ///
10965 /// This function applies a very simplistic algorithm for NRVO: if every return
10966 /// statement in the scope of a variable has the same NRVO candidate, that
10967 /// candidate is an NRVO variable.
10968 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
10969   ReturnStmt **Returns = Scope->Returns.data();
10970
10971   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
10972     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
10973       if (!NRVOCandidate->isNRVOVariable())
10974         Returns[I]->setNRVOCandidate(nullptr);
10975     }
10976   }
10977 }
10978
10979 bool Sema::canDelayFunctionBody(const Declarator &D) {
10980   // We can't delay parsing the body of a constexpr function template (yet).
10981   if (D.getDeclSpec().isConstexprSpecified())
10982     return false;
10983
10984   // We can't delay parsing the body of a function template with a deduced
10985   // return type (yet).
10986   if (D.getDeclSpec().containsPlaceholderType()) {
10987     // If the placeholder introduces a non-deduced trailing return type,
10988     // we can still delay parsing it.
10989     if (D.getNumTypeObjects()) {
10990       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
10991       if (Outer.Kind == DeclaratorChunk::Function &&
10992           Outer.Fun.hasTrailingReturnType()) {
10993         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
10994         return Ty.isNull() || !Ty->isUndeducedType();
10995       }
10996     }
10997     return false;
10998   }
10999
11000   return true;
11001 }
11002
11003 bool Sema::canSkipFunctionBody(Decl *D) {
11004   // We cannot skip the body of a function (or function template) which is
11005   // constexpr, since we may need to evaluate its body in order to parse the
11006   // rest of the file.
11007   // We cannot skip the body of a function with an undeduced return type,
11008   // because any callers of that function need to know the type.
11009   if (const FunctionDecl *FD = D->getAsFunction())
11010     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11011       return false;
11012   return Consumer.shouldSkipFunctionBody(D);
11013 }
11014
11015 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11016   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11017     FD->setHasSkippedBody();
11018   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11019     MD->setHasSkippedBody();
11020   return ActOnFinishFunctionBody(Decl, nullptr);
11021 }
11022
11023 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11024   return ActOnFinishFunctionBody(D, BodyArg, false);
11025 }
11026
11027 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11028                                     bool IsInstantiation) {
11029   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11030
11031   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11032   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11033
11034   if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
11035     CheckCompletedCoroutineBody(FD, Body);
11036
11037   if (FD) {
11038     FD->setBody(Body);
11039
11040     if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
11041         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
11042       // If the function has a deduced result type but contains no 'return'
11043       // statements, the result type as written must be exactly 'auto', and
11044       // the deduced result type is 'void'.
11045       if (!FD->getReturnType()->getAs<AutoType>()) {
11046         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11047             << FD->getReturnType();
11048         FD->setInvalidDecl();
11049       } else {
11050         // Substitute 'void' for the 'auto' in the type.
11051         TypeLoc ResultType = getReturnTypeLoc(FD);
11052         Context.adjustDeducedFunctionResultType(
11053             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11054       }
11055     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11056       auto *LSI = getCurLambda();
11057       if (LSI->HasImplicitReturnType) {
11058         deduceClosureReturnType(*LSI);
11059
11060         // C++11 [expr.prim.lambda]p4:
11061         //   [...] if there are no return statements in the compound-statement
11062         //   [the deduced type is] the type void
11063         QualType RetType =
11064             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11065
11066         // Update the return type to the deduced type.
11067         const FunctionProtoType *Proto =
11068             FD->getType()->getAs<FunctionProtoType>();
11069         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11070                                             Proto->getExtProtoInfo()));
11071       }
11072     }
11073
11074     // The only way to be included in UndefinedButUsed is if there is an
11075     // ODR use before the definition. Avoid the expensive map lookup if this
11076     // is the first declaration.
11077     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11078       if (!FD->isExternallyVisible())
11079         UndefinedButUsed.erase(FD);
11080       else if (FD->isInlined() &&
11081                !LangOpts.GNUInline &&
11082                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11083         UndefinedButUsed.erase(FD);
11084     }
11085
11086     // If the function implicitly returns zero (like 'main') or is naked,
11087     // don't complain about missing return statements.
11088     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11089       WP.disableCheckFallThrough();
11090
11091     // MSVC permits the use of pure specifier (=0) on function definition,
11092     // defined at class scope, warn about this non-standard construct.
11093     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11094       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11095
11096     if (!FD->isInvalidDecl()) {
11097       // Don't diagnose unused parameters of defaulted or deleted functions.
11098       if (!FD->isDeleted() && !FD->isDefaulted())
11099         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
11100       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
11101                                              FD->getReturnType(), FD);
11102
11103       // If this is a structor, we need a vtable.
11104       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11105         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11106       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11107         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11108       
11109       // Try to apply the named return value optimization. We have to check
11110       // if we can do this here because lambdas keep return statements around
11111       // to deduce an implicit return type.
11112       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11113           !FD->isDependentContext())
11114         computeNRVO(Body, getCurFunction());
11115     }
11116
11117     // GNU warning -Wmissing-prototypes:
11118     //   Warn if a global function is defined without a previous
11119     //   prototype declaration. This warning is issued even if the
11120     //   definition itself provides a prototype. The aim is to detect
11121     //   global functions that fail to be declared in header files.
11122     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11123     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11124       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11125
11126       if (PossibleZeroParamPrototype) {
11127         // We found a declaration that is not a prototype,
11128         // but that could be a zero-parameter prototype
11129         if (TypeSourceInfo *TI =
11130                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11131           TypeLoc TL = TI->getTypeLoc();
11132           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11133             Diag(PossibleZeroParamPrototype->getLocation(),
11134                  diag::note_declaration_not_a_prototype)
11135                 << PossibleZeroParamPrototype
11136                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11137         }
11138       }
11139     }
11140
11141     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11142       const CXXMethodDecl *KeyFunction;
11143       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11144           MD->isVirtual() &&
11145           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11146           MD == KeyFunction->getCanonicalDecl()) {
11147         // Update the key-function state if necessary for this ABI.
11148         if (FD->isInlined() &&
11149             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11150           Context.setNonKeyFunction(MD);
11151
11152           // If the newly-chosen key function is already defined, then we
11153           // need to mark the vtable as used retroactively.
11154           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11155           const FunctionDecl *Definition;
11156           if (KeyFunction && KeyFunction->isDefined(Definition))
11157             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11158         } else {
11159           // We just defined they key function; mark the vtable as used.
11160           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11161         }
11162       }
11163     }
11164
11165     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11166            "Function parsing confused");
11167   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11168     assert(MD == getCurMethodDecl() && "Method parsing confused");
11169     MD->setBody(Body);
11170     if (!MD->isInvalidDecl()) {
11171       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
11172       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
11173                                              MD->getReturnType(), MD);
11174
11175       if (Body)
11176         computeNRVO(Body, getCurFunction());
11177     }
11178     if (getCurFunction()->ObjCShouldCallSuper) {
11179       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11180         << MD->getSelector().getAsString();
11181       getCurFunction()->ObjCShouldCallSuper = false;
11182     }
11183     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11184       const ObjCMethodDecl *InitMethod = nullptr;
11185       bool isDesignated =
11186           MD->isDesignatedInitializerForTheInterface(&InitMethod);
11187       assert(isDesignated && InitMethod);
11188       (void)isDesignated;
11189
11190       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11191         auto IFace = MD->getClassInterface();
11192         if (!IFace)
11193           return false;
11194         auto SuperD = IFace->getSuperClass();
11195         if (!SuperD)
11196           return false;
11197         return SuperD->getIdentifier() ==
11198             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11199       };
11200       // Don't issue this warning for unavailable inits or direct subclasses
11201       // of NSObject.
11202       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11203         Diag(MD->getLocation(),
11204              diag::warn_objc_designated_init_missing_super_call);
11205         Diag(InitMethod->getLocation(),
11206              diag::note_objc_designated_init_marked_here);
11207       }
11208       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11209     }
11210     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11211       // Don't issue this warning for unavaialable inits.
11212       if (!MD->isUnavailable())
11213         Diag(MD->getLocation(),
11214              diag::warn_objc_secondary_init_missing_init_call);
11215       getCurFunction()->ObjCWarnForNoInitDelegation = false;
11216     }
11217   } else {
11218     return nullptr;
11219   }
11220
11221   assert(!getCurFunction()->ObjCShouldCallSuper &&
11222          "This should only be set for ObjC methods, which should have been "
11223          "handled in the block above.");
11224
11225   // Verify and clean out per-function state.
11226   if (Body && (!FD || !FD->isDefaulted())) {
11227     // C++ constructors that have function-try-blocks can't have return
11228     // statements in the handlers of that block. (C++ [except.handle]p14)
11229     // Verify this.
11230     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11231       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11232     
11233     // Verify that gotos and switch cases don't jump into scopes illegally.
11234     if (getCurFunction()->NeedsScopeChecking() &&
11235         !PP.isCodeCompletionEnabled())
11236       DiagnoseInvalidJumps(Body);
11237
11238     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11239       if (!Destructor->getParent()->isDependentType())
11240         CheckDestructor(Destructor);
11241
11242       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11243                                              Destructor->getParent());
11244     }
11245     
11246     // If any errors have occurred, clear out any temporaries that may have
11247     // been leftover. This ensures that these temporaries won't be picked up for
11248     // deletion in some later function.
11249     if (getDiagnostics().hasErrorOccurred() ||
11250         getDiagnostics().getSuppressAllDiagnostics()) {
11251       DiscardCleanupsInEvaluationContext();
11252     }
11253     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11254         !isa<FunctionTemplateDecl>(dcl)) {
11255       // Since the body is valid, issue any analysis-based warnings that are
11256       // enabled.
11257       ActivePolicy = &WP;
11258     }
11259
11260     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11261         (!CheckConstexprFunctionDecl(FD) ||
11262          !CheckConstexprFunctionBody(FD, Body)))
11263       FD->setInvalidDecl();
11264
11265     if (FD && FD->hasAttr<NakedAttr>()) {
11266       for (const Stmt *S : Body->children()) {
11267         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11268           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11269           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11270           FD->setInvalidDecl();
11271           break;
11272         }
11273       }
11274     }
11275
11276     assert(ExprCleanupObjects.size() ==
11277                ExprEvalContexts.back().NumCleanupObjects &&
11278            "Leftover temporaries in function");
11279     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
11280     assert(MaybeODRUseExprs.empty() &&
11281            "Leftover expressions for odr-use checking");
11282   }
11283   
11284   if (!IsInstantiation)
11285     PopDeclContext();
11286
11287   PopFunctionScopeInfo(ActivePolicy, dcl);
11288   // If any errors have occurred, clear out any temporaries that may have
11289   // been leftover. This ensures that these temporaries won't be picked up for
11290   // deletion in some later function.
11291   if (getDiagnostics().hasErrorOccurred()) {
11292     DiscardCleanupsInEvaluationContext();
11293   }
11294
11295   return dcl;
11296 }
11297
11298
11299 /// When we finish delayed parsing of an attribute, we must attach it to the
11300 /// relevant Decl.
11301 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11302                                        ParsedAttributes &Attrs) {
11303   // Always attach attributes to the underlying decl.
11304   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11305     D = TD->getTemplatedDecl();
11306   ProcessDeclAttributeList(S, D, Attrs.getList());  
11307   
11308   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11309     if (Method->isStatic())
11310       checkThisInStaticMemberFunctionAttributes(Method);
11311 }
11312
11313
11314 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11315 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11316 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11317                                           IdentifierInfo &II, Scope *S) {
11318   // Before we produce a declaration for an implicitly defined
11319   // function, see whether there was a locally-scoped declaration of
11320   // this name as a function or variable. If so, use that
11321   // (non-visible) declaration, and complain about it.
11322   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11323     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11324     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11325     return ExternCPrev;
11326   }
11327
11328   // Extension in C99.  Legal in C90, but warn about it.
11329   unsigned diag_id;
11330   if (II.getName().startswith("__builtin_"))
11331     diag_id = diag::warn_builtin_unknown;
11332   else if (getLangOpts().C99)
11333     diag_id = diag::ext_implicit_function_decl;
11334   else
11335     diag_id = diag::warn_implicit_function_decl;
11336   Diag(Loc, diag_id) << &II;
11337
11338   // Because typo correction is expensive, only do it if the implicit
11339   // function declaration is going to be treated as an error.
11340   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11341     TypoCorrection Corrected;
11342     if (S &&
11343         (Corrected = CorrectTypo(
11344              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11345              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11346       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11347                    /*ErrorRecovery*/false);
11348   }
11349
11350   // Set a Declarator for the implicit definition: int foo();
11351   const char *Dummy;
11352   AttributeFactory attrFactory;
11353   DeclSpec DS(attrFactory);
11354   unsigned DiagID;
11355   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11356                                   Context.getPrintingPolicy());
11357   (void)Error; // Silence warning.
11358   assert(!Error && "Error setting up implicit decl!");
11359   SourceLocation NoLoc;
11360   Declarator D(DS, Declarator::BlockContext);
11361   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11362                                              /*IsAmbiguous=*/false,
11363                                              /*LParenLoc=*/NoLoc,
11364                                              /*Params=*/nullptr,
11365                                              /*NumParams=*/0,
11366                                              /*EllipsisLoc=*/NoLoc,
11367                                              /*RParenLoc=*/NoLoc,
11368                                              /*TypeQuals=*/0,
11369                                              /*RefQualifierIsLvalueRef=*/true,
11370                                              /*RefQualifierLoc=*/NoLoc,
11371                                              /*ConstQualifierLoc=*/NoLoc,
11372                                              /*VolatileQualifierLoc=*/NoLoc,
11373                                              /*RestrictQualifierLoc=*/NoLoc,
11374                                              /*MutableLoc=*/NoLoc,
11375                                              EST_None,
11376                                              /*ESpecRange=*/SourceRange(),
11377                                              /*Exceptions=*/nullptr,
11378                                              /*ExceptionRanges=*/nullptr,
11379                                              /*NumExceptions=*/0,
11380                                              /*NoexceptExpr=*/nullptr,
11381                                              /*ExceptionSpecTokens=*/nullptr,
11382                                              Loc, Loc, D),
11383                 DS.getAttributes(),
11384                 SourceLocation());
11385   D.SetIdentifier(&II, Loc);
11386
11387   // Insert this function into translation-unit scope.
11388
11389   DeclContext *PrevDC = CurContext;
11390   CurContext = Context.getTranslationUnitDecl();
11391
11392   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11393   FD->setImplicit();
11394
11395   CurContext = PrevDC;
11396
11397   AddKnownFunctionAttributes(FD);
11398
11399   return FD;
11400 }
11401
11402 /// \brief Adds any function attributes that we know a priori based on
11403 /// the declaration of this function.
11404 ///
11405 /// These attributes can apply both to implicitly-declared builtins
11406 /// (like __builtin___printf_chk) or to library-declared functions
11407 /// like NSLog or printf.
11408 ///
11409 /// We need to check for duplicate attributes both here and where user-written
11410 /// attributes are applied to declarations.
11411 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11412   if (FD->isInvalidDecl())
11413     return;
11414
11415   // If this is a built-in function, map its builtin attributes to
11416   // actual attributes.
11417   if (unsigned BuiltinID = FD->getBuiltinID()) {
11418     // Handle printf-formatting attributes.
11419     unsigned FormatIdx;
11420     bool HasVAListArg;
11421     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11422       if (!FD->hasAttr<FormatAttr>()) {
11423         const char *fmt = "printf";
11424         unsigned int NumParams = FD->getNumParams();
11425         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11426             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11427           fmt = "NSString";
11428         FD->addAttr(FormatAttr::CreateImplicit(Context,
11429                                                &Context.Idents.get(fmt),
11430                                                FormatIdx+1,
11431                                                HasVAListArg ? 0 : FormatIdx+2,
11432                                                FD->getLocation()));
11433       }
11434     }
11435     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11436                                              HasVAListArg)) {
11437      if (!FD->hasAttr<FormatAttr>())
11438        FD->addAttr(FormatAttr::CreateImplicit(Context,
11439                                               &Context.Idents.get("scanf"),
11440                                               FormatIdx+1,
11441                                               HasVAListArg ? 0 : FormatIdx+2,
11442                                               FD->getLocation()));
11443     }
11444
11445     // Mark const if we don't care about errno and that is the only
11446     // thing preventing the function from being const. This allows
11447     // IRgen to use LLVM intrinsics for such functions.
11448     if (!getLangOpts().MathErrno &&
11449         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11450       if (!FD->hasAttr<ConstAttr>())
11451         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11452     }
11453
11454     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11455         !FD->hasAttr<ReturnsTwiceAttr>())
11456       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11457                                          FD->getLocation()));
11458     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11459       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11460     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11461       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11462     if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads &&
11463         Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11464         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11465       // Assign appropriate attribute depending on CUDA compilation
11466       // mode and the target builtin belongs to. E.g. during host
11467       // compilation, aux builtins are __device__, the rest are __host__.
11468       if (getLangOpts().CUDAIsDevice !=
11469           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11470         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11471       else
11472         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11473     }
11474   }
11475
11476   IdentifierInfo *Name = FD->getIdentifier();
11477   if (!Name)
11478     return;
11479   if ((!getLangOpts().CPlusPlus &&
11480        FD->getDeclContext()->isTranslationUnit()) ||
11481       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11482        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11483        LinkageSpecDecl::lang_c)) {
11484     // Okay: this could be a libc/libm/Objective-C function we know
11485     // about.
11486   } else
11487     return;
11488
11489   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11490     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11491     // target-specific builtins, perhaps?
11492     if (!FD->hasAttr<FormatAttr>())
11493       FD->addAttr(FormatAttr::CreateImplicit(Context,
11494                                              &Context.Idents.get("printf"), 2,
11495                                              Name->isStr("vasprintf") ? 0 : 3,
11496                                              FD->getLocation()));
11497   }
11498
11499   if (Name->isStr("__CFStringMakeConstantString")) {
11500     // We already have a __builtin___CFStringMakeConstantString,
11501     // but builds that use -fno-constant-cfstrings don't go through that.
11502     if (!FD->hasAttr<FormatArgAttr>())
11503       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11504                                                 FD->getLocation()));
11505   }
11506 }
11507
11508 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11509                                     TypeSourceInfo *TInfo) {
11510   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11511   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11512
11513   if (!TInfo) {
11514     assert(D.isInvalidType() && "no declarator info for valid type");
11515     TInfo = Context.getTrivialTypeSourceInfo(T);
11516   }
11517
11518   // Scope manipulation handled by caller.
11519   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11520                                            D.getLocStart(),
11521                                            D.getIdentifierLoc(),
11522                                            D.getIdentifier(),
11523                                            TInfo);
11524
11525   // Bail out immediately if we have an invalid declaration.
11526   if (D.isInvalidType()) {
11527     NewTD->setInvalidDecl();
11528     return NewTD;
11529   }
11530   
11531   if (D.getDeclSpec().isModulePrivateSpecified()) {
11532     if (CurContext->isFunctionOrMethod())
11533       Diag(NewTD->getLocation(), diag::err_module_private_local)
11534         << 2 << NewTD->getDeclName()
11535         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11536         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11537     else
11538       NewTD->setModulePrivate();
11539   }
11540   
11541   // C++ [dcl.typedef]p8:
11542   //   If the typedef declaration defines an unnamed class (or
11543   //   enum), the first typedef-name declared by the declaration
11544   //   to be that class type (or enum type) is used to denote the
11545   //   class type (or enum type) for linkage purposes only.
11546   // We need to check whether the type was declared in the declaration.
11547   switch (D.getDeclSpec().getTypeSpecType()) {
11548   case TST_enum:
11549   case TST_struct:
11550   case TST_interface:
11551   case TST_union:
11552   case TST_class: {
11553     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11554     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11555     break;
11556   }
11557
11558   default:
11559     break;
11560   }
11561
11562   return NewTD;
11563 }
11564
11565
11566 /// \brief Check that this is a valid underlying type for an enum declaration.
11567 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11568   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11569   QualType T = TI->getType();
11570
11571   if (T->isDependentType())
11572     return false;
11573
11574   if (const BuiltinType *BT = T->getAs<BuiltinType>())
11575     if (BT->isInteger())
11576       return false;
11577
11578   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11579   return true;
11580 }
11581
11582 /// Check whether this is a valid redeclaration of a previous enumeration.
11583 /// \return true if the redeclaration was invalid.
11584 bool Sema::CheckEnumRedeclaration(
11585     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
11586     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
11587   bool IsFixed = !EnumUnderlyingTy.isNull();
11588
11589   if (IsScoped != Prev->isScoped()) {
11590     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11591       << Prev->isScoped();
11592     Diag(Prev->getLocation(), diag::note_previous_declaration);
11593     return true;
11594   }
11595
11596   if (IsFixed && Prev->isFixed()) {
11597     if (!EnumUnderlyingTy->isDependentType() &&
11598         !Prev->getIntegerType()->isDependentType() &&
11599         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11600                                         Prev->getIntegerType())) {
11601       // TODO: Highlight the underlying type of the redeclaration.
11602       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11603         << EnumUnderlyingTy << Prev->getIntegerType();
11604       Diag(Prev->getLocation(), diag::note_previous_declaration)
11605           << Prev->getIntegerTypeRange();
11606       return true;
11607     }
11608   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
11609     ;
11610   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
11611     ;
11612   } else if (IsFixed != Prev->isFixed()) {
11613     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11614       << Prev->isFixed();
11615     Diag(Prev->getLocation(), diag::note_previous_declaration);
11616     return true;
11617   }
11618
11619   return false;
11620 }
11621
11622 /// \brief Get diagnostic %select index for tag kind for
11623 /// redeclaration diagnostic message.
11624 /// WARNING: Indexes apply to particular diagnostics only!
11625 ///
11626 /// \returns diagnostic %select index.
11627 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
11628   switch (Tag) {
11629   case TTK_Struct: return 0;
11630   case TTK_Interface: return 1;
11631   case TTK_Class:  return 2;
11632   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11633   }
11634 }
11635
11636 /// \brief Determine if tag kind is a class-key compatible with
11637 /// class for redeclaration (class, struct, or __interface).
11638 ///
11639 /// \returns true iff the tag kind is compatible.
11640 static bool isClassCompatTagKind(TagTypeKind Tag)
11641 {
11642   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11643 }
11644
11645 /// \brief Determine whether a tag with a given kind is acceptable
11646 /// as a redeclaration of the given tag declaration.
11647 ///
11648 /// \returns true if the new tag kind is acceptable, false otherwise.
11649 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11650                                         TagTypeKind NewTag, bool isDefinition,
11651                                         SourceLocation NewTagLoc,
11652                                         const IdentifierInfo *Name) {
11653   // C++ [dcl.type.elab]p3:
11654   //   The class-key or enum keyword present in the
11655   //   elaborated-type-specifier shall agree in kind with the
11656   //   declaration to which the name in the elaborated-type-specifier
11657   //   refers. This rule also applies to the form of
11658   //   elaborated-type-specifier that declares a class-name or
11659   //   friend class since it can be construed as referring to the
11660   //   definition of the class. Thus, in any
11661   //   elaborated-type-specifier, the enum keyword shall be used to
11662   //   refer to an enumeration (7.2), the union class-key shall be
11663   //   used to refer to a union (clause 9), and either the class or
11664   //   struct class-key shall be used to refer to a class (clause 9)
11665   //   declared using the class or struct class-key.
11666   TagTypeKind OldTag = Previous->getTagKind();
11667   if (!isDefinition || !isClassCompatTagKind(NewTag))
11668     if (OldTag == NewTag)
11669       return true;
11670
11671   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11672     // Warn about the struct/class tag mismatch.
11673     bool isTemplate = false;
11674     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11675       isTemplate = Record->getDescribedClassTemplate();
11676
11677     if (!ActiveTemplateInstantiations.empty()) {
11678       // In a template instantiation, do not offer fix-its for tag mismatches
11679       // since they usually mess up the template instead of fixing the problem.
11680       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11681         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11682         << getRedeclDiagFromTagKind(OldTag);
11683       return true;
11684     }
11685
11686     if (isDefinition) {
11687       // On definitions, check previous tags and issue a fix-it for each
11688       // one that doesn't match the current tag.
11689       if (Previous->getDefinition()) {
11690         // Don't suggest fix-its for redefinitions.
11691         return true;
11692       }
11693
11694       bool previousMismatch = false;
11695       for (auto I : Previous->redecls()) {
11696         if (I->getTagKind() != NewTag) {
11697           if (!previousMismatch) {
11698             previousMismatch = true;
11699             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11700               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11701               << getRedeclDiagFromTagKind(I->getTagKind());
11702           }
11703           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11704             << getRedeclDiagFromTagKind(NewTag)
11705             << FixItHint::CreateReplacement(I->getInnerLocStart(),
11706                  TypeWithKeyword::getTagTypeKindName(NewTag));
11707         }
11708       }
11709       return true;
11710     }
11711
11712     // Check for a previous definition.  If current tag and definition
11713     // are same type, do nothing.  If no definition, but disagree with
11714     // with previous tag type, give a warning, but no fix-it.
11715     const TagDecl *Redecl = Previous->getDefinition() ?
11716                             Previous->getDefinition() : Previous;
11717     if (Redecl->getTagKind() == NewTag) {
11718       return true;
11719     }
11720
11721     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11722       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11723       << getRedeclDiagFromTagKind(OldTag);
11724     Diag(Redecl->getLocation(), diag::note_previous_use);
11725
11726     // If there is a previous definition, suggest a fix-it.
11727     if (Previous->getDefinition()) {
11728         Diag(NewTagLoc, diag::note_struct_class_suggestion)
11729           << getRedeclDiagFromTagKind(Redecl->getTagKind())
11730           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11731                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11732     }
11733
11734     return true;
11735   }
11736   return false;
11737 }
11738
11739 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11740 /// from an outer enclosing namespace or file scope inside a friend declaration.
11741 /// This should provide the commented out code in the following snippet:
11742 ///   namespace N {
11743 ///     struct X;
11744 ///     namespace M {
11745 ///       struct Y { friend struct /*N::*/ X; };
11746 ///     }
11747 ///   }
11748 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11749                                          SourceLocation NameLoc) {
11750   // While the decl is in a namespace, do repeated lookup of that name and see
11751   // if we get the same namespace back.  If we do not, continue until
11752   // translation unit scope, at which point we have a fully qualified NNS.
11753   SmallVector<IdentifierInfo *, 4> Namespaces;
11754   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11755   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11756     // This tag should be declared in a namespace, which can only be enclosed by
11757     // other namespaces.  Bail if there's an anonymous namespace in the chain.
11758     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11759     if (!Namespace || Namespace->isAnonymousNamespace())
11760       return FixItHint();
11761     IdentifierInfo *II = Namespace->getIdentifier();
11762     Namespaces.push_back(II);
11763     NamedDecl *Lookup = SemaRef.LookupSingleName(
11764         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11765     if (Lookup == Namespace)
11766       break;
11767   }
11768
11769   // Once we have all the namespaces, reverse them to go outermost first, and
11770   // build an NNS.
11771   SmallString<64> Insertion;
11772   llvm::raw_svector_ostream OS(Insertion);
11773   if (DC->isTranslationUnit())
11774     OS << "::";
11775   std::reverse(Namespaces.begin(), Namespaces.end());
11776   for (auto *II : Namespaces)
11777     OS << II->getName() << "::";
11778   return FixItHint::CreateInsertion(NameLoc, Insertion);
11779 }
11780
11781 /// \brief Determine whether a tag originally declared in context \p OldDC can
11782 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
11783 /// found a declaration in \p OldDC as a previous decl, perhaps through a
11784 /// using-declaration).
11785 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
11786                                          DeclContext *NewDC) {
11787   OldDC = OldDC->getRedeclContext();
11788   NewDC = NewDC->getRedeclContext();
11789
11790   if (OldDC->Equals(NewDC))
11791     return true;
11792
11793   // In MSVC mode, we allow a redeclaration if the contexts are related (either
11794   // encloses the other).
11795   if (S.getLangOpts().MSVCCompat &&
11796       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
11797     return true;
11798
11799   return false;
11800 }
11801
11802 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
11803 /// former case, Name will be non-null.  In the later case, Name will be null.
11804 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
11805 /// reference/declaration/definition of a tag.
11806 ///
11807 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
11808 /// trailing-type-specifier) other than one in an alias-declaration.
11809 ///
11810 /// \param SkipBody If non-null, will be set to indicate if the caller should
11811 /// skip the definition of this tag and treat it as if it were a declaration.
11812 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11813                      SourceLocation KWLoc, CXXScopeSpec &SS,
11814                      IdentifierInfo *Name, SourceLocation NameLoc,
11815                      AttributeList *Attr, AccessSpecifier AS,
11816                      SourceLocation ModulePrivateLoc,
11817                      MultiTemplateParamsArg TemplateParameterLists,
11818                      bool &OwnedDecl, bool &IsDependent,
11819                      SourceLocation ScopedEnumKWLoc,
11820                      bool ScopedEnumUsesClassTag,
11821                      TypeResult UnderlyingType,
11822                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
11823   // If this is not a definition, it must have a name.
11824   IdentifierInfo *OrigName = Name;
11825   assert((Name != nullptr || TUK == TUK_Definition) &&
11826          "Nameless record must be a definition!");
11827   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
11828
11829   OwnedDecl = false;
11830   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11831   bool ScopedEnum = ScopedEnumKWLoc.isValid();
11832
11833   // FIXME: Check explicit specializations more carefully.
11834   bool isExplicitSpecialization = false;
11835   bool Invalid = false;
11836
11837   // We only need to do this matching if we have template parameters
11838   // or a scope specifier, which also conveniently avoids this work
11839   // for non-C++ cases.
11840   if (TemplateParameterLists.size() > 0 ||
11841       (SS.isNotEmpty() && TUK != TUK_Reference)) {
11842     if (TemplateParameterList *TemplateParams =
11843             MatchTemplateParametersToScopeSpecifier(
11844                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
11845                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
11846       if (Kind == TTK_Enum) {
11847         Diag(KWLoc, diag::err_enum_template);
11848         return nullptr;
11849       }
11850
11851       if (TemplateParams->size() > 0) {
11852         // This is a declaration or definition of a class template (which may
11853         // be a member of another template).
11854
11855         if (Invalid)
11856           return nullptr;
11857
11858         OwnedDecl = false;
11859         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
11860                                                SS, Name, NameLoc, Attr,
11861                                                TemplateParams, AS,
11862                                                ModulePrivateLoc,
11863                                                /*FriendLoc*/SourceLocation(),
11864                                                TemplateParameterLists.size()-1,
11865                                                TemplateParameterLists.data(),
11866                                                SkipBody);
11867         return Result.get();
11868       } else {
11869         // The "template<>" header is extraneous.
11870         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11871           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11872         isExplicitSpecialization = true;
11873       }
11874     }
11875   }
11876
11877   // Figure out the underlying type if this a enum declaration. We need to do
11878   // this early, because it's needed to detect if this is an incompatible
11879   // redeclaration.
11880   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11881   bool EnumUnderlyingIsImplicit = false;
11882
11883   if (Kind == TTK_Enum) {
11884     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11885       // No underlying type explicitly specified, or we failed to parse the
11886       // type, default to int.
11887       EnumUnderlying = Context.IntTy.getTypePtr();
11888     else if (UnderlyingType.get()) {
11889       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11890       // integral type; any cv-qualification is ignored.
11891       TypeSourceInfo *TI = nullptr;
11892       GetTypeFromParser(UnderlyingType.get(), &TI);
11893       EnumUnderlying = TI;
11894
11895       if (CheckEnumUnderlyingType(TI))
11896         // Recover by falling back to int.
11897         EnumUnderlying = Context.IntTy.getTypePtr();
11898
11899       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
11900                                           UPPC_FixedUnderlyingType))
11901         EnumUnderlying = Context.IntTy.getTypePtr();
11902
11903     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
11904       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
11905         // Microsoft enums are always of int type.
11906         EnumUnderlying = Context.IntTy.getTypePtr();
11907         EnumUnderlyingIsImplicit = true;
11908       }
11909     }
11910   }
11911
11912   DeclContext *SearchDC = CurContext;
11913   DeclContext *DC = CurContext;
11914   bool isStdBadAlloc = false;
11915
11916   RedeclarationKind Redecl = ForRedeclaration;
11917   if (TUK == TUK_Friend || TUK == TUK_Reference)
11918     Redecl = NotForRedeclaration;
11919
11920   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
11921   if (Name && SS.isNotEmpty()) {
11922     // We have a nested-name tag ('struct foo::bar').
11923
11924     // Check for invalid 'foo::'.
11925     if (SS.isInvalid()) {
11926       Name = nullptr;
11927       goto CreateNewDecl;
11928     }
11929
11930     // If this is a friend or a reference to a class in a dependent
11931     // context, don't try to make a decl for it.
11932     if (TUK == TUK_Friend || TUK == TUK_Reference) {
11933       DC = computeDeclContext(SS, false);
11934       if (!DC) {
11935         IsDependent = true;
11936         return nullptr;
11937       }
11938     } else {
11939       DC = computeDeclContext(SS, true);
11940       if (!DC) {
11941         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11942           << SS.getRange();
11943         return nullptr;
11944       }
11945     }
11946
11947     if (RequireCompleteDeclContext(SS, DC))
11948       return nullptr;
11949
11950     SearchDC = DC;
11951     // Look-up name inside 'foo::'.
11952     LookupQualifiedName(Previous, DC);
11953
11954     if (Previous.isAmbiguous())
11955       return nullptr;
11956
11957     if (Previous.empty()) {
11958       // Name lookup did not find anything. However, if the
11959       // nested-name-specifier refers to the current instantiation,
11960       // and that current instantiation has any dependent base
11961       // classes, we might find something at instantiation time: treat
11962       // this as a dependent elaborated-type-specifier.
11963       // But this only makes any sense for reference-like lookups.
11964       if (Previous.wasNotFoundInCurrentInstantiation() &&
11965           (TUK == TUK_Reference || TUK == TUK_Friend)) {
11966         IsDependent = true;
11967         return nullptr;
11968       }
11969
11970       // A tag 'foo::bar' must already exist.
11971       Diag(NameLoc, diag::err_not_tag_in_scope) 
11972         << Kind << Name << DC << SS.getRange();
11973       Name = nullptr;
11974       Invalid = true;
11975       goto CreateNewDecl;
11976     }
11977   } else if (Name) {
11978     // C++14 [class.mem]p14:
11979     //   If T is the name of a class, then each of the following shall have a
11980     //   name different from T:
11981     //    -- every member of class T that is itself a type
11982     if (TUK != TUK_Reference && TUK != TUK_Friend &&
11983         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
11984       return nullptr;
11985
11986     // If this is a named struct, check to see if there was a previous forward
11987     // declaration or definition.
11988     // FIXME: We're looking into outer scopes here, even when we
11989     // shouldn't be. Doing so can result in ambiguities that we
11990     // shouldn't be diagnosing.
11991     LookupName(Previous, S);
11992
11993     // When declaring or defining a tag, ignore ambiguities introduced
11994     // by types using'ed into this scope.
11995     if (Previous.isAmbiguous() && 
11996         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
11997       LookupResult::Filter F = Previous.makeFilter();
11998       while (F.hasNext()) {
11999         NamedDecl *ND = F.next();
12000         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
12001           F.erase();
12002       }
12003       F.done();
12004     }
12005
12006     // C++11 [namespace.memdef]p3:
12007     //   If the name in a friend declaration is neither qualified nor
12008     //   a template-id and the declaration is a function or an
12009     //   elaborated-type-specifier, the lookup to determine whether
12010     //   the entity has been previously declared shall not consider
12011     //   any scopes outside the innermost enclosing namespace.
12012     //
12013     // MSVC doesn't implement the above rule for types, so a friend tag
12014     // declaration may be a redeclaration of a type declared in an enclosing
12015     // scope.  They do implement this rule for friend functions.
12016     //
12017     // Does it matter that this should be by scope instead of by
12018     // semantic context?
12019     if (!Previous.empty() && TUK == TUK_Friend) {
12020       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12021       LookupResult::Filter F = Previous.makeFilter();
12022       bool FriendSawTagOutsideEnclosingNamespace = false;
12023       while (F.hasNext()) {
12024         NamedDecl *ND = F.next();
12025         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12026         if (DC->isFileContext() &&
12027             !EnclosingNS->Encloses(ND->getDeclContext())) {
12028           if (getLangOpts().MSVCCompat)
12029             FriendSawTagOutsideEnclosingNamespace = true;
12030           else
12031             F.erase();
12032         }
12033       }
12034       F.done();
12035
12036       // Diagnose this MSVC extension in the easy case where lookup would have
12037       // unambiguously found something outside the enclosing namespace.
12038       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12039         NamedDecl *ND = Previous.getFoundDecl();
12040         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12041             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12042       }
12043     }
12044
12045     // Note:  there used to be some attempt at recovery here.
12046     if (Previous.isAmbiguous())
12047       return nullptr;
12048
12049     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12050       // FIXME: This makes sure that we ignore the contexts associated
12051       // with C structs, unions, and enums when looking for a matching
12052       // tag declaration or definition. See the similar lookup tweak
12053       // in Sema::LookupName; is there a better way to deal with this?
12054       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12055         SearchDC = SearchDC->getParent();
12056     }
12057   }
12058
12059   if (Previous.isSingleResult() &&
12060       Previous.getFoundDecl()->isTemplateParameter()) {
12061     // Maybe we will complain about the shadowed template parameter.
12062     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12063     // Just pretend that we didn't see the previous declaration.
12064     Previous.clear();
12065   }
12066
12067   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12068       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12069     // This is a declaration of or a reference to "std::bad_alloc".
12070     isStdBadAlloc = true;
12071     
12072     if (Previous.empty() && StdBadAlloc) {
12073       // std::bad_alloc has been implicitly declared (but made invisible to
12074       // name lookup). Fill in this implicit declaration as the previous 
12075       // declaration, so that the declarations get chained appropriately.
12076       Previous.addDecl(getStdBadAlloc());
12077     }
12078   }
12079
12080   // If we didn't find a previous declaration, and this is a reference
12081   // (or friend reference), move to the correct scope.  In C++, we
12082   // also need to do a redeclaration lookup there, just in case
12083   // there's a shadow friend decl.
12084   if (Name && Previous.empty() &&
12085       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12086     if (Invalid) goto CreateNewDecl;
12087     assert(SS.isEmpty());
12088
12089     if (TUK == TUK_Reference) {
12090       // C++ [basic.scope.pdecl]p5:
12091       //   -- for an elaborated-type-specifier of the form
12092       //
12093       //          class-key identifier
12094       //
12095       //      if the elaborated-type-specifier is used in the
12096       //      decl-specifier-seq or parameter-declaration-clause of a
12097       //      function defined in namespace scope, the identifier is
12098       //      declared as a class-name in the namespace that contains
12099       //      the declaration; otherwise, except as a friend
12100       //      declaration, the identifier is declared in the smallest
12101       //      non-class, non-function-prototype scope that contains the
12102       //      declaration.
12103       //
12104       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12105       // C structs and unions.
12106       //
12107       // It is an error in C++ to declare (rather than define) an enum
12108       // type, including via an elaborated type specifier.  We'll
12109       // diagnose that later; for now, declare the enum in the same
12110       // scope as we would have picked for any other tag type.
12111       //
12112       // GNU C also supports this behavior as part of its incomplete
12113       // enum types extension, while GNU C++ does not.
12114       //
12115       // Find the context where we'll be declaring the tag.
12116       // FIXME: We would like to maintain the current DeclContext as the
12117       // lexical context,
12118       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
12119         SearchDC = SearchDC->getParent();
12120
12121       // Find the scope where we'll be declaring the tag.
12122       while (S->isClassScope() ||
12123              (getLangOpts().CPlusPlus &&
12124               S->isFunctionPrototypeScope()) ||
12125              ((S->getFlags() & Scope::DeclScope) == 0) ||
12126              (S->getEntity() && S->getEntity()->isTransparentContext()))
12127         S = S->getParent();
12128     } else {
12129       assert(TUK == TUK_Friend);
12130       // C++ [namespace.memdef]p3:
12131       //   If a friend declaration in a non-local class first declares a
12132       //   class or function, the friend class or function is a member of
12133       //   the innermost enclosing namespace.
12134       SearchDC = SearchDC->getEnclosingNamespaceContext();
12135     }
12136
12137     // In C++, we need to do a redeclaration lookup to properly
12138     // diagnose some problems.
12139     if (getLangOpts().CPlusPlus) {
12140       Previous.setRedeclarationKind(ForRedeclaration);
12141       LookupQualifiedName(Previous, SearchDC);
12142     }
12143   }
12144
12145   // If we have a known previous declaration to use, then use it.
12146   if (Previous.empty() && SkipBody && SkipBody->Previous)
12147     Previous.addDecl(SkipBody->Previous);
12148
12149   if (!Previous.empty()) {
12150     NamedDecl *PrevDecl = Previous.getFoundDecl();
12151     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12152
12153     // It's okay to have a tag decl in the same scope as a typedef
12154     // which hides a tag decl in the same scope.  Finding this
12155     // insanity with a redeclaration lookup can only actually happen
12156     // in C++.
12157     //
12158     // This is also okay for elaborated-type-specifiers, which is
12159     // technically forbidden by the current standard but which is
12160     // okay according to the likely resolution of an open issue;
12161     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12162     if (getLangOpts().CPlusPlus) {
12163       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12164         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12165           TagDecl *Tag = TT->getDecl();
12166           if (Tag->getDeclName() == Name &&
12167               Tag->getDeclContext()->getRedeclContext()
12168                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
12169             PrevDecl = Tag;
12170             Previous.clear();
12171             Previous.addDecl(Tag);
12172             Previous.resolveKind();
12173           }
12174         }
12175       }
12176     }
12177
12178     // If this is a redeclaration of a using shadow declaration, it must
12179     // declare a tag in the same context. In MSVC mode, we allow a
12180     // redefinition if either context is within the other.
12181     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12182       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12183       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12184           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12185           !(OldTag && isAcceptableTagRedeclContext(
12186                           *this, OldTag->getDeclContext(), SearchDC))) {
12187         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12188         Diag(Shadow->getTargetDecl()->getLocation(),
12189              diag::note_using_decl_target);
12190         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12191             << 0;
12192         // Recover by ignoring the old declaration.
12193         Previous.clear();
12194         goto CreateNewDecl;
12195       }
12196     }
12197
12198     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12199       // If this is a use of a previous tag, or if the tag is already declared
12200       // in the same scope (so that the definition/declaration completes or
12201       // rementions the tag), reuse the decl.
12202       if (TUK == TUK_Reference || TUK == TUK_Friend ||
12203           isDeclInScope(DirectPrevDecl, SearchDC, S,
12204                         SS.isNotEmpty() || isExplicitSpecialization)) {
12205         // Make sure that this wasn't declared as an enum and now used as a
12206         // struct or something similar.
12207         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12208                                           TUK == TUK_Definition, KWLoc,
12209                                           Name)) {
12210           bool SafeToContinue
12211             = (PrevTagDecl->getTagKind() != TTK_Enum &&
12212                Kind != TTK_Enum);
12213           if (SafeToContinue)
12214             Diag(KWLoc, diag::err_use_with_wrong_tag)
12215               << Name
12216               << FixItHint::CreateReplacement(SourceRange(KWLoc),
12217                                               PrevTagDecl->getKindName());
12218           else
12219             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12220           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12221
12222           if (SafeToContinue)
12223             Kind = PrevTagDecl->getTagKind();
12224           else {
12225             // Recover by making this an anonymous redefinition.
12226             Name = nullptr;
12227             Previous.clear();
12228             Invalid = true;
12229           }
12230         }
12231
12232         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12233           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12234
12235           // If this is an elaborated-type-specifier for a scoped enumeration,
12236           // the 'class' keyword is not necessary and not permitted.
12237           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12238             if (ScopedEnum)
12239               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12240                 << PrevEnum->isScoped()
12241                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12242             return PrevTagDecl;
12243           }
12244
12245           QualType EnumUnderlyingTy;
12246           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12247             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12248           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12249             EnumUnderlyingTy = QualType(T, 0);
12250
12251           // All conflicts with previous declarations are recovered by
12252           // returning the previous declaration, unless this is a definition,
12253           // in which case we want the caller to bail out.
12254           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12255                                      ScopedEnum, EnumUnderlyingTy,
12256                                      EnumUnderlyingIsImplicit, PrevEnum))
12257             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12258         }
12259
12260         // C++11 [class.mem]p1:
12261         //   A member shall not be declared twice in the member-specification,
12262         //   except that a nested class or member class template can be declared
12263         //   and then later defined.
12264         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12265             S->isDeclScope(PrevDecl)) {
12266           Diag(NameLoc, diag::ext_member_redeclared);
12267           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12268         }
12269
12270         if (!Invalid) {
12271           // If this is a use, just return the declaration we found, unless
12272           // we have attributes.
12273
12274           // FIXME: In the future, return a variant or some other clue
12275           // for the consumer of this Decl to know it doesn't own it.
12276           // For our current ASTs this shouldn't be a problem, but will
12277           // need to be changed with DeclGroups.
12278           if (!Attr &&
12279               ((TUK == TUK_Reference &&
12280                 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
12281                || TUK == TUK_Friend))
12282             return PrevTagDecl;
12283
12284           // Diagnose attempts to redefine a tag.
12285           if (TUK == TUK_Definition) {
12286             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12287               // If we're defining a specialization and the previous definition
12288               // is from an implicit instantiation, don't emit an error
12289               // here; we'll catch this in the general case below.
12290               bool IsExplicitSpecializationAfterInstantiation = false;
12291               if (isExplicitSpecialization) {
12292                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12293                   IsExplicitSpecializationAfterInstantiation =
12294                     RD->getTemplateSpecializationKind() !=
12295                     TSK_ExplicitSpecialization;
12296                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12297                   IsExplicitSpecializationAfterInstantiation =
12298                     ED->getTemplateSpecializationKind() !=
12299                     TSK_ExplicitSpecialization;
12300               }
12301
12302               NamedDecl *Hidden = nullptr;
12303               if (SkipBody && getLangOpts().CPlusPlus &&
12304                   !hasVisibleDefinition(Def, &Hidden)) {
12305                 // There is a definition of this tag, but it is not visible. We
12306                 // explicitly make use of C++'s one definition rule here, and
12307                 // assume that this definition is identical to the hidden one
12308                 // we already have. Make the existing definition visible and
12309                 // use it in place of this one.
12310                 SkipBody->ShouldSkip = true;
12311                 makeMergedDefinitionVisible(Hidden, KWLoc);
12312                 return Def;
12313               } else if (!IsExplicitSpecializationAfterInstantiation) {
12314                 // A redeclaration in function prototype scope in C isn't
12315                 // visible elsewhere, so merely issue a warning.
12316                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12317                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12318                 else
12319                   Diag(NameLoc, diag::err_redefinition) << Name;
12320                 Diag(Def->getLocation(), diag::note_previous_definition);
12321                 // If this is a redefinition, recover by making this
12322                 // struct be anonymous, which will make any later
12323                 // references get the previous definition.
12324                 Name = nullptr;
12325                 Previous.clear();
12326                 Invalid = true;
12327               }
12328             } else {
12329               // If the type is currently being defined, complain
12330               // about a nested redefinition.
12331               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12332               if (TD->isBeingDefined()) {
12333                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12334                 Diag(PrevTagDecl->getLocation(),
12335                      diag::note_previous_definition);
12336                 Name = nullptr;
12337                 Previous.clear();
12338                 Invalid = true;
12339               }
12340             }
12341
12342             // Okay, this is definition of a previously declared or referenced
12343             // tag. We're going to create a new Decl for it.
12344           }
12345
12346           // Okay, we're going to make a redeclaration.  If this is some kind
12347           // of reference, make sure we build the redeclaration in the same DC
12348           // as the original, and ignore the current access specifier.
12349           if (TUK == TUK_Friend || TUK == TUK_Reference) {
12350             SearchDC = PrevTagDecl->getDeclContext();
12351             AS = AS_none;
12352           }
12353         }
12354         // If we get here we have (another) forward declaration or we
12355         // have a definition.  Just create a new decl.
12356
12357       } else {
12358         // If we get here, this is a definition of a new tag type in a nested
12359         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12360         // new decl/type.  We set PrevDecl to NULL so that the entities
12361         // have distinct types.
12362         Previous.clear();
12363       }
12364       // If we get here, we're going to create a new Decl. If PrevDecl
12365       // is non-NULL, it's a definition of the tag declared by
12366       // PrevDecl. If it's NULL, we have a new definition.
12367
12368
12369     // Otherwise, PrevDecl is not a tag, but was found with tag
12370     // lookup.  This is only actually possible in C++, where a few
12371     // things like templates still live in the tag namespace.
12372     } else {
12373       // Use a better diagnostic if an elaborated-type-specifier
12374       // found the wrong kind of type on the first
12375       // (non-redeclaration) lookup.
12376       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12377           !Previous.isForRedeclaration()) {
12378         unsigned Kind = 0;
12379         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12380         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12381         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12382         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12383         Diag(PrevDecl->getLocation(), diag::note_declared_at);
12384         Invalid = true;
12385
12386       // Otherwise, only diagnose if the declaration is in scope.
12387       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12388                                 SS.isNotEmpty() || isExplicitSpecialization)) {
12389         // do nothing
12390
12391       // Diagnose implicit declarations introduced by elaborated types.
12392       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12393         unsigned Kind = 0;
12394         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12395         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12396         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12397         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12398         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12399         Invalid = true;
12400
12401       // Otherwise it's a declaration.  Call out a particularly common
12402       // case here.
12403       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12404         unsigned Kind = 0;
12405         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12406         Diag(NameLoc, diag::err_tag_definition_of_typedef)
12407           << Name << Kind << TND->getUnderlyingType();
12408         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12409         Invalid = true;
12410
12411       // Otherwise, diagnose.
12412       } else {
12413         // The tag name clashes with something else in the target scope,
12414         // issue an error and recover by making this tag be anonymous.
12415         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12416         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12417         Name = nullptr;
12418         Invalid = true;
12419       }
12420
12421       // The existing declaration isn't relevant to us; we're in a
12422       // new scope, so clear out the previous declaration.
12423       Previous.clear();
12424     }
12425   }
12426
12427 CreateNewDecl:
12428
12429   TagDecl *PrevDecl = nullptr;
12430   if (Previous.isSingleResult())
12431     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12432
12433   // If there is an identifier, use the location of the identifier as the
12434   // location of the decl, otherwise use the location of the struct/union
12435   // keyword.
12436   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12437
12438   // Otherwise, create a new declaration. If there is a previous
12439   // declaration of the same entity, the two will be linked via
12440   // PrevDecl.
12441   TagDecl *New;
12442
12443   bool IsForwardReference = false;
12444   if (Kind == TTK_Enum) {
12445     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12446     // enum X { A, B, C } D;    D should chain to X.
12447     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12448                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12449                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12450     // If this is an undefined enum, warn.
12451     if (TUK != TUK_Definition && !Invalid) {
12452       TagDecl *Def;
12453       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12454           cast<EnumDecl>(New)->isFixed()) {
12455         // C++0x: 7.2p2: opaque-enum-declaration.
12456         // Conflicts are diagnosed above. Do nothing.
12457       }
12458       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12459         Diag(Loc, diag::ext_forward_ref_enum_def)
12460           << New;
12461         Diag(Def->getLocation(), diag::note_previous_definition);
12462       } else {
12463         unsigned DiagID = diag::ext_forward_ref_enum;
12464         if (getLangOpts().MSVCCompat)
12465           DiagID = diag::ext_ms_forward_ref_enum;
12466         else if (getLangOpts().CPlusPlus)
12467           DiagID = diag::err_forward_ref_enum;
12468         Diag(Loc, DiagID);
12469         
12470         // If this is a forward-declared reference to an enumeration, make a 
12471         // note of it; we won't actually be introducing the declaration into
12472         // the declaration context.
12473         if (TUK == TUK_Reference)
12474           IsForwardReference = true;
12475       }
12476     }
12477
12478     if (EnumUnderlying) {
12479       EnumDecl *ED = cast<EnumDecl>(New);
12480       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12481         ED->setIntegerTypeSourceInfo(TI);
12482       else
12483         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12484       ED->setPromotionType(ED->getIntegerType());
12485     }
12486
12487   } else {
12488     // struct/union/class
12489
12490     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12491     // struct X { int A; } D;    D should chain to X.
12492     if (getLangOpts().CPlusPlus) {
12493       // FIXME: Look for a way to use RecordDecl for simple structs.
12494       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12495                                   cast_or_null<CXXRecordDecl>(PrevDecl));
12496
12497       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12498         StdBadAlloc = cast<CXXRecordDecl>(New);
12499     } else
12500       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12501                                cast_or_null<RecordDecl>(PrevDecl));
12502   }
12503
12504   // C++11 [dcl.type]p3:
12505   //   A type-specifier-seq shall not define a class or enumeration [...].
12506   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12507     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12508       << Context.getTagDeclType(New);
12509     Invalid = true;
12510   }
12511
12512   // Maybe add qualifier info.
12513   if (SS.isNotEmpty()) {
12514     if (SS.isSet()) {
12515       // If this is either a declaration or a definition, check the 
12516       // nested-name-specifier against the current context. We don't do this
12517       // for explicit specializations, because they have similar checking
12518       // (with more specific diagnostics) in the call to 
12519       // CheckMemberSpecialization, below.
12520       if (!isExplicitSpecialization &&
12521           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12522           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12523         Invalid = true;
12524
12525       New->setQualifierInfo(SS.getWithLocInContext(Context));
12526       if (TemplateParameterLists.size() > 0) {
12527         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12528       }
12529     }
12530     else
12531       Invalid = true;
12532   }
12533
12534   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12535     // Add alignment attributes if necessary; these attributes are checked when
12536     // the ASTContext lays out the structure.
12537     //
12538     // It is important for implementing the correct semantics that this
12539     // happen here (in act on tag decl). The #pragma pack stack is
12540     // maintained as a result of parser callbacks which can occur at
12541     // many points during the parsing of a struct declaration (because
12542     // the #pragma tokens are effectively skipped over during the
12543     // parsing of the struct).
12544     if (TUK == TUK_Definition) {
12545       AddAlignmentAttributesForRecord(RD);
12546       AddMsStructLayoutForRecord(RD);
12547     }
12548   }
12549
12550   if (ModulePrivateLoc.isValid()) {
12551     if (isExplicitSpecialization)
12552       Diag(New->getLocation(), diag::err_module_private_specialization)
12553         << 2
12554         << FixItHint::CreateRemoval(ModulePrivateLoc);
12555     // __module_private__ does not apply to local classes. However, we only
12556     // diagnose this as an error when the declaration specifiers are
12557     // freestanding. Here, we just ignore the __module_private__.
12558     else if (!SearchDC->isFunctionOrMethod())
12559       New->setModulePrivate();
12560   }
12561
12562   // If this is a specialization of a member class (of a class template),
12563   // check the specialization.
12564   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12565     Invalid = true;
12566
12567   // If we're declaring or defining a tag in function prototype scope in C,
12568   // note that this type can only be used within the function and add it to
12569   // the list of decls to inject into the function definition scope.
12570   if ((Name || Kind == TTK_Enum) &&
12571       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12572     if (getLangOpts().CPlusPlus) {
12573       // C++ [dcl.fct]p6:
12574       //   Types shall not be defined in return or parameter types.
12575       if (TUK == TUK_Definition && !IsTypeSpecifier) {
12576         Diag(Loc, diag::err_type_defined_in_param_type)
12577             << Name;
12578         Invalid = true;
12579       }
12580     } else {
12581       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
12582     }
12583     DeclsInPrototypeScope.push_back(New);
12584   }
12585
12586   if (Invalid)
12587     New->setInvalidDecl();
12588
12589   if (Attr)
12590     ProcessDeclAttributeList(S, New, Attr);
12591
12592   // Set the lexical context. If the tag has a C++ scope specifier, the
12593   // lexical context will be different from the semantic context.
12594   New->setLexicalDeclContext(CurContext);
12595
12596   // Mark this as a friend decl if applicable.
12597   // In Microsoft mode, a friend declaration also acts as a forward
12598   // declaration so we always pass true to setObjectOfFriendDecl to make
12599   // the tag name visible.
12600   if (TUK == TUK_Friend)
12601     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
12602
12603   // Set the access specifier.
12604   if (!Invalid && SearchDC->isRecord())
12605     SetMemberAccessSpecifier(New, PrevDecl, AS);
12606
12607   if (TUK == TUK_Definition)
12608     New->startDefinition();
12609
12610   // If this has an identifier, add it to the scope stack.
12611   if (TUK == TUK_Friend) {
12612     // We might be replacing an existing declaration in the lookup tables;
12613     // if so, borrow its access specifier.
12614     if (PrevDecl)
12615       New->setAccess(PrevDecl->getAccess());
12616
12617     DeclContext *DC = New->getDeclContext()->getRedeclContext();
12618     DC->makeDeclVisibleInContext(New);
12619     if (Name) // can be null along some error paths
12620       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12621         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
12622   } else if (Name) {
12623     S = getNonFieldDeclScope(S);
12624     PushOnScopeChains(New, S, !IsForwardReference);
12625     if (IsForwardReference)
12626       SearchDC->makeDeclVisibleInContext(New);
12627
12628   } else {
12629     CurContext->addDecl(New);
12630   }
12631
12632   // If this is the C FILE type, notify the AST context.
12633   if (IdentifierInfo *II = New->getIdentifier())
12634     if (!New->isInvalidDecl() &&
12635         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
12636         II->isStr("FILE"))
12637       Context.setFILEDecl(New);
12638
12639   if (PrevDecl)
12640     mergeDeclAttributes(New, PrevDecl);
12641
12642   // If there's a #pragma GCC visibility in scope, set the visibility of this
12643   // record.
12644   AddPushedVisibilityAttribute(New);
12645
12646   OwnedDecl = true;
12647   // In C++, don't return an invalid declaration. We can't recover well from
12648   // the cases where we make the type anonymous.
12649   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
12650 }
12651
12652 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
12653   AdjustDeclIfTemplate(TagD);
12654   TagDecl *Tag = cast<TagDecl>(TagD);
12655   
12656   // Enter the tag context.
12657   PushDeclContext(S, Tag);
12658
12659   ActOnDocumentableDecl(TagD);
12660
12661   // If there's a #pragma GCC visibility in scope, set the visibility of this
12662   // record.
12663   AddPushedVisibilityAttribute(Tag);
12664 }
12665
12666 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
12667   assert(isa<ObjCContainerDecl>(IDecl) && 
12668          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
12669   DeclContext *OCD = cast<DeclContext>(IDecl);
12670   assert(getContainingDC(OCD) == CurContext &&
12671       "The next DeclContext should be lexically contained in the current one.");
12672   CurContext = OCD;
12673   return IDecl;
12674 }
12675
12676 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
12677                                            SourceLocation FinalLoc,
12678                                            bool IsFinalSpelledSealed,
12679                                            SourceLocation LBraceLoc) {
12680   AdjustDeclIfTemplate(TagD);
12681   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
12682
12683   FieldCollector->StartClass();
12684
12685   if (!Record->getIdentifier())
12686     return;
12687
12688   if (FinalLoc.isValid())
12689     Record->addAttr(new (Context)
12690                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
12691
12692   // C++ [class]p2:
12693   //   [...] The class-name is also inserted into the scope of the
12694   //   class itself; this is known as the injected-class-name. For
12695   //   purposes of access checking, the injected-class-name is treated
12696   //   as if it were a public member name.
12697   CXXRecordDecl *InjectedClassName
12698     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
12699                             Record->getLocStart(), Record->getLocation(),
12700                             Record->getIdentifier(),
12701                             /*PrevDecl=*/nullptr,
12702                             /*DelayTypeCreation=*/true);
12703   Context.getTypeDeclType(InjectedClassName, Record);
12704   InjectedClassName->setImplicit();
12705   InjectedClassName->setAccess(AS_public);
12706   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
12707       InjectedClassName->setDescribedClassTemplate(Template);
12708   PushOnScopeChains(InjectedClassName, S);
12709   assert(InjectedClassName->isInjectedClassName() &&
12710          "Broken injected-class-name");
12711 }
12712
12713 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
12714                                     SourceLocation RBraceLoc) {
12715   AdjustDeclIfTemplate(TagD);
12716   TagDecl *Tag = cast<TagDecl>(TagD);
12717   Tag->setRBraceLoc(RBraceLoc);
12718
12719   // Make sure we "complete" the definition even it is invalid.
12720   if (Tag->isBeingDefined()) {
12721     assert(Tag->isInvalidDecl() && "We should already have completed it");
12722     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12723       RD->completeDefinition();
12724   }
12725
12726   if (isa<CXXRecordDecl>(Tag))
12727     FieldCollector->FinishClass();
12728
12729   // Exit this scope of this tag's definition.
12730   PopDeclContext();
12731
12732   if (getCurLexicalContext()->isObjCContainer() &&
12733       Tag->getDeclContext()->isFileContext())
12734     Tag->setTopLevelDeclInObjCContainer();
12735
12736   // Notify the consumer that we've defined a tag.
12737   if (!Tag->isInvalidDecl())
12738     Consumer.HandleTagDeclDefinition(Tag);
12739 }
12740
12741 void Sema::ActOnObjCContainerFinishDefinition() {
12742   // Exit this scope of this interface definition.
12743   PopDeclContext();
12744 }
12745
12746 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
12747   assert(DC == CurContext && "Mismatch of container contexts");
12748   OriginalLexicalContext = DC;
12749   ActOnObjCContainerFinishDefinition();
12750 }
12751
12752 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
12753   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
12754   OriginalLexicalContext = nullptr;
12755 }
12756
12757 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
12758   AdjustDeclIfTemplate(TagD);
12759   TagDecl *Tag = cast<TagDecl>(TagD);
12760   Tag->setInvalidDecl();
12761
12762   // Make sure we "complete" the definition even it is invalid.
12763   if (Tag->isBeingDefined()) {
12764     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12765       RD->completeDefinition();
12766   }
12767
12768   // We're undoing ActOnTagStartDefinition here, not
12769   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
12770   // the FieldCollector.
12771
12772   PopDeclContext();  
12773 }
12774
12775 // Note that FieldName may be null for anonymous bitfields.
12776 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
12777                                 IdentifierInfo *FieldName,
12778                                 QualType FieldTy, bool IsMsStruct,
12779                                 Expr *BitWidth, bool *ZeroWidth) {
12780   // Default to true; that shouldn't confuse checks for emptiness
12781   if (ZeroWidth)
12782     *ZeroWidth = true;
12783
12784   // C99 6.7.2.1p4 - verify the field type.
12785   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
12786   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
12787     // Handle incomplete types with specific error.
12788     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
12789       return ExprError();
12790     if (FieldName)
12791       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12792         << FieldName << FieldTy << BitWidth->getSourceRange();
12793     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12794       << FieldTy << BitWidth->getSourceRange();
12795   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12796                                              UPPC_BitFieldWidth))
12797     return ExprError();
12798
12799   // If the bit-width is type- or value-dependent, don't try to check
12800   // it now.
12801   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
12802     return BitWidth;
12803
12804   llvm::APSInt Value;
12805   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
12806   if (ICE.isInvalid())
12807     return ICE;
12808   BitWidth = ICE.get();
12809
12810   if (Value != 0 && ZeroWidth)
12811     *ZeroWidth = false;
12812
12813   // Zero-width bitfield is ok for anonymous field.
12814   if (Value == 0 && FieldName)
12815     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
12816
12817   if (Value.isSigned() && Value.isNegative()) {
12818     if (FieldName)
12819       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
12820                << FieldName << Value.toString(10);
12821     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
12822       << Value.toString(10);
12823   }
12824
12825   if (!FieldTy->isDependentType()) {
12826     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
12827     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
12828     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
12829
12830     // Over-wide bitfields are an error in C or when using the MSVC bitfield
12831     // ABI.
12832     bool CStdConstraintViolation =
12833         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
12834     bool MSBitfieldViolation =
12835         Value.ugt(TypeStorageSize) &&
12836         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
12837     if (CStdConstraintViolation || MSBitfieldViolation) {
12838       unsigned DiagWidth =
12839           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
12840       if (FieldName)
12841         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
12842                << FieldName << (unsigned)Value.getZExtValue()
12843                << !CStdConstraintViolation << DiagWidth;
12844
12845       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
12846              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
12847              << DiagWidth;
12848     }
12849
12850     // Warn on types where the user might conceivably expect to get all
12851     // specified bits as value bits: that's all integral types other than
12852     // 'bool'.
12853     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
12854       if (FieldName)
12855         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
12856             << FieldName << (unsigned)Value.getZExtValue()
12857             << (unsigned)TypeWidth;
12858       else
12859         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
12860             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
12861     }
12862   }
12863
12864   return BitWidth;
12865 }
12866
12867 /// ActOnField - Each field of a C struct/union is passed into this in order
12868 /// to create a FieldDecl object for it.
12869 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
12870                        Declarator &D, Expr *BitfieldWidth) {
12871   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
12872                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
12873                                /*InitStyle=*/ICIS_NoInit, AS_public);
12874   return Res;
12875 }
12876
12877 /// HandleField - Analyze a field of a C struct or a C++ data member.
12878 ///
12879 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
12880                              SourceLocation DeclStart,
12881                              Declarator &D, Expr *BitWidth,
12882                              InClassInitStyle InitStyle,
12883                              AccessSpecifier AS) {
12884   IdentifierInfo *II = D.getIdentifier();
12885   SourceLocation Loc = DeclStart;
12886   if (II) Loc = D.getIdentifierLoc();
12887
12888   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12889   QualType T = TInfo->getType();
12890   if (getLangOpts().CPlusPlus) {
12891     CheckExtraCXXDefaultArguments(D);
12892
12893     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12894                                         UPPC_DataMemberType)) {
12895       D.setInvalidType();
12896       T = Context.IntTy;
12897       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12898     }
12899   }
12900
12901   // TR 18037 does not allow fields to be declared with address spaces.
12902   if (T.getQualifiers().hasAddressSpace()) {
12903     Diag(Loc, diag::err_field_with_address_space);
12904     D.setInvalidType();
12905   }
12906
12907   // OpenCL 1.2 spec, s6.9 r:
12908   // The event type cannot be used to declare a structure or union field.
12909   if (LangOpts.OpenCL && T->isEventT()) {
12910     Diag(Loc, diag::err_event_t_struct_field);
12911     D.setInvalidType();
12912   }
12913
12914   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12915
12916   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12917     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12918          diag::err_invalid_thread)
12919       << DeclSpec::getSpecifierName(TSCS);
12920
12921   // Check to see if this name was declared as a member previously
12922   NamedDecl *PrevDecl = nullptr;
12923   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12924   LookupName(Previous, S);
12925   switch (Previous.getResultKind()) {
12926     case LookupResult::Found:
12927     case LookupResult::FoundUnresolvedValue:
12928       PrevDecl = Previous.getAsSingle<NamedDecl>();
12929       break;
12930       
12931     case LookupResult::FoundOverloaded:
12932       PrevDecl = Previous.getRepresentativeDecl();
12933       break;
12934       
12935     case LookupResult::NotFound:
12936     case LookupResult::NotFoundInCurrentInstantiation:
12937     case LookupResult::Ambiguous:
12938       break;
12939   }
12940   Previous.suppressDiagnostics();
12941
12942   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12943     // Maybe we will complain about the shadowed template parameter.
12944     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12945     // Just pretend that we didn't see the previous declaration.
12946     PrevDecl = nullptr;
12947   }
12948
12949   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12950     PrevDecl = nullptr;
12951
12952   bool Mutable
12953     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
12954   SourceLocation TSSL = D.getLocStart();
12955   FieldDecl *NewFD
12956     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
12957                      TSSL, AS, PrevDecl, &D);
12958
12959   if (NewFD->isInvalidDecl())
12960     Record->setInvalidDecl();
12961
12962   if (D.getDeclSpec().isModulePrivateSpecified())
12963     NewFD->setModulePrivate();
12964   
12965   if (NewFD->isInvalidDecl() && PrevDecl) {
12966     // Don't introduce NewFD into scope; there's already something
12967     // with the same name in the same scope.
12968   } else if (II) {
12969     PushOnScopeChains(NewFD, S);
12970   } else
12971     Record->addDecl(NewFD);
12972
12973   return NewFD;
12974 }
12975
12976 /// \brief Build a new FieldDecl and check its well-formedness.
12977 ///
12978 /// This routine builds a new FieldDecl given the fields name, type,
12979 /// record, etc. \p PrevDecl should refer to any previous declaration
12980 /// with the same name and in the same scope as the field to be
12981 /// created.
12982 ///
12983 /// \returns a new FieldDecl.
12984 ///
12985 /// \todo The Declarator argument is a hack. It will be removed once
12986 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
12987                                 TypeSourceInfo *TInfo,
12988                                 RecordDecl *Record, SourceLocation Loc,
12989                                 bool Mutable, Expr *BitWidth,
12990                                 InClassInitStyle InitStyle,
12991                                 SourceLocation TSSL,
12992                                 AccessSpecifier AS, NamedDecl *PrevDecl,
12993                                 Declarator *D) {
12994   IdentifierInfo *II = Name.getAsIdentifierInfo();
12995   bool InvalidDecl = false;
12996   if (D) InvalidDecl = D->isInvalidType();
12997
12998   // If we receive a broken type, recover by assuming 'int' and
12999   // marking this declaration as invalid.
13000   if (T.isNull()) {
13001     InvalidDecl = true;
13002     T = Context.IntTy;
13003   }
13004
13005   QualType EltTy = Context.getBaseElementType(T);
13006   if (!EltTy->isDependentType()) {
13007     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13008       // Fields of incomplete type force their record to be invalid.
13009       Record->setInvalidDecl();
13010       InvalidDecl = true;
13011     } else {
13012       NamedDecl *Def;
13013       EltTy->isIncompleteType(&Def);
13014       if (Def && Def->isInvalidDecl()) {
13015         Record->setInvalidDecl();
13016         InvalidDecl = true;
13017       }
13018     }
13019   }
13020
13021   // OpenCL v1.2 s6.9.c: bitfields are not supported.
13022   if (BitWidth && getLangOpts().OpenCL) {
13023     Diag(Loc, diag::err_opencl_bitfields);
13024     InvalidDecl = true;
13025   }
13026
13027   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13028   // than a variably modified type.
13029   if (!InvalidDecl && T->isVariablyModifiedType()) {
13030     bool SizeIsNegative;
13031     llvm::APSInt Oversized;
13032
13033     TypeSourceInfo *FixedTInfo =
13034       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13035                                                     SizeIsNegative,
13036                                                     Oversized);
13037     if (FixedTInfo) {
13038       Diag(Loc, diag::warn_illegal_constant_array_size);
13039       TInfo = FixedTInfo;
13040       T = FixedTInfo->getType();
13041     } else {
13042       if (SizeIsNegative)
13043         Diag(Loc, diag::err_typecheck_negative_array_size);
13044       else if (Oversized.getBoolValue())
13045         Diag(Loc, diag::err_array_too_large)
13046           << Oversized.toString(10);
13047       else
13048         Diag(Loc, diag::err_typecheck_field_variable_size);
13049       InvalidDecl = true;
13050     }
13051   }
13052
13053   // Fields can not have abstract class types
13054   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13055                                              diag::err_abstract_type_in_decl,
13056                                              AbstractFieldType))
13057     InvalidDecl = true;
13058
13059   bool ZeroWidth = false;
13060   if (InvalidDecl)
13061     BitWidth = nullptr;
13062   // If this is declared as a bit-field, check the bit-field.
13063   if (BitWidth) {
13064     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13065                               &ZeroWidth).get();
13066     if (!BitWidth) {
13067       InvalidDecl = true;
13068       BitWidth = nullptr;
13069       ZeroWidth = false;
13070     }
13071   }
13072
13073   // Check that 'mutable' is consistent with the type of the declaration.
13074   if (!InvalidDecl && Mutable) {
13075     unsigned DiagID = 0;
13076     if (T->isReferenceType())
13077       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13078                                         : diag::err_mutable_reference;
13079     else if (T.isConstQualified())
13080       DiagID = diag::err_mutable_const;
13081
13082     if (DiagID) {
13083       SourceLocation ErrLoc = Loc;
13084       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13085         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13086       Diag(ErrLoc, DiagID);
13087       if (DiagID != diag::ext_mutable_reference) {
13088         Mutable = false;
13089         InvalidDecl = true;
13090       }
13091     }
13092   }
13093
13094   // C++11 [class.union]p8 (DR1460):
13095   //   At most one variant member of a union may have a
13096   //   brace-or-equal-initializer.
13097   if (InitStyle != ICIS_NoInit)
13098     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13099
13100   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13101                                        BitWidth, Mutable, InitStyle);
13102   if (InvalidDecl)
13103     NewFD->setInvalidDecl();
13104
13105   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13106     Diag(Loc, diag::err_duplicate_member) << II;
13107     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13108     NewFD->setInvalidDecl();
13109   }
13110
13111   if (!InvalidDecl && getLangOpts().CPlusPlus) {
13112     if (Record->isUnion()) {
13113       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13114         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13115         if (RDecl->getDefinition()) {
13116           // C++ [class.union]p1: An object of a class with a non-trivial
13117           // constructor, a non-trivial copy constructor, a non-trivial
13118           // destructor, or a non-trivial copy assignment operator
13119           // cannot be a member of a union, nor can an array of such
13120           // objects.
13121           if (CheckNontrivialField(NewFD))
13122             NewFD->setInvalidDecl();
13123         }
13124       }
13125
13126       // C++ [class.union]p1: If a union contains a member of reference type,
13127       // the program is ill-formed, except when compiling with MSVC extensions
13128       // enabled.
13129       if (EltTy->isReferenceType()) {
13130         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13131                                     diag::ext_union_member_of_reference_type :
13132                                     diag::err_union_member_of_reference_type)
13133           << NewFD->getDeclName() << EltTy;
13134         if (!getLangOpts().MicrosoftExt)
13135           NewFD->setInvalidDecl();
13136       }
13137     }
13138   }
13139
13140   // FIXME: We need to pass in the attributes given an AST
13141   // representation, not a parser representation.
13142   if (D) {
13143     // FIXME: The current scope is almost... but not entirely... correct here.
13144     ProcessDeclAttributes(getCurScope(), NewFD, *D);
13145
13146     if (NewFD->hasAttrs())
13147       CheckAlignasUnderalignment(NewFD);
13148   }
13149
13150   // In auto-retain/release, infer strong retension for fields of
13151   // retainable type.
13152   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13153     NewFD->setInvalidDecl();
13154
13155   if (T.isObjCGCWeak())
13156     Diag(Loc, diag::warn_attribute_weak_on_field);
13157
13158   NewFD->setAccess(AS);
13159   return NewFD;
13160 }
13161
13162 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13163   assert(FD);
13164   assert(getLangOpts().CPlusPlus && "valid check only for C++");
13165
13166   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13167     return false;
13168
13169   QualType EltTy = Context.getBaseElementType(FD->getType());
13170   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13171     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13172     if (RDecl->getDefinition()) {
13173       // We check for copy constructors before constructors
13174       // because otherwise we'll never get complaints about
13175       // copy constructors.
13176
13177       CXXSpecialMember member = CXXInvalid;
13178       // We're required to check for any non-trivial constructors. Since the
13179       // implicit default constructor is suppressed if there are any
13180       // user-declared constructors, we just need to check that there is a
13181       // trivial default constructor and a trivial copy constructor. (We don't
13182       // worry about move constructors here, since this is a C++98 check.)
13183       if (RDecl->hasNonTrivialCopyConstructor())
13184         member = CXXCopyConstructor;
13185       else if (!RDecl->hasTrivialDefaultConstructor())
13186         member = CXXDefaultConstructor;
13187       else if (RDecl->hasNonTrivialCopyAssignment())
13188         member = CXXCopyAssignment;
13189       else if (RDecl->hasNonTrivialDestructor())
13190         member = CXXDestructor;
13191
13192       if (member != CXXInvalid) {
13193         if (!getLangOpts().CPlusPlus11 &&
13194             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13195           // Objective-C++ ARC: it is an error to have a non-trivial field of
13196           // a union. However, system headers in Objective-C programs 
13197           // occasionally have Objective-C lifetime objects within unions,
13198           // and rather than cause the program to fail, we make those 
13199           // members unavailable.
13200           SourceLocation Loc = FD->getLocation();
13201           if (getSourceManager().isInSystemHeader(Loc)) {
13202             if (!FD->hasAttr<UnavailableAttr>())
13203               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13204                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13205             return false;
13206           }
13207         }
13208
13209         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13210                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13211                diag::err_illegal_union_or_anon_struct_member)
13212           << FD->getParent()->isUnion() << FD->getDeclName() << member;
13213         DiagnoseNontrivial(RDecl, member);
13214         return !getLangOpts().CPlusPlus11;
13215       }
13216     }
13217   }
13218
13219   return false;
13220 }
13221
13222 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13223 ///  AST enum value.
13224 static ObjCIvarDecl::AccessControl
13225 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13226   switch (ivarVisibility) {
13227   default: llvm_unreachable("Unknown visitibility kind");
13228   case tok::objc_private: return ObjCIvarDecl::Private;
13229   case tok::objc_public: return ObjCIvarDecl::Public;
13230   case tok::objc_protected: return ObjCIvarDecl::Protected;
13231   case tok::objc_package: return ObjCIvarDecl::Package;
13232   }
13233 }
13234
13235 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13236 /// in order to create an IvarDecl object for it.
13237 Decl *Sema::ActOnIvar(Scope *S,
13238                                 SourceLocation DeclStart,
13239                                 Declarator &D, Expr *BitfieldWidth,
13240                                 tok::ObjCKeywordKind Visibility) {
13241
13242   IdentifierInfo *II = D.getIdentifier();
13243   Expr *BitWidth = (Expr*)BitfieldWidth;
13244   SourceLocation Loc = DeclStart;
13245   if (II) Loc = D.getIdentifierLoc();
13246
13247   // FIXME: Unnamed fields can be handled in various different ways, for
13248   // example, unnamed unions inject all members into the struct namespace!
13249
13250   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13251   QualType T = TInfo->getType();
13252
13253   if (BitWidth) {
13254     // 6.7.2.1p3, 6.7.2.1p4
13255     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13256     if (!BitWidth)
13257       D.setInvalidType();
13258   } else {
13259     // Not a bitfield.
13260
13261     // validate II.
13262
13263   }
13264   if (T->isReferenceType()) {
13265     Diag(Loc, diag::err_ivar_reference_type);
13266     D.setInvalidType();
13267   }
13268   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13269   // than a variably modified type.
13270   else if (T->isVariablyModifiedType()) {
13271     Diag(Loc, diag::err_typecheck_ivar_variable_size);
13272     D.setInvalidType();
13273   }
13274
13275   // Get the visibility (access control) for this ivar.
13276   ObjCIvarDecl::AccessControl ac =
13277     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13278                                         : ObjCIvarDecl::None;
13279   // Must set ivar's DeclContext to its enclosing interface.
13280   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13281   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13282     return nullptr;
13283   ObjCContainerDecl *EnclosingContext;
13284   if (ObjCImplementationDecl *IMPDecl =
13285       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13286     if (LangOpts.ObjCRuntime.isFragile()) {
13287     // Case of ivar declared in an implementation. Context is that of its class.
13288       EnclosingContext = IMPDecl->getClassInterface();
13289       assert(EnclosingContext && "Implementation has no class interface!");
13290     }
13291     else
13292       EnclosingContext = EnclosingDecl;
13293   } else {
13294     if (ObjCCategoryDecl *CDecl = 
13295         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13296       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13297         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13298         return nullptr;
13299       }
13300     }
13301     EnclosingContext = EnclosingDecl;
13302   }
13303
13304   // Construct the decl.
13305   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13306                                              DeclStart, Loc, II, T,
13307                                              TInfo, ac, (Expr *)BitfieldWidth);
13308
13309   if (II) {
13310     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13311                                            ForRedeclaration);
13312     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13313         && !isa<TagDecl>(PrevDecl)) {
13314       Diag(Loc, diag::err_duplicate_member) << II;
13315       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13316       NewID->setInvalidDecl();
13317     }
13318   }
13319
13320   // Process attributes attached to the ivar.
13321   ProcessDeclAttributes(S, NewID, D);
13322
13323   if (D.isInvalidType())
13324     NewID->setInvalidDecl();
13325
13326   // In ARC, infer 'retaining' for ivars of retainable type.
13327   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13328     NewID->setInvalidDecl();
13329
13330   if (D.getDeclSpec().isModulePrivateSpecified())
13331     NewID->setModulePrivate();
13332   
13333   if (II) {
13334     // FIXME: When interfaces are DeclContexts, we'll need to add
13335     // these to the interface.
13336     S->AddDecl(NewID);
13337     IdResolver.AddDecl(NewID);
13338   }
13339   
13340   if (LangOpts.ObjCRuntime.isNonFragile() &&
13341       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13342     Diag(Loc, diag::warn_ivars_in_interface);
13343   
13344   return NewID;
13345 }
13346
13347 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 
13348 /// class and class extensions. For every class \@interface and class 
13349 /// extension \@interface, if the last ivar is a bitfield of any type, 
13350 /// then add an implicit `char :0` ivar to the end of that interface.
13351 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13352                              SmallVectorImpl<Decl *> &AllIvarDecls) {
13353   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13354     return;
13355   
13356   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13357   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13358   
13359   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13360     return;
13361   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13362   if (!ID) {
13363     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13364       if (!CD->IsClassExtension())
13365         return;
13366     }
13367     // No need to add this to end of @implementation.
13368     else
13369       return;
13370   }
13371   // All conditions are met. Add a new bitfield to the tail end of ivars.
13372   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13373   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13374
13375   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13376                               DeclLoc, DeclLoc, nullptr,
13377                               Context.CharTy, 
13378                               Context.getTrivialTypeSourceInfo(Context.CharTy,
13379                                                                DeclLoc),
13380                               ObjCIvarDecl::Private, BW,
13381                               true);
13382   AllIvarDecls.push_back(Ivar);
13383 }
13384
13385 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13386                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
13387                        SourceLocation RBrac, AttributeList *Attr) {
13388   assert(EnclosingDecl && "missing record or interface decl");
13389
13390   // If this is an Objective-C @implementation or category and we have
13391   // new fields here we should reset the layout of the interface since
13392   // it will now change.
13393   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13394     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13395     switch (DC->getKind()) {
13396     default: break;
13397     case Decl::ObjCCategory:
13398       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13399       break;
13400     case Decl::ObjCImplementation:
13401       Context.
13402         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13403       break;
13404     }
13405   }
13406   
13407   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13408
13409   // Start counting up the number of named members; make sure to include
13410   // members of anonymous structs and unions in the total.
13411   unsigned NumNamedMembers = 0;
13412   if (Record) {
13413     for (const auto *I : Record->decls()) {
13414       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13415         if (IFD->getDeclName())
13416           ++NumNamedMembers;
13417     }
13418   }
13419
13420   // Verify that all the fields are okay.
13421   SmallVector<FieldDecl*, 32> RecFields;
13422
13423   bool ARCErrReported = false;
13424   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13425        i != end; ++i) {
13426     FieldDecl *FD = cast<FieldDecl>(*i);
13427
13428     // Get the type for the field.
13429     const Type *FDTy = FD->getType().getTypePtr();
13430
13431     if (!FD->isAnonymousStructOrUnion()) {
13432       // Remember all fields written by the user.
13433       RecFields.push_back(FD);
13434     }
13435
13436     // If the field is already invalid for some reason, don't emit more
13437     // diagnostics about it.
13438     if (FD->isInvalidDecl()) {
13439       EnclosingDecl->setInvalidDecl();
13440       continue;
13441     }
13442
13443     // C99 6.7.2.1p2:
13444     //   A structure or union shall not contain a member with
13445     //   incomplete or function type (hence, a structure shall not
13446     //   contain an instance of itself, but may contain a pointer to
13447     //   an instance of itself), except that the last member of a
13448     //   structure with more than one named member may have incomplete
13449     //   array type; such a structure (and any union containing,
13450     //   possibly recursively, a member that is such a structure)
13451     //   shall not be a member of a structure or an element of an
13452     //   array.
13453     if (FDTy->isFunctionType()) {
13454       // Field declared as a function.
13455       Diag(FD->getLocation(), diag::err_field_declared_as_function)
13456         << FD->getDeclName();
13457       FD->setInvalidDecl();
13458       EnclosingDecl->setInvalidDecl();
13459       continue;
13460     } else if (FDTy->isIncompleteArrayType() && Record && 
13461                ((i + 1 == Fields.end() && !Record->isUnion()) ||
13462                 ((getLangOpts().MicrosoftExt ||
13463                   getLangOpts().CPlusPlus) &&
13464                  (i + 1 == Fields.end() || Record->isUnion())))) {
13465       // Flexible array member.
13466       // Microsoft and g++ is more permissive regarding flexible array.
13467       // It will accept flexible array in union and also
13468       // as the sole element of a struct/class.
13469       unsigned DiagID = 0;
13470       if (Record->isUnion())
13471         DiagID = getLangOpts().MicrosoftExt
13472                      ? diag::ext_flexible_array_union_ms
13473                      : getLangOpts().CPlusPlus
13474                            ? diag::ext_flexible_array_union_gnu
13475                            : diag::err_flexible_array_union;
13476       else if (Fields.size() == 1)
13477         DiagID = getLangOpts().MicrosoftExt
13478                      ? diag::ext_flexible_array_empty_aggregate_ms
13479                      : getLangOpts().CPlusPlus
13480                            ? diag::ext_flexible_array_empty_aggregate_gnu
13481                            : NumNamedMembers < 1
13482                                  ? diag::err_flexible_array_empty_aggregate
13483                                  : 0;
13484
13485       if (DiagID)
13486         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13487                                         << Record->getTagKind();
13488       // While the layout of types that contain virtual bases is not specified
13489       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13490       // virtual bases after the derived members.  This would make a flexible
13491       // array member declared at the end of an object not adjacent to the end
13492       // of the type.
13493       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13494         if (RD->getNumVBases() != 0)
13495           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13496             << FD->getDeclName() << Record->getTagKind();
13497       if (!getLangOpts().C99)
13498         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13499           << FD->getDeclName() << Record->getTagKind();
13500
13501       // If the element type has a non-trivial destructor, we would not
13502       // implicitly destroy the elements, so disallow it for now.
13503       //
13504       // FIXME: GCC allows this. We should probably either implicitly delete
13505       // the destructor of the containing class, or just allow this.
13506       QualType BaseElem = Context.getBaseElementType(FD->getType());
13507       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13508         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13509           << FD->getDeclName() << FD->getType();
13510         FD->setInvalidDecl();
13511         EnclosingDecl->setInvalidDecl();
13512         continue;
13513       }
13514       // Okay, we have a legal flexible array member at the end of the struct.
13515       Record->setHasFlexibleArrayMember(true);
13516     } else if (!FDTy->isDependentType() &&
13517                RequireCompleteType(FD->getLocation(), FD->getType(),
13518                                    diag::err_field_incomplete)) {
13519       // Incomplete type
13520       FD->setInvalidDecl();
13521       EnclosingDecl->setInvalidDecl();
13522       continue;
13523     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13524       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13525         // A type which contains a flexible array member is considered to be a
13526         // flexible array member.
13527         Record->setHasFlexibleArrayMember(true);
13528         if (!Record->isUnion()) {
13529           // If this is a struct/class and this is not the last element, reject
13530           // it.  Note that GCC supports variable sized arrays in the middle of
13531           // structures.
13532           if (i + 1 != Fields.end())
13533             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13534               << FD->getDeclName() << FD->getType();
13535           else {
13536             // We support flexible arrays at the end of structs in
13537             // other structs as an extension.
13538             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13539               << FD->getDeclName();
13540           }
13541         }
13542       }
13543       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13544           RequireNonAbstractType(FD->getLocation(), FD->getType(),
13545                                  diag::err_abstract_type_in_decl,
13546                                  AbstractIvarType)) {
13547         // Ivars can not have abstract class types
13548         FD->setInvalidDecl();
13549       }
13550       if (Record && FDTTy->getDecl()->hasObjectMember())
13551         Record->setHasObjectMember(true);
13552       if (Record && FDTTy->getDecl()->hasVolatileMember())
13553         Record->setHasVolatileMember(true);
13554     } else if (FDTy->isObjCObjectType()) {
13555       /// A field cannot be an Objective-c object
13556       Diag(FD->getLocation(), diag::err_statically_allocated_object)
13557         << FixItHint::CreateInsertion(FD->getLocation(), "*");
13558       QualType T = Context.getObjCObjectPointerType(FD->getType());
13559       FD->setType(T);
13560     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13561                (!getLangOpts().CPlusPlus || Record->isUnion())) {
13562       // It's an error in ARC if a field has lifetime.
13563       // We don't want to report this in a system header, though,
13564       // so we just make the field unavailable.
13565       // FIXME: that's really not sufficient; we need to make the type
13566       // itself invalid to, say, initialize or copy.
13567       QualType T = FD->getType();
13568       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
13569       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13570         SourceLocation loc = FD->getLocation();
13571         if (getSourceManager().isInSystemHeader(loc)) {
13572           if (!FD->hasAttr<UnavailableAttr>()) {
13573             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13574                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
13575           }
13576         } else {
13577           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 
13578             << T->isBlockPointerType() << Record->getTagKind();
13579         }
13580         ARCErrReported = true;
13581       }
13582     } else if (getLangOpts().ObjC1 &&
13583                getLangOpts().getGC() != LangOptions::NonGC &&
13584                Record && !Record->hasObjectMember()) {
13585       if (FD->getType()->isObjCObjectPointerType() ||
13586           FD->getType().isObjCGCStrong())
13587         Record->setHasObjectMember(true);
13588       else if (Context.getAsArrayType(FD->getType())) {
13589         QualType BaseType = Context.getBaseElementType(FD->getType());
13590         if (BaseType->isRecordType() && 
13591             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
13592           Record->setHasObjectMember(true);
13593         else if (BaseType->isObjCObjectPointerType() ||
13594                  BaseType.isObjCGCStrong())
13595                Record->setHasObjectMember(true);
13596       }
13597     }
13598     if (Record && FD->getType().isVolatileQualified())
13599       Record->setHasVolatileMember(true);
13600     // Keep track of the number of named members.
13601     if (FD->getIdentifier())
13602       ++NumNamedMembers;
13603   }
13604
13605   // Okay, we successfully defined 'Record'.
13606   if (Record) {
13607     bool Completed = false;
13608     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
13609       if (!CXXRecord->isInvalidDecl()) {
13610         // Set access bits correctly on the directly-declared conversions.
13611         for (CXXRecordDecl::conversion_iterator
13612                I = CXXRecord->conversion_begin(),
13613                E = CXXRecord->conversion_end(); I != E; ++I)
13614           I.setAccess((*I)->getAccess());
13615         
13616         if (!CXXRecord->isDependentType()) {
13617           if (CXXRecord->hasUserDeclaredDestructor()) {
13618             // Adjust user-defined destructor exception spec.
13619             if (getLangOpts().CPlusPlus11)
13620               AdjustDestructorExceptionSpec(CXXRecord,
13621                                             CXXRecord->getDestructor());
13622           }
13623
13624           // Add any implicitly-declared members to this class.
13625           AddImplicitlyDeclaredMembersToClass(CXXRecord);
13626
13627           // If we have virtual base classes, we may end up finding multiple 
13628           // final overriders for a given virtual function. Check for this 
13629           // problem now.
13630           if (CXXRecord->getNumVBases()) {
13631             CXXFinalOverriderMap FinalOverriders;
13632             CXXRecord->getFinalOverriders(FinalOverriders);
13633             
13634             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 
13635                                              MEnd = FinalOverriders.end();
13636                  M != MEnd; ++M) {
13637               for (OverridingMethods::iterator SO = M->second.begin(), 
13638                                             SOEnd = M->second.end();
13639                    SO != SOEnd; ++SO) {
13640                 assert(SO->second.size() > 0 && 
13641                        "Virtual function without overridding functions?");
13642                 if (SO->second.size() == 1)
13643                   continue;
13644                 
13645                 // C++ [class.virtual]p2:
13646                 //   In a derived class, if a virtual member function of a base
13647                 //   class subobject has more than one final overrider the
13648                 //   program is ill-formed.
13649                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
13650                   << (const NamedDecl *)M->first << Record;
13651                 Diag(M->first->getLocation(), 
13652                      diag::note_overridden_virtual_function);
13653                 for (OverridingMethods::overriding_iterator 
13654                           OM = SO->second.begin(), 
13655                        OMEnd = SO->second.end();
13656                      OM != OMEnd; ++OM)
13657                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
13658                     << (const NamedDecl *)M->first << OM->Method->getParent();
13659                 
13660                 Record->setInvalidDecl();
13661               }
13662             }
13663             CXXRecord->completeDefinition(&FinalOverriders);
13664             Completed = true;
13665           }
13666         }
13667       }
13668     }
13669     
13670     if (!Completed)
13671       Record->completeDefinition();
13672
13673     if (Record->hasAttrs()) {
13674       CheckAlignasUnderalignment(Record);
13675
13676       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
13677         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
13678                                            IA->getRange(), IA->getBestCase(),
13679                                            IA->getSemanticSpelling());
13680     }
13681
13682     // Check if the structure/union declaration is a type that can have zero
13683     // size in C. For C this is a language extension, for C++ it may cause
13684     // compatibility problems.
13685     bool CheckForZeroSize;
13686     if (!getLangOpts().CPlusPlus) {
13687       CheckForZeroSize = true;
13688     } else {
13689       // For C++ filter out types that cannot be referenced in C code.
13690       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
13691       CheckForZeroSize =
13692           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
13693           !CXXRecord->isDependentType() &&
13694           CXXRecord->isCLike();
13695     }
13696     if (CheckForZeroSize) {
13697       bool ZeroSize = true;
13698       bool IsEmpty = true;
13699       unsigned NonBitFields = 0;
13700       for (RecordDecl::field_iterator I = Record->field_begin(),
13701                                       E = Record->field_end();
13702            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
13703         IsEmpty = false;
13704         if (I->isUnnamedBitfield()) {
13705           if (I->getBitWidthValue(Context) > 0)
13706             ZeroSize = false;
13707         } else {
13708           ++NonBitFields;
13709           QualType FieldType = I->getType();
13710           if (FieldType->isIncompleteType() ||
13711               !Context.getTypeSizeInChars(FieldType).isZero())
13712             ZeroSize = false;
13713         }
13714       }
13715
13716       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
13717       // allowed in C++, but warn if its declaration is inside
13718       // extern "C" block.
13719       if (ZeroSize) {
13720         Diag(RecLoc, getLangOpts().CPlusPlus ?
13721                          diag::warn_zero_size_struct_union_in_extern_c :
13722                          diag::warn_zero_size_struct_union_compat)
13723           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
13724       }
13725
13726       // Structs without named members are extension in C (C99 6.7.2.1p7),
13727       // but are accepted by GCC.
13728       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
13729         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
13730                                diag::ext_no_named_members_in_struct_union)
13731           << Record->isUnion();
13732       }
13733     }
13734   } else {
13735     ObjCIvarDecl **ClsFields =
13736       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
13737     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
13738       ID->setEndOfDefinitionLoc(RBrac);
13739       // Add ivar's to class's DeclContext.
13740       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13741         ClsFields[i]->setLexicalDeclContext(ID);
13742         ID->addDecl(ClsFields[i]);
13743       }
13744       // Must enforce the rule that ivars in the base classes may not be
13745       // duplicates.
13746       if (ID->getSuperClass())
13747         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
13748     } else if (ObjCImplementationDecl *IMPDecl =
13749                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13750       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
13751       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
13752         // Ivar declared in @implementation never belongs to the implementation.
13753         // Only it is in implementation's lexical context.
13754         ClsFields[I]->setLexicalDeclContext(IMPDecl);
13755       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
13756       IMPDecl->setIvarLBraceLoc(LBrac);
13757       IMPDecl->setIvarRBraceLoc(RBrac);
13758     } else if (ObjCCategoryDecl *CDecl = 
13759                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13760       // case of ivars in class extension; all other cases have been
13761       // reported as errors elsewhere.
13762       // FIXME. Class extension does not have a LocEnd field.
13763       // CDecl->setLocEnd(RBrac);
13764       // Add ivar's to class extension's DeclContext.
13765       // Diagnose redeclaration of private ivars.
13766       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
13767       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13768         if (IDecl) {
13769           if (const ObjCIvarDecl *ClsIvar = 
13770               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
13771             Diag(ClsFields[i]->getLocation(), 
13772                  diag::err_duplicate_ivar_declaration); 
13773             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
13774             continue;
13775           }
13776           for (const auto *Ext : IDecl->known_extensions()) {
13777             if (const ObjCIvarDecl *ClsExtIvar
13778                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
13779               Diag(ClsFields[i]->getLocation(), 
13780                    diag::err_duplicate_ivar_declaration); 
13781               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
13782               continue;
13783             }
13784           }
13785         }
13786         ClsFields[i]->setLexicalDeclContext(CDecl);
13787         CDecl->addDecl(ClsFields[i]);
13788       }
13789       CDecl->setIvarLBraceLoc(LBrac);
13790       CDecl->setIvarRBraceLoc(RBrac);
13791     }
13792   }
13793
13794   if (Attr)
13795     ProcessDeclAttributeList(S, Record, Attr);
13796 }
13797
13798 /// \brief Determine whether the given integral value is representable within
13799 /// the given type T.
13800 static bool isRepresentableIntegerValue(ASTContext &Context,
13801                                         llvm::APSInt &Value,
13802                                         QualType T) {
13803   assert(T->isIntegralType(Context) && "Integral type required!");
13804   unsigned BitWidth = Context.getIntWidth(T);
13805   
13806   if (Value.isUnsigned() || Value.isNonNegative()) {
13807     if (T->isSignedIntegerOrEnumerationType()) 
13808       --BitWidth;
13809     return Value.getActiveBits() <= BitWidth;
13810   }  
13811   return Value.getMinSignedBits() <= BitWidth;
13812 }
13813
13814 // \brief Given an integral type, return the next larger integral type
13815 // (or a NULL type of no such type exists).
13816 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
13817   // FIXME: Int128/UInt128 support, which also needs to be introduced into 
13818   // enum checking below.
13819   assert(T->isIntegralType(Context) && "Integral type required!");
13820   const unsigned NumTypes = 4;
13821   QualType SignedIntegralTypes[NumTypes] = { 
13822     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
13823   };
13824   QualType UnsignedIntegralTypes[NumTypes] = { 
13825     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 
13826     Context.UnsignedLongLongTy
13827   };
13828   
13829   unsigned BitWidth = Context.getTypeSize(T);
13830   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
13831                                                         : UnsignedIntegralTypes;
13832   for (unsigned I = 0; I != NumTypes; ++I)
13833     if (Context.getTypeSize(Types[I]) > BitWidth)
13834       return Types[I];
13835   
13836   return QualType();
13837 }
13838
13839 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
13840                                           EnumConstantDecl *LastEnumConst,
13841                                           SourceLocation IdLoc,
13842                                           IdentifierInfo *Id,
13843                                           Expr *Val) {
13844   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13845   llvm::APSInt EnumVal(IntWidth);
13846   QualType EltTy;
13847
13848   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
13849     Val = nullptr;
13850
13851   if (Val)
13852     Val = DefaultLvalueConversion(Val).get();
13853
13854   if (Val) {
13855     if (Enum->isDependentType() || Val->isTypeDependent())
13856       EltTy = Context.DependentTy;
13857     else {
13858       SourceLocation ExpLoc;
13859       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
13860           !getLangOpts().MSVCCompat) {
13861         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
13862         // constant-expression in the enumerator-definition shall be a converted
13863         // constant expression of the underlying type.
13864         EltTy = Enum->getIntegerType();
13865         ExprResult Converted =
13866           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
13867                                            CCEK_Enumerator);
13868         if (Converted.isInvalid())
13869           Val = nullptr;
13870         else
13871           Val = Converted.get();
13872       } else if (!Val->isValueDependent() &&
13873                  !(Val = VerifyIntegerConstantExpression(Val,
13874                                                          &EnumVal).get())) {
13875         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
13876       } else {
13877         if (Enum->isFixed()) {
13878           EltTy = Enum->getIntegerType();
13879
13880           // In Obj-C and Microsoft mode, require the enumeration value to be
13881           // representable in the underlying type of the enumeration. In C++11,
13882           // we perform a non-narrowing conversion as part of converted constant
13883           // expression checking.
13884           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13885             if (getLangOpts().MSVCCompat) {
13886               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
13887               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13888             } else
13889               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
13890           } else
13891             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13892         } else if (getLangOpts().CPlusPlus) {
13893           // C++11 [dcl.enum]p5:
13894           //   If the underlying type is not fixed, the type of each enumerator
13895           //   is the type of its initializing value:
13896           //     - If an initializer is specified for an enumerator, the 
13897           //       initializing value has the same type as the expression.
13898           EltTy = Val->getType();
13899         } else {
13900           // C99 6.7.2.2p2:
13901           //   The expression that defines the value of an enumeration constant
13902           //   shall be an integer constant expression that has a value
13903           //   representable as an int.
13904
13905           // Complain if the value is not representable in an int.
13906           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
13907             Diag(IdLoc, diag::ext_enum_value_not_int)
13908               << EnumVal.toString(10) << Val->getSourceRange()
13909               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13910           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13911             // Force the type of the expression to 'int'.
13912             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
13913           }
13914           EltTy = Val->getType();
13915         }
13916       }
13917     }
13918   }
13919
13920   if (!Val) {
13921     if (Enum->isDependentType())
13922       EltTy = Context.DependentTy;
13923     else if (!LastEnumConst) {
13924       // C++0x [dcl.enum]p5:
13925       //   If the underlying type is not fixed, the type of each enumerator
13926       //   is the type of its initializing value:
13927       //     - If no initializer is specified for the first enumerator, the 
13928       //       initializing value has an unspecified integral type.
13929       //
13930       // GCC uses 'int' for its unspecified integral type, as does 
13931       // C99 6.7.2.2p3.
13932       if (Enum->isFixed()) {
13933         EltTy = Enum->getIntegerType();
13934       }
13935       else {
13936         EltTy = Context.IntTy;
13937       }
13938     } else {
13939       // Assign the last value + 1.
13940       EnumVal = LastEnumConst->getInitVal();
13941       ++EnumVal;
13942       EltTy = LastEnumConst->getType();
13943
13944       // Check for overflow on increment.
13945       if (EnumVal < LastEnumConst->getInitVal()) {
13946         // C++0x [dcl.enum]p5:
13947         //   If the underlying type is not fixed, the type of each enumerator
13948         //   is the type of its initializing value:
13949         //
13950         //     - Otherwise the type of the initializing value is the same as
13951         //       the type of the initializing value of the preceding enumerator
13952         //       unless the incremented value is not representable in that type,
13953         //       in which case the type is an unspecified integral type 
13954         //       sufficient to contain the incremented value. If no such type
13955         //       exists, the program is ill-formed.
13956         QualType T = getNextLargerIntegralType(Context, EltTy);
13957         if (T.isNull() || Enum->isFixed()) {
13958           // There is no integral type larger enough to represent this 
13959           // value. Complain, then allow the value to wrap around.
13960           EnumVal = LastEnumConst->getInitVal();
13961           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
13962           ++EnumVal;
13963           if (Enum->isFixed())
13964             // When the underlying type is fixed, this is ill-formed.
13965             Diag(IdLoc, diag::err_enumerator_wrapped)
13966               << EnumVal.toString(10)
13967               << EltTy;
13968           else
13969             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
13970               << EnumVal.toString(10);
13971         } else {
13972           EltTy = T;
13973         }
13974         
13975         // Retrieve the last enumerator's value, extent that type to the
13976         // type that is supposed to be large enough to represent the incremented
13977         // value, then increment.
13978         EnumVal = LastEnumConst->getInitVal();
13979         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13980         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
13981         ++EnumVal;        
13982         
13983         // If we're not in C++, diagnose the overflow of enumerator values,
13984         // which in C99 means that the enumerator value is not representable in
13985         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
13986         // permits enumerator values that are representable in some larger
13987         // integral type.
13988         if (!getLangOpts().CPlusPlus && !T.isNull())
13989           Diag(IdLoc, diag::warn_enum_value_overflow);
13990       } else if (!getLangOpts().CPlusPlus &&
13991                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13992         // Enforce C99 6.7.2.2p2 even when we compute the next value.
13993         Diag(IdLoc, diag::ext_enum_value_not_int)
13994           << EnumVal.toString(10) << 1;
13995       }
13996     }
13997   }
13998
13999   if (!EltTy->isDependentType()) {
14000     // Make the enumerator value match the signedness and size of the 
14001     // enumerator's type.
14002     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14003     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14004   }
14005   
14006   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14007                                   Val, EnumVal);
14008 }
14009
14010 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14011                                                 SourceLocation IILoc) {
14012   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14013       !getLangOpts().CPlusPlus)
14014     return SkipBodyInfo();
14015
14016   // We have an anonymous enum definition. Look up the first enumerator to
14017   // determine if we should merge the definition with an existing one and
14018   // skip the body.
14019   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14020                                          ForRedeclaration);
14021   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14022   if (!PrevECD)
14023     return SkipBodyInfo();
14024
14025   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14026   NamedDecl *Hidden;
14027   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14028     SkipBodyInfo Skip;
14029     Skip.Previous = Hidden;
14030     return Skip;
14031   }
14032
14033   return SkipBodyInfo();
14034 }
14035
14036 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14037                               SourceLocation IdLoc, IdentifierInfo *Id,
14038                               AttributeList *Attr,
14039                               SourceLocation EqualLoc, Expr *Val) {
14040   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14041   EnumConstantDecl *LastEnumConst =
14042     cast_or_null<EnumConstantDecl>(lastEnumConst);
14043
14044   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14045   // we find one that is.
14046   S = getNonFieldDeclScope(S);
14047
14048   // Verify that there isn't already something declared with this name in this
14049   // scope.
14050   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14051                                          ForRedeclaration);
14052   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14053     // Maybe we will complain about the shadowed template parameter.
14054     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14055     // Just pretend that we didn't see the previous declaration.
14056     PrevDecl = nullptr;
14057   }
14058
14059   // C++ [class.mem]p15:
14060   // If T is the name of a class, then each of the following shall have a name 
14061   // different from T:
14062   // - every enumerator of every member of class T that is an unscoped 
14063   // enumerated type
14064   if (!TheEnumDecl->isScoped())
14065     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14066                             DeclarationNameInfo(Id, IdLoc));
14067   
14068   EnumConstantDecl *New =
14069     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14070   if (!New)
14071     return nullptr;
14072
14073   if (PrevDecl) {
14074     // When in C++, we may get a TagDecl with the same name; in this case the
14075     // enum constant will 'hide' the tag.
14076     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14077            "Received TagDecl when not in C++!");
14078     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14079         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14080       if (isa<EnumConstantDecl>(PrevDecl))
14081         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14082       else
14083         Diag(IdLoc, diag::err_redefinition) << Id;
14084       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14085       return nullptr;
14086     }
14087   }
14088
14089   // Process attributes.
14090   if (Attr) ProcessDeclAttributeList(S, New, Attr);
14091
14092   // Register this decl in the current scope stack.
14093   New->setAccess(TheEnumDecl->getAccess());
14094   PushOnScopeChains(New, S);
14095
14096   ActOnDocumentableDecl(New);
14097
14098   return New;
14099 }
14100
14101 // Returns true when the enum initial expression does not trigger the
14102 // duplicate enum warning.  A few common cases are exempted as follows:
14103 // Element2 = Element1
14104 // Element2 = Element1 + 1
14105 // Element2 = Element1 - 1
14106 // Where Element2 and Element1 are from the same enum.
14107 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14108   Expr *InitExpr = ECD->getInitExpr();
14109   if (!InitExpr)
14110     return true;
14111   InitExpr = InitExpr->IgnoreImpCasts();
14112
14113   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14114     if (!BO->isAdditiveOp())
14115       return true;
14116     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14117     if (!IL)
14118       return true;
14119     if (IL->getValue() != 1)
14120       return true;
14121
14122     InitExpr = BO->getLHS();
14123   }
14124
14125   // This checks if the elements are from the same enum.
14126   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14127   if (!DRE)
14128     return true;
14129
14130   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14131   if (!EnumConstant)
14132     return true;
14133
14134   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14135       Enum)
14136     return true;
14137
14138   return false;
14139 }
14140
14141 namespace {
14142 struct DupKey {
14143   int64_t val;
14144   bool isTombstoneOrEmptyKey;
14145   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14146     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14147 };
14148
14149 static DupKey GetDupKey(const llvm::APSInt& Val) {
14150   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14151                 false);
14152 }
14153
14154 struct DenseMapInfoDupKey {
14155   static DupKey getEmptyKey() { return DupKey(0, true); }
14156   static DupKey getTombstoneKey() { return DupKey(1, true); }
14157   static unsigned getHashValue(const DupKey Key) {
14158     return (unsigned)(Key.val * 37);
14159   }
14160   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14161     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14162            LHS.val == RHS.val;
14163   }
14164 };
14165 } // end anonymous namespace
14166
14167 // Emits a warning when an element is implicitly set a value that
14168 // a previous element has already been set to.
14169 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14170                                         EnumDecl *Enum,
14171                                         QualType EnumType) {
14172   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14173     return;
14174   // Avoid anonymous enums
14175   if (!Enum->getIdentifier())
14176     return;
14177
14178   // Only check for small enums.
14179   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14180     return;
14181
14182   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14183   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14184
14185   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14186   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14187           ValueToVectorMap;
14188
14189   DuplicatesVector DupVector;
14190   ValueToVectorMap EnumMap;
14191
14192   // Populate the EnumMap with all values represented by enum constants without
14193   // an initialier.
14194   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14195     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14196
14197     // Null EnumConstantDecl means a previous diagnostic has been emitted for
14198     // this constant.  Skip this enum since it may be ill-formed.
14199     if (!ECD) {
14200       return;
14201     }
14202
14203     if (ECD->getInitExpr())
14204       continue;
14205
14206     DupKey Key = GetDupKey(ECD->getInitVal());
14207     DeclOrVector &Entry = EnumMap[Key];
14208
14209     // First time encountering this value.
14210     if (Entry.isNull())
14211       Entry = ECD;
14212   }
14213
14214   // Create vectors for any values that has duplicates.
14215   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14216     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14217     if (!ValidDuplicateEnum(ECD, Enum))
14218       continue;
14219
14220     DupKey Key = GetDupKey(ECD->getInitVal());
14221
14222     DeclOrVector& Entry = EnumMap[Key];
14223     if (Entry.isNull())
14224       continue;
14225
14226     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14227       // Ensure constants are different.
14228       if (D == ECD)
14229         continue;
14230
14231       // Create new vector and push values onto it.
14232       ECDVector *Vec = new ECDVector();
14233       Vec->push_back(D);
14234       Vec->push_back(ECD);
14235
14236       // Update entry to point to the duplicates vector.
14237       Entry = Vec;
14238
14239       // Store the vector somewhere we can consult later for quick emission of
14240       // diagnostics.
14241       DupVector.push_back(Vec);
14242       continue;
14243     }
14244
14245     ECDVector *Vec = Entry.get<ECDVector*>();
14246     // Make sure constants are not added more than once.
14247     if (*Vec->begin() == ECD)
14248       continue;
14249
14250     Vec->push_back(ECD);
14251   }
14252
14253   // Emit diagnostics.
14254   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14255                                   DupVectorEnd = DupVector.end();
14256        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14257     ECDVector *Vec = *DupVectorIter;
14258     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14259
14260     // Emit warning for one enum constant.
14261     ECDVector::iterator I = Vec->begin();
14262     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14263       << (*I)->getName() << (*I)->getInitVal().toString(10)
14264       << (*I)->getSourceRange();
14265     ++I;
14266
14267     // Emit one note for each of the remaining enum constants with
14268     // the same value.
14269     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14270       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14271         << (*I)->getName() << (*I)->getInitVal().toString(10)
14272         << (*I)->getSourceRange();
14273     delete Vec;
14274   }
14275 }
14276
14277 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14278                              bool AllowMask) const {
14279   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14280   assert(ED->isCompleteDefinition() && "expected enum definition");
14281
14282   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14283   llvm::APInt &FlagBits = R.first->second;
14284
14285   if (R.second) {
14286     for (auto *E : ED->enumerators()) {
14287       const auto &EVal = E->getInitVal();
14288       // Only single-bit enumerators introduce new flag values.
14289       if (EVal.isPowerOf2())
14290         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14291     }
14292   }
14293
14294   // A value is in a flag enum if either its bits are a subset of the enum's
14295   // flag bits (the first condition) or we are allowing masks and the same is
14296   // true of its complement (the second condition). When masks are allowed, we
14297   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14298   //
14299   // While it's true that any value could be used as a mask, the assumption is
14300   // that a mask will have all of the insignificant bits set. Anything else is
14301   // likely a logic error.
14302   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14303   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14304 }
14305
14306 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14307                          SourceLocation RBraceLoc, Decl *EnumDeclX,
14308                          ArrayRef<Decl *> Elements,
14309                          Scope *S, AttributeList *Attr) {
14310   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14311   QualType EnumType = Context.getTypeDeclType(Enum);
14312
14313   if (Attr)
14314     ProcessDeclAttributeList(S, Enum, Attr);
14315
14316   if (Enum->isDependentType()) {
14317     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14318       EnumConstantDecl *ECD =
14319         cast_or_null<EnumConstantDecl>(Elements[i]);
14320       if (!ECD) continue;
14321
14322       ECD->setType(EnumType);
14323     }
14324
14325     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14326     return;
14327   }
14328
14329   // TODO: If the result value doesn't fit in an int, it must be a long or long
14330   // long value.  ISO C does not support this, but GCC does as an extension,
14331   // emit a warning.
14332   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14333   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14334   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14335
14336   // Verify that all the values are okay, compute the size of the values, and
14337   // reverse the list.
14338   unsigned NumNegativeBits = 0;
14339   unsigned NumPositiveBits = 0;
14340
14341   // Keep track of whether all elements have type int.
14342   bool AllElementsInt = true;
14343
14344   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14345     EnumConstantDecl *ECD =
14346       cast_or_null<EnumConstantDecl>(Elements[i]);
14347     if (!ECD) continue;  // Already issued a diagnostic.
14348
14349     const llvm::APSInt &InitVal = ECD->getInitVal();
14350
14351     // Keep track of the size of positive and negative values.
14352     if (InitVal.isUnsigned() || InitVal.isNonNegative())
14353       NumPositiveBits = std::max(NumPositiveBits,
14354                                  (unsigned)InitVal.getActiveBits());
14355     else
14356       NumNegativeBits = std::max(NumNegativeBits,
14357                                  (unsigned)InitVal.getMinSignedBits());
14358
14359     // Keep track of whether every enum element has type int (very commmon).
14360     if (AllElementsInt)
14361       AllElementsInt = ECD->getType() == Context.IntTy;
14362   }
14363
14364   // Figure out the type that should be used for this enum.
14365   QualType BestType;
14366   unsigned BestWidth;
14367
14368   // C++0x N3000 [conv.prom]p3:
14369   //   An rvalue of an unscoped enumeration type whose underlying
14370   //   type is not fixed can be converted to an rvalue of the first
14371   //   of the following types that can represent all the values of
14372   //   the enumeration: int, unsigned int, long int, unsigned long
14373   //   int, long long int, or unsigned long long int.
14374   // C99 6.4.4.3p2:
14375   //   An identifier declared as an enumeration constant has type int.
14376   // The C99 rule is modified by a gcc extension 
14377   QualType BestPromotionType;
14378
14379   bool Packed = Enum->hasAttr<PackedAttr>();
14380   // -fshort-enums is the equivalent to specifying the packed attribute on all
14381   // enum definitions.
14382   if (LangOpts.ShortEnums)
14383     Packed = true;
14384
14385   if (Enum->isFixed()) {
14386     BestType = Enum->getIntegerType();
14387     if (BestType->isPromotableIntegerType())
14388       BestPromotionType = Context.getPromotedIntegerType(BestType);
14389     else
14390       BestPromotionType = BestType;
14391
14392     BestWidth = Context.getIntWidth(BestType);
14393   }
14394   else if (NumNegativeBits) {
14395     // If there is a negative value, figure out the smallest integer type (of
14396     // int/long/longlong) that fits.
14397     // If it's packed, check also if it fits a char or a short.
14398     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14399       BestType = Context.SignedCharTy;
14400       BestWidth = CharWidth;
14401     } else if (Packed && NumNegativeBits <= ShortWidth &&
14402                NumPositiveBits < ShortWidth) {
14403       BestType = Context.ShortTy;
14404       BestWidth = ShortWidth;
14405     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14406       BestType = Context.IntTy;
14407       BestWidth = IntWidth;
14408     } else {
14409       BestWidth = Context.getTargetInfo().getLongWidth();
14410
14411       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14412         BestType = Context.LongTy;
14413       } else {
14414         BestWidth = Context.getTargetInfo().getLongLongWidth();
14415
14416         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14417           Diag(Enum->getLocation(), diag::ext_enum_too_large);
14418         BestType = Context.LongLongTy;
14419       }
14420     }
14421     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14422   } else {
14423     // If there is no negative value, figure out the smallest type that fits
14424     // all of the enumerator values.
14425     // If it's packed, check also if it fits a char or a short.
14426     if (Packed && NumPositiveBits <= CharWidth) {
14427       BestType = Context.UnsignedCharTy;
14428       BestPromotionType = Context.IntTy;
14429       BestWidth = CharWidth;
14430     } else if (Packed && NumPositiveBits <= ShortWidth) {
14431       BestType = Context.UnsignedShortTy;
14432       BestPromotionType = Context.IntTy;
14433       BestWidth = ShortWidth;
14434     } else if (NumPositiveBits <= IntWidth) {
14435       BestType = Context.UnsignedIntTy;
14436       BestWidth = IntWidth;
14437       BestPromotionType
14438         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14439                            ? Context.UnsignedIntTy : Context.IntTy;
14440     } else if (NumPositiveBits <=
14441                (BestWidth = Context.getTargetInfo().getLongWidth())) {
14442       BestType = Context.UnsignedLongTy;
14443       BestPromotionType
14444         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14445                            ? Context.UnsignedLongTy : Context.LongTy;
14446     } else {
14447       BestWidth = Context.getTargetInfo().getLongLongWidth();
14448       assert(NumPositiveBits <= BestWidth &&
14449              "How could an initializer get larger than ULL?");
14450       BestType = Context.UnsignedLongLongTy;
14451       BestPromotionType
14452         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14453                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
14454     }
14455   }
14456
14457   // Loop over all of the enumerator constants, changing their types to match
14458   // the type of the enum if needed.
14459   for (auto *D : Elements) {
14460     auto *ECD = cast_or_null<EnumConstantDecl>(D);
14461     if (!ECD) continue;  // Already issued a diagnostic.
14462
14463     // Standard C says the enumerators have int type, but we allow, as an
14464     // extension, the enumerators to be larger than int size.  If each
14465     // enumerator value fits in an int, type it as an int, otherwise type it the
14466     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
14467     // that X has type 'int', not 'unsigned'.
14468
14469     // Determine whether the value fits into an int.
14470     llvm::APSInt InitVal = ECD->getInitVal();
14471
14472     // If it fits into an integer type, force it.  Otherwise force it to match
14473     // the enum decl type.
14474     QualType NewTy;
14475     unsigned NewWidth;
14476     bool NewSign;
14477     if (!getLangOpts().CPlusPlus &&
14478         !Enum->isFixed() &&
14479         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14480       NewTy = Context.IntTy;
14481       NewWidth = IntWidth;
14482       NewSign = true;
14483     } else if (ECD->getType() == BestType) {
14484       // Already the right type!
14485       if (getLangOpts().CPlusPlus)
14486         // C++ [dcl.enum]p4: Following the closing brace of an
14487         // enum-specifier, each enumerator has the type of its
14488         // enumeration.
14489         ECD->setType(EnumType);
14490       continue;
14491     } else {
14492       NewTy = BestType;
14493       NewWidth = BestWidth;
14494       NewSign = BestType->isSignedIntegerOrEnumerationType();
14495     }
14496
14497     // Adjust the APSInt value.
14498     InitVal = InitVal.extOrTrunc(NewWidth);
14499     InitVal.setIsSigned(NewSign);
14500     ECD->setInitVal(InitVal);
14501
14502     // Adjust the Expr initializer and type.
14503     if (ECD->getInitExpr() &&
14504         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14505       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14506                                                 CK_IntegralCast,
14507                                                 ECD->getInitExpr(),
14508                                                 /*base paths*/ nullptr,
14509                                                 VK_RValue));
14510     if (getLangOpts().CPlusPlus)
14511       // C++ [dcl.enum]p4: Following the closing brace of an
14512       // enum-specifier, each enumerator has the type of its
14513       // enumeration.
14514       ECD->setType(EnumType);
14515     else
14516       ECD->setType(NewTy);
14517   }
14518
14519   Enum->completeDefinition(BestType, BestPromotionType,
14520                            NumPositiveBits, NumNegativeBits);
14521
14522   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14523
14524   if (Enum->hasAttr<FlagEnumAttr>()) {
14525     for (Decl *D : Elements) {
14526       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14527       if (!ECD) continue;  // Already issued a diagnostic.
14528
14529       llvm::APSInt InitVal = ECD->getInitVal();
14530       if (InitVal != 0 && !InitVal.isPowerOf2() &&
14531           !IsValueInFlagEnum(Enum, InitVal, true))
14532         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14533           << ECD << Enum;
14534     }
14535   }
14536
14537   // Now that the enum type is defined, ensure it's not been underaligned.
14538   if (Enum->hasAttrs())
14539     CheckAlignasUnderalignment(Enum);
14540 }
14541
14542 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
14543                                   SourceLocation StartLoc,
14544                                   SourceLocation EndLoc) {
14545   StringLiteral *AsmString = cast<StringLiteral>(expr);
14546
14547   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
14548                                                    AsmString, StartLoc,
14549                                                    EndLoc);
14550   CurContext->addDecl(New);
14551   return New;
14552 }
14553
14554 static void checkModuleImportContext(Sema &S, Module *M,
14555                                      SourceLocation ImportLoc, DeclContext *DC,
14556                                      bool FromInclude = false) {
14557   SourceLocation ExternCLoc;
14558
14559   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14560     switch (LSD->getLanguage()) {
14561     case LinkageSpecDecl::lang_c:
14562       if (ExternCLoc.isInvalid())
14563         ExternCLoc = LSD->getLocStart();
14564       break;
14565     case LinkageSpecDecl::lang_cxx:
14566       break;
14567     }
14568     DC = LSD->getParent();
14569   }
14570
14571   while (isa<LinkageSpecDecl>(DC))
14572     DC = DC->getParent();
14573
14574   if (!isa<TranslationUnitDecl>(DC)) {
14575     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
14576                           ? diag::ext_module_import_not_at_top_level_noop
14577                           : diag::err_module_import_not_at_top_level_fatal)
14578         << M->getFullModuleName() << DC;
14579     S.Diag(cast<Decl>(DC)->getLocStart(),
14580            diag::note_module_import_not_at_top_level) << DC;
14581   } else if (!M->IsExternC && ExternCLoc.isValid()) {
14582     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
14583       << M->getFullModuleName();
14584     S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
14585   }
14586 }
14587
14588 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
14589   return checkModuleImportContext(*this, M, ImportLoc, CurContext);
14590 }
14591
14592 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 
14593                                    SourceLocation ImportLoc, 
14594                                    ModuleIdPath Path) {
14595   Module *Mod =
14596       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
14597                                    /*IsIncludeDirective=*/false);
14598   if (!Mod)
14599     return true;
14600
14601   VisibleModules.setVisible(Mod, ImportLoc);
14602
14603   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
14604
14605   // FIXME: we should support importing a submodule within a different submodule
14606   // of the same top-level module. Until we do, make it an error rather than
14607   // silently ignoring the import.
14608   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
14609     Diag(ImportLoc, diag::err_module_self_import)
14610         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
14611   else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
14612     Diag(ImportLoc, diag::err_module_import_in_implementation)
14613         << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
14614
14615   SmallVector<SourceLocation, 2> IdentifierLocs;
14616   Module *ModCheck = Mod;
14617   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
14618     // If we've run out of module parents, just drop the remaining identifiers.
14619     // We need the length to be consistent.
14620     if (!ModCheck)
14621       break;
14622     ModCheck = ModCheck->Parent;
14623     
14624     IdentifierLocs.push_back(Path[I].second);
14625   }
14626
14627   ImportDecl *Import = ImportDecl::Create(Context, 
14628                                           Context.getTranslationUnitDecl(),
14629                                           AtLoc.isValid()? AtLoc : ImportLoc, 
14630                                           Mod, IdentifierLocs);
14631   Context.getTranslationUnitDecl()->addDecl(Import);
14632   return Import;
14633 }
14634
14635 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
14636   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
14637
14638   // Determine whether we're in the #include buffer for a module. The #includes
14639   // in that buffer do not qualify as module imports; they're just an
14640   // implementation detail of us building the module.
14641   //
14642   // FIXME: Should we even get ActOnModuleInclude calls for those?
14643   bool IsInModuleIncludes =
14644       TUKind == TU_Module &&
14645       getSourceManager().isWrittenInMainFile(DirectiveLoc);
14646
14647   // If this module import was due to an inclusion directive, create an 
14648   // implicit import declaration to capture it in the AST.
14649   if (!IsInModuleIncludes) {
14650     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14651     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14652                                                      DirectiveLoc, Mod,
14653                                                      DirectiveLoc);
14654     TU->addDecl(ImportD);
14655     Consumer.HandleImplicitImportDecl(ImportD);
14656   }
14657   
14658   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
14659   VisibleModules.setVisible(Mod, DirectiveLoc);
14660 }
14661
14662 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
14663   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14664
14665   if (getLangOpts().ModulesLocalVisibility)
14666     VisibleModulesStack.push_back(std::move(VisibleModules));
14667   VisibleModules.setVisible(Mod, DirectiveLoc);
14668 }
14669
14670 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
14671   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14672
14673   if (getLangOpts().ModulesLocalVisibility) {
14674     VisibleModules = std::move(VisibleModulesStack.back());
14675     VisibleModulesStack.pop_back();
14676     VisibleModules.setVisible(Mod, DirectiveLoc);
14677   }
14678 }
14679
14680 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
14681                                                       Module *Mod) {
14682   // Bail if we're not allowed to implicitly import a module here.
14683   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
14684     return;
14685
14686   // Create the implicit import declaration.
14687   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14688   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14689                                                    Loc, Mod, Loc);
14690   TU->addDecl(ImportD);
14691   Consumer.HandleImplicitImportDecl(ImportD);
14692
14693   // Make the module visible.
14694   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
14695   VisibleModules.setVisible(Mod, Loc);
14696 }
14697
14698 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
14699                                       IdentifierInfo* AliasName,
14700                                       SourceLocation PragmaLoc,
14701                                       SourceLocation NameLoc,
14702                                       SourceLocation AliasNameLoc) {
14703   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
14704                                          LookupOrdinaryName);
14705   AsmLabelAttr *Attr =
14706       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
14707
14708   // If a declaration that:
14709   // 1) declares a function or a variable
14710   // 2) has external linkage
14711   // already exists, add a label attribute to it.
14712   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
14713     if (isDeclExternC(PrevDecl))
14714       PrevDecl->addAttr(Attr);
14715     else
14716       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
14717           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
14718   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
14719   } else
14720     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
14721 }
14722
14723 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
14724                              SourceLocation PragmaLoc,
14725                              SourceLocation NameLoc) {
14726   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
14727
14728   if (PrevDecl) {
14729     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
14730   } else {
14731     (void)WeakUndeclaredIdentifiers.insert(
14732       std::pair<IdentifierInfo*,WeakInfo>
14733         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
14734   }
14735 }
14736
14737 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
14738                                 IdentifierInfo* AliasName,
14739                                 SourceLocation PragmaLoc,
14740                                 SourceLocation NameLoc,
14741                                 SourceLocation AliasNameLoc) {
14742   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
14743                                     LookupOrdinaryName);
14744   WeakInfo W = WeakInfo(Name, NameLoc);
14745
14746   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
14747     if (!PrevDecl->hasAttr<AliasAttr>())
14748       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
14749         DeclApplyPragmaWeak(TUScope, ND, W);
14750   } else {
14751     (void)WeakUndeclaredIdentifiers.insert(
14752       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
14753   }
14754 }
14755
14756 Decl *Sema::getObjCDeclContext() const {
14757   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
14758 }
14759
14760 AvailabilityResult Sema::getCurContextAvailability() const {
14761   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
14762   if (!D)
14763     return AR_Available;
14764
14765   // If we are within an Objective-C method, we should consult
14766   // both the availability of the method as well as the
14767   // enclosing class.  If the class is (say) deprecated,
14768   // the entire method is considered deprecated from the
14769   // purpose of checking if the current context is deprecated.
14770   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
14771     AvailabilityResult R = MD->getAvailability();
14772     if (R != AR_Available)
14773       return R;
14774     D = MD->getClassInterface();
14775   }
14776   // If we are within an Objective-c @implementation, it
14777   // gets the same availability context as the @interface.
14778   else if (const ObjCImplementationDecl *ID =
14779             dyn_cast<ObjCImplementationDecl>(D)) {
14780     D = ID->getClassInterface();
14781   }
14782   // Recover from user error.
14783   return D ? D->getAvailability() : AR_Available;
14784 }